agentos

package
v1.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 12, 2026 License: Apache-2.0 Imports: 27 Imported by: 0

README

AgentOS - Production-Ready Agent Server

AgentOS is a production-ready HTTP server for managing and running AI agents built with Agno-Go.

Features

  • 🚀 RESTful API - Clean, intuitive API design
  • 💬 Session Management - Multi-turn conversation support
  • 🤖 Agent Registry - Dynamic agent registration and execution
  • 🔧 Tool Support - Agents can use tools for extended capabilities
  • 💾 Memory Management - Automatic conversation history management
  • 📊 Structured Logging - Built-in request logging with slog
  • High Performance - Built on Gin framework for speed
  • 🔒 Thread-Safe - Concurrent request handling

Quick Start

Basic Usage
package main

import (
    "context"
    "log"
    "os"
    "os/signal"
    "syscall"
    "time"

    "github.com/jholhewres/agent-go/pkg/agentgo/agent"
    "github.com/jholhewres/agent-go/pkg/agentgo/models/openai"
    "github.com/jholhewres/agent-go/pkg/agentos"
)

func main() {
    // Create an OpenAI model
    model, err := openai.New("gpt-4", openai.Config{
        APIKey: os.Getenv("OPENAI_API_KEY"),
    })
    if err != nil {
        log.Fatal(err)
    }

    // Create an agent
    ag, err := agent.New(agent.Config{
        Name:         "Assistant",
        Model:        model,
        Instructions: "You are a helpful assistant.",
    })
    if err != nil {
        log.Fatal(err)
    }

    // Create AgentOS server
    server, err := agentos.NewServer(&agentos.Config{
        Address: ":8080",
        Debug:   true,
    })
    if err != nil {
        log.Fatal(err)
    }

    // Register the agent
    if err := server.RegisterAgent("assistant", ag); err != nil {
        log.Fatal(err)
    }

    // Start server in a goroutine
    go func() {
        if err := server.Start(); err != nil {
            log.Printf("Server error: %v", err)
        }
    }()

    log.Println("AgentOS server started on :8080")
    log.Println("Try: curl -X POST http://localhost:8080/api/v1/agents/assistant/run -H 'Content-Type: application/json' -d '{\"input\":\"Hello!\"}'")

    // Wait for interrupt signal
    quit := make(chan os.Signal, 1)
    signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
    <-quit

    log.Println("Shutting down server...")
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()

    if err := server.Shutdown(ctx); err != nil {
        log.Printf("Server shutdown error: %v", err)
    }
    log.Println("Server stopped")
}

API Documentation

Full OpenAPI 3.0 specification is available in openapi.yaml.

Streaming Events

AgentOS supports Server-Sent Events (SSE) for monitoring agent execution in real time via:

POST /api/v1/agents/{agent_id}/run/stream

Query parameter types can be used to filter event categories (e.g. types=token,complete,reasoning).
Each event is delivered in the following structure:

  • run_start: Input payload and session metadata.
  • reasoning: Structured reasoning segments (content, token_count, redacted_content) produced by supported reasoning models.
  • token: Individual streaming tokens for response generation.
  • tool_call: Tool invocation details (name, arguments, result).
  • complete: Final response content, elapsed duration, aggregated token usage (including reasoning token estimates).
  • error: Rich error payload when execution fails.

📦 需要将事件转发到 Logfire 或其他可观测性平台?请参考 cmd/examples/logfire_observability 示例(使用 go run -tags logfire .)以及文档 docs/release/logfire_observability.md

Refer to pkg/agentos/events.go for the latest schema definitions.

Endpoints
Health Check
GET /health

Returns server health status.

Response:

{
  "status": "healthy",
  "service": "agentos",
  "time": 1704067200
}
Sessions

Create Session

POST /api/v1/sessions
Content-Type: application/json

{
  "agent_id": "assistant",
  "user_id": "user-123",
  "name": "Customer Support"
}

Get Session

GET /api/v1/sessions/{session_id}

Update Session

PUT /api/v1/sessions/{session_id}
Content-Type: application/json

{
  "name": "Updated Name",
  "metadata": {"key": "value"}
}

Delete Session

DELETE /api/v1/sessions/{session_id}

List Sessions

GET /api/v1/sessions?agent_id=assistant&user_id=user-123
Agents

List Agents

GET /api/v1/agents

Response:

{
  "agents": [
    {
      "id": "assistant",
      "name": "Assistant"
    }
  ],
  "count": 1
}

Run Agent

POST /api/v1/agents/{agent_id}/run
Content-Type: application/json

{
  "input": "What is the weather in SF?",
  "session_id": "optional-session-id",
  "media": [
    {
      "type": "image",
      "url": "https://example.com/photo.png"
    }
  ]
}

Response:

{
  "content": "I don't have access to real-time weather data...",
  "session_id": "optional-session-id",
  "metadata": {
    "agent_id": "assistant",
    "media": [
      {
        "type": "image",
        "url": "https://example.com/photo.png"
      }
    ]
  }
}

Media support: when media attachments are supplied, AgentOS validates the payload and keeps the attachment metadata alongside the run so downstream consumers can render or audit the original assets. Pure-media requests (no input text) are accepted as long as at least one attachment is present.

Configuration

Server Config
type Config struct {
    // Server address (default: :8080)
    Address string

    // Session storage (default: memory storage)
    SessionStorage session.Storage

    // Logger (default: slog.Default())
    Logger *slog.Logger

    // Enable debug mode
    Debug bool

    // CORS settings
    AllowOrigins []string
    AllowMethods []string
    AllowHeaders []string

    // Request timeout (default: 30s)
    RequestTimeout time.Duration

    // Max request size in bytes (default: 10MB)
    MaxRequestSize int64
}
Example with Custom Config
server, err := agentos.NewServer(&agentos.Config{
    Address: ":9090",
    Debug:   true,
    AllowOrigins: []string{"https://example.com"},
    RequestTimeout: 60 * time.Second,
    Logger: slog.New(slog.NewJSONHandler(os.Stdout, nil)),
})

Advanced Usage

With Multiple Agents
// Register multiple agents
server.RegisterAgent("customer-support", customerSupportAgent)
server.RegisterAgent("sales-assistant", salesAgent)
server.RegisterAgent("technical-support", techSupportAgent)

// Clients can now call:
// POST /api/v1/agents/customer-support/run
// POST /api/v1/agents/sales-assistant/run
// POST /api/v1/agents/technical-support/run
With Tool-Enabled Agents
import (
    "github.com/jholhewres/agent-go/pkg/agentgo/tools/calculator"
    "github.com/jholhewres/agent-go/pkg/agentgo/tools/http"
)

// Create agent with tools
ag, err := agent.New(agent.Config{
    Name:  "ToolAgent",
    Model: model,
    Toolkits: []toolkit.Toolkit{
        calculator.New(),
        http.New(),
    },
    Instructions: "You can perform calculations and make HTTP requests.",
})

server.RegisterAgent("tool-agent", ag)
With Custom Session Storage
import "github.com/jholhewres/agent-go/pkg/agentgo/session"

// Use custom storage (e.g., PostgreSQL, Redis)
storage := session.NewPostgresStorage(connString)

server, err := agentos.NewServer(&agentos.Config{
    SessionStorage: storage,
})

Testing

The package includes comprehensive tests:

# Run all tests
go test ./pkg/agentos/ -v

# Run with coverage
go test ./pkg/agentos/ -cover

# Generate coverage report
go test ./pkg/agentos/ -coverprofile=coverage.out
go tool cover -html=coverage.out

Current test coverage: 65.0%

  • 16 Registry tests (100% coverage)
  • 13 Server/API tests
  • Session management tests
  • Agent execution tests

Architecture

┌─────────────────────────────────────────┐
│         HTTP Client (curl/SDK)          │
└────────────────┬────────────────────────┘
                 │
                 ▼
┌─────────────────────────────────────────┐
│          Gin HTTP Server                │
│  ┌─────────────────────────────────┐   │
│  │      Middleware Stack           │   │
│  │  - Logger                        │   │
│  │  - CORS                          │   │
│  │  - Timeout                       │   │
│  │  - Recovery                      │   │
│  └─────────────────────────────────┘   │
└────────────────┬────────────────────────┘
                 │
    ┌────────────┼────────────┐
    │            │            │
    ▼            ▼            ▼
┌────────┐  ┌─────────┐  ┌──────────┐
│Session │  │ Agent   │  │  Health  │
│Handler │  │ Handler │  │  Handler │
└───┬────┘  └────┬────┘  └──────────┘
    │            │
    ▼            ▼
┌─────────┐  ┌──────────┐
│ Session │  │  Agent   │
│ Storage │  │ Registry │
└─────────┘  └────┬─────┘
                   │
                   ▼
              ┌─────────┐
              │  Agent  │
              │ (Agno)  │
              └────┬────┘
                   │
        ┌──────────┼──────────┐
        ▼          ▼          ▼
    ┌───────┐  ┌──────┐  ┌────────┐
    │ Model │  │Tools │  │ Memory │
    └───────┘  └──────┘  └────────┘

Error Handling

AgentOS uses structured error responses:

{
  "error": "agent not found",
  "message": "agent with ID 'non-existent' not found",
  "code": "AGENT_NOT_FOUND"
}
Error Codes
  • INVALID_REQUEST - Invalid request format or missing required fields
  • AGENT_NOT_FOUND - Requested agent does not exist in registry
  • SESSION_NOT_FOUND - Requested session does not exist
  • EXECUTION_ERROR - Agent execution failed

Performance

AgentOS is built for high-performance agent serving:

  • Concurrent Requests: Thread-safe agent registry with RWMutex
  • Low Latency: Gin framework for fast routing
  • Memory Efficient: Reuses agent instances across requests
  • Graceful Shutdown: Properly closes resources on shutdown

Deployment

Docker
FROM golang:1.21-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN go build -o agentos cmd/server/main.go

FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /app/agentos .
EXPOSE 8080
CMD ["./agentos"]
Docker Compose

See docker-compose.yml for full setup.

Environment Variables
# Required
OPENAI_API_KEY=sk-...

# Optional
AGENTOS_ADDRESS=:8080
AGENTOS_DEBUG=false
ANTHROPIC_API_KEY=sk-ant-...

Logging

AgentOS uses structured logging with log/slog:

2025/10/02 00:15:15 INFO request method=POST path=/api/v1/sessions status=201 duration=174.875µs ip=192.168.1.1
2025/10/02 00:15:15 INFO session created session_id=c1110224-9676-41eb-842a-611a205c28c3 agent_id=assistant
2025/10/02 00:15:16 INFO agent run requested agent_id=assistant input="Hello!" session_id=c1110224...
2025/10/02 00:15:17 INFO agent run completed agent_id=assistant content_length=142

Best Practices

  1. Use Sessions for Multi-Turn Conversations

    • Create a session once, reuse for multiple agent runs
    • Sessions automatically manage conversation history
  2. Register Agents at Startup

    • Register all agents before starting the server
    • Agent registry is thread-safe but best to register early
  3. Handle Errors Gracefully

    • Check response status codes
    • Use error codes to determine appropriate action
  4. Set Appropriate Timeouts

    • Default is 30s, adjust based on your agent complexity
    • LLM calls can take time, especially with tools
  5. Monitor Memory Usage

    • Sessions store conversation history
    • Consider implementing session cleanup for long-running servers

Contributing

Contributions are welcome! Please ensure:

  1. All tests pass: go test ./pkg/agentos/
  2. Code is formatted: make fmt
  3. Coverage is maintained or improved

License

MIT License - See LICENSE for details.

  • Agno-Go - Core agent framework
  • Agno - Python implementation

Support

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func TeamToolDefinitions

func TeamToolDefinitions(t *team.Team) []models.ToolDefinition

TeamToolDefinitions returns the effective tool definitions available to a team. It aggregates tools from all member agents' toolkits and de-duplicates them by function name so the result can be used for OS schema/tooling purposes.

Types

type AddContentRequest

type AddContentRequest struct {
	// Content 文本内容
	// Content is the text content
	Content string `json:"content" binding:"required"`

	// Metadata 元数据
	// Metadata is the metadata
	Metadata map[string]interface{} `json:"metadata,omitempty"`

	// ChunkerType 分块器类型(character/sentence/paragraph)
	// ChunkerType is the chunker type
	ChunkerType string `json:"chunker_type,omitempty"`

	// ChunkSize 块大小
	// ChunkSize is the chunk size
	ChunkSize int `json:"chunk_size,omitempty"`

	// ChunkOverlap specifies overlap between consecutive chunks
	ChunkOverlap int `json:"chunk_overlap,omitempty"`

	// CollectionName 集合名称
	// CollectionName is the collection name
	CollectionName string `json:"collection_name,omitempty"`
}

AddContentRequest 表示添加内容请求(P2 任务,预留) AddContentRequest represents an add content request (P2 task, reserved)

type AddContentResponse

type AddContentResponse struct {
	// DocumentIDs 添加的文档 ID 列表
	// DocumentIDs is the list of added document IDs
	DocumentIDs []string `json:"document_ids"`

	// ChunkCount 生成的块数量
	// ChunkCount is the number of chunks generated
	ChunkCount int `json:"chunk_count"`

	// ChunkerType 使用的分块器类型
	// ChunkerType is the chunker type used
	ChunkerType string `json:"chunker_type"`

	// Collection 使用的集合名称
	// Collection is the collection that stored the documents
	Collection string `json:"collection,omitempty"`

	// Message 处理消息
	// Message is the processing message
	Message string `json:"message"`
}

AddContentResponse 表示添加内容的响应 AddContentResponse represents the response for adding content

type AgentRegistry

type AgentRegistry struct {
	// contains filtered or unexported fields
}

AgentRegistry manages registered agents

func NewAgentRegistry

func NewAgentRegistry() *AgentRegistry

NewAgentRegistry creates a new agent registry

func (*AgentRegistry) Clear

func (r *AgentRegistry) Clear()

Clear removes all agents from the registry

func (*AgentRegistry) Count

func (r *AgentRegistry) Count() int

Count returns the number of registered agents

func (*AgentRegistry) Exists

func (r *AgentRegistry) Exists(agentID string) bool

Exists checks if an agent with the given ID is registered

func (*AgentRegistry) Get

func (r *AgentRegistry) Get(agentID string) (*agent.Agent, error)

Get retrieves an agent by ID

func (*AgentRegistry) GetIDs

func (r *AgentRegistry) GetIDs() []string

GetIDs returns a list of all registered agent IDs

func (*AgentRegistry) List

func (r *AgentRegistry) List() map[string]*agent.Agent

List returns all registered agents

func (*AgentRegistry) Register

func (r *AgentRegistry) Register(agentID string, ag *agent.Agent) error

Register registers an agent with the given ID

func (*AgentRegistry) Unregister

func (r *AgentRegistry) Unregister(agentID string) error

Unregister removes an agent from the registry

type AgentRunRequest

type AgentRunRequest struct {
	Input      string             `json:"input"`
	SessionID  string             `json:"session_id,omitempty"`
	Stream     bool               `json:"stream,omitempty"`
	Media      interface{}        `json:"media,omitempty"`
	RunContext *RunContextRequest `json:"run_context,omitempty"`
}

AgentRunRequest represents a request to run an agent

type AgentRunResponse

type AgentRunResponse struct {
	RunID     string                 `json:"run_id,omitempty"`
	Status    agent.RunStatus        `json:"status,omitempty"`
	Content   string                 `json:"content"`
	SessionID string                 `json:"session_id,omitempty"`
	Metadata  map[string]interface{} `json:"metadata,omitempty"`
}

AgentRunResponse represents the response from running an agent

type ChunkerInfo

type ChunkerInfo struct {
	// Name 分块器名称
	// Name is the chunker name
	Name string `json:"name"`

	// Description 分块器描述
	// Description is the chunker description
	Description string `json:"description"`

	// DefaultChunkSize 默认块大小
	// DefaultChunkSize is the default chunk size
	DefaultChunkSize int `json:"default_chunk_size,omitempty"`

	// DefaultOverlap 默认重叠大小
	// DefaultOverlap is the default overlap size
	DefaultOverlap int `json:"default_overlap,omitempty"`

	// Metadata describes additional chunker-specific configuration.
	Metadata map[string]interface{} `json:"metadata,omitempty"`
}

ChunkerInfo 表示分块器信息 ChunkerInfo represents chunker information

type CompleteData

type CompleteData struct {
	// Output 输出内容
	// Output is the output content
	Output string `json:"output"`

	// Duration 运行时长(秒)
	// Duration is the run duration in seconds
	Duration float64 `json:"duration"`

	// TokenCount 令牌数量(可选)
	// TokenCount is the token count (optional)
	TokenCount int `json:"token_count,omitempty"`

	// Reasoning 推理摘要(可选)
	// Reasoning is an optional reasoning summary
	Reasoning *ReasoningSummary `json:"reasoning,omitempty"`

	// Usage 用量统计(可选)
	// Usage provides usage statistics (optional)
	Usage *UsageMetrics `json:"usage,omitempty"`

	// Status 运行状态
	Status string `json:"status,omitempty"`

	// CacheHit 缓存命中
	CacheHit bool `json:"cache_hit,omitempty"`

	// RunID 运行标识
	RunID string `json:"run_id,omitempty"`

	// CancellationReason 取消原因
	CancellationReason string `json:"cancellation_reason,omitempty"`
}

CompleteData 完成事件数据 CompleteData is the data for complete event

type Config

type Config struct {
	// Server address (default: :8080)
	// 服务器地址 (默认: :8080)
	Address string

	// API route prefix (e.g., "/api/v1", "/chat", empty for no prefix)
	// API 路由前缀 (例如: "/api/v1", "/chat", 空字符串表示无前缀)
	Prefix string

	// Session storage
	// Session 存储
	SessionStorage session.Storage

	// Logger
	// 日志记录器
	Logger *slog.Logger

	// Enable debug mode
	// 启用调试模式
	Debug bool

	// CORS settings
	// CORS 设置
	AllowOrigins []string
	AllowMethods []string
	AllowHeaders []string

	// Request timeout
	// 请求超时时间
	RequestTimeout time.Duration

	// Max request size (in bytes)
	// 最大请求大小 (字节)
	MaxRequestSize int64

	// VectorDBConfig 向量数据库配置(新增)
	// VectorDBConfig is the vector database configuration (new)
	VectorDBConfig *VectorDBConfig

	// EmbeddingConfig 嵌入模型配置(新增)
	// EmbeddingConfig is the embedding model configuration (new)
	EmbeddingConfig *EmbeddingConfig

	// KnowledgeAPI 知识 API 行为控制
	// KnowledgeAPI configures knowledge endpoints behaviour
	KnowledgeAPI *KnowledgeAPIOptions

	// SummaryManager 会话摘要管理器
	SummaryManager *session.SummaryManager

	// HealthPath allows overriding the health check endpoint path.
	HealthPath string
}

Config holds server configuration Config 持有服务器配置

type CreateSessionRequest

type CreateSessionRequest struct {
	AgentID    string                 `json:"agent_id" binding:"required"`
	UserID     string                 `json:"user_id,omitempty"`
	TeamID     string                 `json:"team_id,omitempty"`
	WorkflowID string                 `json:"workflow_id,omitempty"`
	Name       string                 `json:"name,omitempty"`
	Metadata   map[string]interface{} `json:"metadata,omitempty"`
}

CreateSessionRequest represents the request to create a new session

type EmbeddingConfig

type EmbeddingConfig struct {
	// Provider 提供商(openai)
	// Provider is the provider
	Provider string

	// APIKey API 密钥
	// APIKey is the API key
	APIKey string

	// Model 模型名称
	// Model is the model name
	Model string

	// BaseURL API 基础 URL
	// BaseURL is the API base URL
	BaseURL string
}

EmbeddingConfig 嵌入模型配置 EmbeddingConfig is the embedding model configuration

type EmbeddingModelInfo

type EmbeddingModelInfo struct {
	// Provider 提供商(openai, etc.)
	// Provider is the model provider
	Provider string `json:"provider"`

	// Model 模型名称
	// Model is the model name
	Model string `json:"model"`

	// Dimensions 嵌入维度
	// Dimensions is the embedding dimensions
	Dimensions int `json:"dimensions"`
}

EmbeddingModelInfo 表示嵌入模型信息 EmbeddingModelInfo represents embedding model information

type ErrorData

type ErrorData struct {
	// Error 错误消息
	// Error is the error message
	Error string `json:"error"`

	// Code 错误代码
	// Code is the error code
	Code string `json:"code,omitempty"`

	// Details 错误详情
	// Details are error details
	Details interface{} `json:"details,omitempty"`
}

ErrorData 错误事件数据 ErrorData is the data for error event

type ErrorResponse

type ErrorResponse struct {
	Status  string `json:"status,omitempty"` // "error"
	Error   string `json:"error"`
	Message string `json:"message,omitempty"`
	Code    string `json:"code,omitempty"`
}

ErrorResponse represents an error response

type Event

type Event struct {
	// Type 事件类型
	// Type is the event type
	Type EventType `json:"type"`

	// Timestamp 事件时间戳
	// Timestamp is the event timestamp
	Timestamp time.Time `json:"timestamp"`

	// Data 事件数据
	// Data is the event data
	Data interface{} `json:"data,omitempty"`

	// SessionID 会话 ID(可选)
	// SessionID is the session ID (optional)
	SessionID string `json:"session_id,omitempty"`

	// AgentID Agent ID(可选)
	// AgentID is the agent ID (optional)
	AgentID string `json:"agent_id,omitempty"`

	// RunContextID 运行上下文 ID(可选,用于事件关联)
	// RunContextID is the run context identifier for correlating events (optional)
	RunContextID string `json:"run_context_id,omitempty"`
}

Event 表示一个事件 Event represents an event

func NewEvent

func NewEvent(eventType EventType, data interface{}) *Event

NewEvent 创建一个新事件 NewEvent creates a new event

func (*Event) ToSSE

func (e *Event) ToSSE() string

ToSSE 将事件转换为 SSE 格式 ToSSE converts event to SSE format

type EventFilter

type EventFilter struct {
	// Types 允许的事件类型(如果为空则允许所有)
	// Types are the allowed event types (if empty, all types are allowed)
	Types map[EventType]bool
}

EventFilter 事件过滤器 EventFilter is an event filter

func NewEventFilter

func NewEventFilter(types []string) *EventFilter

NewEventFilter 创建事件过滤器 NewEventFilter creates an event filter from a list of type strings

func (*EventFilter) ShouldSend

func (f *EventFilter) ShouldSend(event *Event) bool

ShouldSend 判断是否应该发送此事件 ShouldSend determines if the event should be sent

type EventType

type EventType string

EventType 表示事件类型 EventType represents the type of event

const (
	// EventRunStart Agent 运行开始
	// EventRunStart indicates agent run has started
	EventRunStart EventType = "run_start"

	// EventReasoning 推理事件
	// EventReasoning indicates reasoning content has been produced
	EventReasoning EventType = "reasoning"

	// EventToolCall 工具调用事件
	// EventToolCall indicates a tool call event
	EventToolCall EventType = "tool_call"

	// EventToken 令牌生成事件(流式输出)
	// EventToken indicates a token generation event (streaming)
	EventToken EventType = "token"

	// EventStepStart 步骤开始
	// EventStepStart indicates a step has started
	EventStepStart EventType = "step_start"

	// EventStepEnd 步骤结束
	// EventStepEnd indicates a step has ended
	EventStepEnd EventType = "step_end"

	// EventError 错误事件
	// EventError indicates an error occurred
	EventError EventType = "error"

	// EventComplete 运行完成
	// EventComplete indicates run has completed
	EventComplete EventType = "complete"
)

type KnowledgeAPIOptions

type KnowledgeAPIOptions struct {
	// DisableSearch 禁用搜索端点
	DisableSearch bool

	// DisableIngestion 禁用入库端点
	DisableIngestion bool

	// EnableHealth 暴露健康检查端点
	EnableHealth bool

	// DefaultLimit 搜索默认条数
	DefaultLimit int

	// MaxLimit 搜索最大条数
	MaxLimit int

	// SearchTimeout 搜索超时时间
	SearchTimeout time.Duration

	// IngestionTimeout 入库超时时间
	IngestionTimeout time.Duration

	// HealthTimeout 健康检查超时时间
	HealthTimeout time.Duration

	// AllowedCollections 允许的集合列表 (为空时仅默认集合)
	AllowedCollections []string

	// AllowAllCollections 是否允许任意集合
	AllowAllCollections bool

	// AllowedSourceSchemes 允许的来源 URL scheme(为空表示不限制)
	AllowedSourceSchemes []string
}

KnowledgeAPIOptions controls knowledge endpoint behaviour

type KnowledgeConfigResponse

type KnowledgeConfigResponse struct {
	// AvailableChunkers 可用的分块器列表
	// AvailableChunkers is the list of available chunkers
	AvailableChunkers []ChunkerInfo `json:"available_chunkers"`

	// AvailableVectorDBs 可用的向量数据库列表
	// AvailableVectorDBs is the list of available vector databases
	AvailableVectorDBs []string `json:"available_vector_dbs"`

	// DefaultChunker 默认分块器
	// DefaultChunker is the default chunker
	DefaultChunker string `json:"default_chunker"`

	// DefaultVectorDB 默认向量数据库
	// DefaultVectorDB is the default vector database
	DefaultVectorDB string `json:"default_vector_db"`

	// EmbeddingModel 嵌入模型信息
	// EmbeddingModel is the embedding model information
	EmbeddingModel EmbeddingModelInfo `json:"embedding_model"`

	// Features 功能开关
	Features KnowledgeFeatures `json:"features"`

	// Limits 搜索限制
	Limits KnowledgeLimits `json:"limits"`

	// DefaultCollection 默认集合
	DefaultCollection string `json:"default_collection"`

	// AllowedCollections 允许的集合列表
	AllowedCollections []string `json:"allowed_collections,omitempty"`

	// AllowedSourceSchemes 允许的来源 URL scheme
	AllowedSourceSchemes []string `json:"allowed_source_schemes,omitempty"`
}

KnowledgeConfigResponse 表示知识库配置响应 KnowledgeConfigResponse represents the knowledge configuration response

type KnowledgeFeatures

type KnowledgeFeatures struct {
	SearchEnabled    bool `json:"search_enabled"`
	IngestionEnabled bool `json:"ingestion_enabled"`
	HealthEnabled    bool `json:"health_enabled"`
}

KnowledgeFeatures describes enabled capabilities.

type KnowledgeLimits

type KnowledgeLimits struct {
	DefaultLimit int `json:"default_limit"`
	MaxLimit     int `json:"max_limit"`
}

KnowledgeLimits captures pagination defaults and caps.

type KnowledgeService

type KnowledgeService struct {
	// contains filtered or unexported fields
}

KnowledgeService 封装知识库操作 KnowledgeService encapsulates knowledge operations

func NewKnowledgeService

func NewKnowledgeService(vdb vectordb.VectorDB, embFunc vectordb.EmbeddingFunction, config KnowledgeServiceConfig) *KnowledgeService

NewKnowledgeService 创建知识库服务 NewKnowledgeService creates a new knowledge service

type KnowledgeServiceConfig

type KnowledgeServiceConfig struct {
	// DefaultLimit 默认返回结果数量
	// DefaultLimit is the default number of results to return
	DefaultLimit int

	// MaxLimit 最大返回结果数量
	// MaxLimit is the maximum number of results to return
	MaxLimit int

	// DefaultChunkerType 默认分块器类型
	// DefaultChunkerType is the default chunker type
	DefaultChunkerType string

	// DefaultChunkSize 默认块大小
	// DefaultChunkSize is the default chunk size
	DefaultChunkSize int

	// DefaultOverlap 默认重叠大小
	// DefaultOverlap is the default overlap size
	DefaultOverlap int

	// EmbeddingProvider 嵌入模型提供商
	// EmbeddingProvider is the embedding model provider
	EmbeddingProvider string

	// EmbeddingModel 嵌入模型名称
	// EmbeddingModel is the embedding model name
	EmbeddingModel string

	// EmbeddingDimensions 嵌入维度
	// EmbeddingDimensions is the embedding dimensions
	EmbeddingDimensions int

	// EnableSearch 是否启用搜索
	EnableSearch bool

	// EnableIngestion 是否启用知识入库
	EnableIngestion bool

	// EnableHealth 是否启用健康检查
	EnableHealth bool

	// SearchTimeout 搜索超时时间
	SearchTimeout time.Duration

	// IngestionTimeout 入库超时时间
	IngestionTimeout time.Duration

	// HealthTimeout 健康检查超时时间
	HealthTimeout time.Duration

	// DefaultCollection 默认集合名称
	DefaultCollection string

	// AllowedCollections 允许访问的集合列表
	AllowedCollections []string

	// AllowAllCollections 是否允许任意集合
	AllowAllCollections bool

	// AllowedSourceSchemes 允许的来源 URL scheme
	AllowedSourceSchemes []string
}

KnowledgeServiceConfig 知识库服务配置 KnowledgeServiceConfig is the knowledge service configuration

type PaginationMeta

type PaginationMeta struct {
	// TotalCount 总结果数(注意:向量数据库可能不支持精确计数)
	// TotalCount is the total number of results
	TotalCount int `json:"total_count"`

	// Page 当前页码(基于 offset 和 limit 计算)
	// Page is the current page number
	Page int `json:"page"`

	// PageSize 每页大小
	// PageSize is the number of results per page
	PageSize int `json:"page_size"`

	// TotalPages 总页数(基于 total_count 和 page_size 计算)
	// TotalPages is the total number of pages
	TotalPages int `json:"total_pages"`

	// Offset 当前偏移量
	Offset int `json:"offset"`

	// HasMore 是否还有更多结果
	HasMore bool `json:"has_more"`

	// NextOffset 下一页的偏移量
	NextOffset int `json:"next_offset,omitempty"`
}

PaginationMeta 表示分页元数据 PaginationMeta represents pagination metadata

type ReasoningData

type ReasoningData struct {
	Content         string  `json:"content"`
	TokenCount      *int    `json:"token_count,omitempty"`
	RedactedContent *string `json:"redacted_content,omitempty"`
	MessageIndex    int     `json:"message_index"`
	Model           string  `json:"model,omitempty"`
	Provider        string  `json:"provider,omitempty"`
}

ReasoningData 推理事件数据 ReasoningData is the payload for reasoning events

type ReasoningSummary

type ReasoningSummary struct {
	Content         string  `json:"content"`
	TokenCount      *int    `json:"token_count,omitempty"`
	RedactedContent *string `json:"redacted_content,omitempty"`
	Model           string  `json:"model,omitempty"`
	Provider        string  `json:"provider,omitempty"`
}

ReasoningSummary provides a compact reasoning representation

type ReuseSessionRequest

type ReuseSessionRequest struct {
	AgentID    string `json:"agent_id,omitempty"`
	TeamID     string `json:"team_id,omitempty"`
	WorkflowID string `json:"workflow_id,omitempty"`
	UserID     string `json:"user_id,omitempty"`
}

ReuseSessionRequest allows attaching an existing session to other entities.

type RunContextRequest

type RunContextRequest struct {
	RunID       string                 `json:"run_id,omitempty"`
	ParentRunID string                 `json:"parent_run_id,omitempty"`
	SessionID   string                 `json:"session_id,omitempty"`
	UserID      string                 `json:"user_id,omitempty"`
	WorkflowID  string                 `json:"workflow_id,omitempty"`
	TeamID      string                 `json:"team_id,omitempty"`
	Metadata    map[string]interface{} `json:"metadata,omitempty"`
}

RunContextRequest captures the optional run context payload from clients.

type RunStartData

type RunStartData struct {
	// Input 输入内容
	// Input is the input content
	Input string `json:"input"`

	// SessionID 会话 ID
	// SessionID is the session ID
	SessionID string `json:"session_id,omitempty"`

	// Media 附带的媒体资源
	// Media contains normalized media attachments
	Media []media.Attachment `json:"media,omitempty"`
}

RunStartData 运行开始事件数据 RunStartData is the data for run start event

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server represents the AgentOS HTTP server

func NewServer

func NewServer(config *Config) (*Server, error)

NewServer creates a new AgentOS server

func (*Server) GetAgentRegistry

func (s *Server) GetAgentRegistry() *AgentRegistry

GetAgentRegistry returns the agent registry

func (*Server) GetHealthRouter

func (s *Server) GetHealthRouter(path string) *gin.RouterGroup

GetHealthRouter returns a router group for the given health path so callers can attach additional handlers (e.g. custom health checks) while the server still maintains its default `/health` endpoint.

func (*Server) GetTeamRegistry

func (s *Server) GetTeamRegistry() *TeamRegistry

GetTeamRegistry returns the team registry.

func (*Server) RegisterAgent

func (s *Server) RegisterAgent(agentID string, ag *agent.Agent) error

RegisterAgent registers an agent with the server

func (*Server) RegisterDocs

func (s *Server) RegisterDocs(router *gin.Engine)

RegisterDocs mounts the OpenAPI specification and Swagger UI handlers onto the provided router. Passing nil registers the routes on the server's primary router, allowing callers to re-register after custom wiring or resync steps.

func (*Server) RegisterTeam

func (s *Server) RegisterTeam(teamID string, tm *team.Team) error

RegisterTeam registers a team with the server.

func (*Server) Resync

func (s *Server) Resync()

Resync re-registers documentation routes ensuring `/docs` remains mounted after custom wiring or hot reload flows.

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the server

func (*Server) Start

func (s *Server) Start() error

Start starts the HTTP server

type SessionResponse

type SessionResponse struct {
	SessionID  string                  `json:"session_id"`
	AgentID    string                  `json:"agent_id,omitempty"`
	UserID     string                  `json:"user_id,omitempty"`
	TeamID     string                  `json:"team_id,omitempty"`
	WorkflowID string                  `json:"workflow_id,omitempty"`
	Name       string                  `json:"name,omitempty"`
	Metadata   map[string]interface{}  `json:"metadata,omitempty"`
	State      map[string]interface{}  `json:"state,omitempty"`
	RunCount   int                     `json:"run_count"`
	CreatedAt  int64                   `json:"created_at"`
	UpdatedAt  int64                   `json:"updated_at"`
	Summary    *session.SessionSummary `json:"summary,omitempty"`
	Runs       []SessionRunMetadata    `json:"runs,omitempty"`
}

SessionResponse represents the session API response

type SessionRunMetadata

type SessionRunMetadata struct {
	RunID              string          `json:"run_id"`
	Status             agent.RunStatus `json:"status"`
	StartedAt          int64           `json:"started_at,omitempty"`
	CompletedAt        int64           `json:"completed_at,omitempty"`
	CancellationReason string          `json:"cancellation_reason,omitempty"`
	CacheHit           bool            `json:"cache_hit,omitempty"`
}

SessionRunMetadata captures key details of a run persisted in a session.

type SessionSummaryResult

type SessionSummaryResult struct {
	Summary *session.SessionSummary `json:"summary"`
}

SessionSummaryResult represents the payload returned by summary endpoints.

type StepData

type StepData struct {
	// StepName 步骤名称
	// StepName is the step name
	StepName string `json:"step_name"`

	// StepIndex 步骤索引
	// StepIndex is the step index
	StepIndex int `json:"step_index"`

	// Description 步骤描述
	// Description is the step description
	Description string `json:"description,omitempty"`
}

StepData 步骤事件数据 StepData is the data for step events

type TeamRegistry

type TeamRegistry struct {
	// contains filtered or unexported fields
}

TeamRegistry manages registered teams.

func NewTeamRegistry

func NewTeamRegistry() *TeamRegistry

NewTeamRegistry creates a new team registry.

func (*TeamRegistry) Clear

func (r *TeamRegistry) Clear()

Clear removes all teams from the registry.

func (*TeamRegistry) Exists

func (r *TeamRegistry) Exists(teamID string) bool

Exists checks if a team with the given ID is registered.

func (*TeamRegistry) Get

func (r *TeamRegistry) Get(teamID string) (*team.Team, error)

Get retrieves a team by ID.

func (*TeamRegistry) List

func (r *TeamRegistry) List() map[string]*team.Team

List returns a copy of all registered teams.

func (*TeamRegistry) Register

func (r *TeamRegistry) Register(teamID string, tm *team.Team) error

Register registers a team with the given ID.

type TeamToolsResponse

type TeamToolsResponse struct {
	TeamID string                  `json:"team_id"`
	Tools  []models.ToolDefinition `json:"tools"`
}

TeamToolsResponse is the API payload for listing team tools.

type TokenData

type TokenData struct {
	// Token 生成的令牌
	// Token is the generated token
	Token string `json:"token"`

	// Index 令牌索引
	// Index is the token index
	Index int `json:"index"`
}

TokenData 令牌事件数据 TokenData is the data for token event

type ToolCallData

type ToolCallData struct {
	// ToolName 工具名称
	// ToolName is the tool name
	ToolName string `json:"tool_name"`

	// Arguments 工具参数
	// Arguments are the tool arguments
	Arguments map[string]interface{} `json:"arguments"`

	// Result 工具结果(可选)
	// Result is the tool result (optional)
	Result interface{} `json:"result,omitempty"`
}

ToolCallData 工具调用事件数据 ToolCallData is the data for tool call event

type UpdateSessionRequest

type UpdateSessionRequest struct {
	Name     string                 `json:"name,omitempty"`
	Metadata map[string]interface{} `json:"metadata,omitempty"`
	State    map[string]interface{} `json:"state,omitempty"`
}

UpdateSessionRequest represents the request to update a session

type UsageMetrics

type UsageMetrics struct {
	PromptTokens     int `json:"prompt_tokens,omitempty"`
	CompletionTokens int `json:"completion_tokens,omitempty"`
	TotalTokens      int `json:"total_tokens,omitempty"`
	ReasoningTokens  int `json:"reasoning_tokens,omitempty"`
}

UsageMetrics captures token usage details

type VectorDBConfig

type VectorDBConfig struct {
	// Type 向量数据库类型(chromadb)
	// Type is the vector database type
	Type string

	// BaseURL 向量数据库 URL
	// BaseURL is the vector database URL
	BaseURL string

	// CollectionName 集合名称
	// CollectionName is the collection name
	CollectionName string

	// Database 数据库名称
	// Database is the database name
	Database string

	// Tenant 租户名称
	// Tenant is the tenant name
	Tenant string
}

VectorDBConfig 向量数据库配置 VectorDBConfig is the vector database configuration

type VectorSearchRequest

type VectorSearchRequest struct {
	// Query 查询文本
	// Query is the search query text
	Query string `json:"query" binding:"required"`

	// Limit 返回结果数量限制(默认: 10, 最大: 100)
	// Limit is the maximum number of results to return
	Limit int `json:"limit,omitempty"`

	// Offset 分页偏移量(默认: 0)
	// Offset is the pagination offset
	Offset int `json:"offset,omitempty"`

	// Filters 元数据过滤条件
	// Filters are metadata filter conditions
	Filters map[string]interface{} `json:"filters,omitempty"`

	// CollectionName 集合名称(可选,默认使用配置的集合)
	// CollectionName is the collection to search in
	CollectionName string `json:"collection_name,omitempty"`
}

VectorSearchRequest 表示向量搜索请求 VectorSearchRequest represents a vector search request

type VectorSearchResponse

type VectorSearchResponse struct {
	// Results 搜索结果列表
	// Results is the list of search results
	Results []VectorSearchResult `json:"results"`

	// Meta 分页元数据
	// Meta is pagination metadata
	Meta PaginationMeta `json:"meta"`
}

VectorSearchResponse 表示搜索响应 VectorSearchResponse represents the search response

type VectorSearchResult

type VectorSearchResult struct {
	// ID 文档 ID
	// ID is the document identifier
	ID string `json:"id"`

	// Content 文档内容
	// Content is the document content
	Content string `json:"content"`

	// Metadata 文档元数据
	// Metadata is the document metadata
	Metadata map[string]interface{} `json:"metadata,omitempty"`

	// Score 相似度得分(越高越相似)
	// Score is the similarity score (higher is better)
	Score float32 `json:"score"`

	// Distance 距离度量(越低越相似)
	// Distance is the distance metric (lower is better)
	Distance float32 `json:"distance"`
}

VectorSearchResult 表示单个搜索结果 VectorSearchResult represents a single search result

Directories

Path Synopsis
Package a2a implements the Agent-to-Agent (A2A) communication protocol based on JSON-RPC 2.0 standard.
Package a2a implements the Agent-to-Agent (A2A) communication protocol based on JSON-RPC 2.0 standard.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL