server

package
v0.35.0 Latest Latest
Warning

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

Go to latest
Published: Dec 29, 2025 License: MIT Imports: 21 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BadRequest

func BadRequest(w http.ResponseWriter, message string)

BadRequest 辅助函数:400 Bad Request

func Conflict

func Conflict(w http.ResponseWriter, message string)

Conflict 辅助函数:409 Conflict

func Created

func Created(w http.ResponseWriter, data any)

Created 辅助函数:发送 201 Created 响应

func Error

func Error(w http.ResponseWriter, status int, code, message string)

Error 辅助函数:发送错误响应

func ErrorWithDetails

func ErrorWithDetails(w http.ResponseWriter, status int, code, message, details string)

ErrorWithDetails 辅助函数:发送带详细信息的错误响应

func Forbidden

func Forbidden(w http.ResponseWriter, message string)

Forbidden 辅助函数:403 Forbidden

func InternalError

func InternalError(w http.ResponseWriter, message string)

InternalError 辅助函数:500 Internal Server Error

func JSON

func JSON(w http.ResponseWriter, status int, data any)

JSON 辅助函数:发送 JSON 响应

func NoContent

func NoContent(w http.ResponseWriter)

NoContent 辅助函数:发送 204 No Content 响应

func NotFound

func NotFound(w http.ResponseWriter, message string)

NotFound 辅助函数:404 Not Found

func Paginated

func Paginated(w http.ResponseWriter, items any, total, page, pageSize int)

Paginated 辅助函数:发送分页响应

func ParseJSON

func ParseJSON(r *http.Request, v any) error

ParseJSON 解析 JSON 请求体

func Unauthorized

func Unauthorized(w http.ResponseWriter, message string)

Unauthorized 辅助函数:401 Unauthorized

Types

type APIError

type APIError struct {
	Code    string `json:"code"`
	Message string `json:"message"`
	Details string `json:"details,omitempty"`
}

APIError 统一的错误格式

type APIResponse

type APIResponse struct {
	Success bool      `json:"success"`
	Data    any       `json:"data,omitempty"`
	Error   *APIError `json:"error,omitempty"`
}

APIResponse 统一的 API 响应格式

type BatchEvalRequest

type BatchEvalRequest struct {
	// TestCases 测试用例列表
	TestCases []BatchTestCaseRequest `json:"test_cases"`
	// Scorers 要使用的评分器列表
	Scorers []string `json:"scorers,omitempty"`
	// Concurrency 并发数(默认: 1)
	Concurrency int `json:"concurrency,omitempty"`
	// StopOnError 遇到错误时是否停止(默认: false)
	StopOnError bool `json:"stop_on_error,omitempty"`
	// Keywords 关键词列表(用于keyword_coverage scorer)
	Keywords []string `json:"keywords,omitempty"`
	// ProviderConfig 可选的LLM Provider配置(用于LLM-based scorers)
	ProviderConfig *types.ModelConfig `json:"provider_config,omitempty"`
}

BatchEvalRequest 表示批量评估请求

type BatchEvalResponse

type BatchEvalResponse struct {
	Results       []BatchResultResponse `json:"results"`
	Summary       *BatchSummaryResponse `json:"summary"`
	TotalDuration int64                 `json:"total_duration_ms"`
}

BatchEvalResponse 批量评估响应

type BatchResultResponse

type BatchResultResponse struct {
	TestCaseID string              `json:"test_case_id"`
	Scores     []evals.ScoreResult `json:"scores"`
	Duration   int64               `json:"duration_ms"`
	Error      string              `json:"error,omitempty"`
	Metadata   map[string]any      `json:"metadata,omitempty"`
}

BatchResultResponse 单个测试用例的结果

type BatchSummaryResponse

type BatchSummaryResponse struct {
	TotalCases      int                `json:"total_cases"`
	SuccessfulCases int                `json:"successful_cases"`
	FailedCases     int                `json:"failed_cases"`
	AverageScores   map[string]float64 `json:"average_scores"`
	AverageDuration int64              `json:"average_duration_ms"`
}

BatchSummaryResponse 批量评估汇总

type BatchTestCaseRequest

type BatchTestCaseRequest struct {
	ID        string         `json:"id"`
	Answer    string         `json:"answer"`
	Context   []string       `json:"context,omitempty"`
	Reference string         `json:"reference,omitempty"`
	Metadata  map[string]any `json:"metadata,omitempty"`
}

BatchTestCaseRequest 单个测试用例请求

type ChatRequest

type ChatRequest struct {
	// TemplateID 指定要使用的 Agent 模板 ID。
	TemplateID string `json:"template_id"`
	// Input 用户输入的自然语言文本。
	Input string `json:"input"`

	// RoutingProfile 可选路由偏好,与 types.AgentConfig.RoutingProfile 对应。
	// 例如: "cost"、"quality"、"latency"。
	RoutingProfile string `json:"routing_profile,omitempty"`

	// ModelConfig 可选模型配置,未提供时使用模板默认配置。
	ModelConfig *types.ModelConfig `json:"model_config,omitempty"`
	// Sandbox 可选沙箱配置,未提供时使用默认本地沙箱。
	Sandbox *types.SandboxConfig `json:"sandbox,omitempty"`
	// Middlewares 可选中间件列表。
	Middlewares []string `json:"middlewares,omitempty"`
	// Metadata 可选元数据,会传递给 AgentConfig.Metadata。
	Metadata map[string]any `json:"metadata,omitempty"`

	// Skills 可选: 本次请求允许启用的 Skills 列表。
	// 对应 types.SkillsPackageConfig.EnabledSkills, 用于按请求粒度控制 Skill 集合,
	// 类似 Claude API 中 container.skills 的作用。
	Skills []string `json:"skills,omitempty"`

	// SkillsPackage 可选: 更细粒度控制 Skills 包的配置。
	// 如果提供, 则优先于 Skills 字段, 直接传递给 AgentConfig.SkillsPackage。
	SkillsPackage *types.SkillsPackageConfig `json:"skills_package,omitempty"`
}

ChatRequest 表示 HTTP Chat 请求体。 这是一个最小可用结构,后续可按需扩展。

type ChatResponse

type ChatResponse struct {
	AgentID string `json:"agent_id"`
	Text    string `json:"text"`
	Status  string `json:"status"`

	// ErrorMessage 非空表示请求失败时的错误信息。
	ErrorMessage string `json:"error_message,omitempty"`
}

ChatResponse 表示 Chat 请求的同步响应。

type LLMWorkflowAgent

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

LLMWorkflowAgent 是一个基于 agent.Agent 封装的 workflow.Agent 实现, 用于在 demo 工作流中调用真实 LLM。

func NewLLMWorkflowAgent

func NewLLMWorkflowAgent(name, description string, deps *agent.Dependencies) *LLMWorkflowAgent

NewLLMWorkflowAgent 创建一个 LLMWorkflowAgent。 当前默认使用 templateID = "assistant"。

func (*LLMWorkflowAgent) Execute

func (a *LLMWorkflowAgent) Execute(ctx context.Context, message string) *stream.Reader[*session.Event]

Execute 实现 workflow.Agent 接口。

func (*LLMWorkflowAgent) Name

func (a *LLMWorkflowAgent) Name() string

Name 实现 workflow.Agent 接口。

type PaginatedResponse

type PaginatedResponse struct {
	Items      any `json:"items"`
	Total      int `json:"total"`
	Page       int `json:"page"`
	PageSize   int `json:"page_size"`
	TotalPages int `json:"total_pages"`
}

PaginatedResponse 分页响应

type Server

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

Server 提供基于 HTTP 的 aster 接入层。 设计目标: - 封装 Agent 创建和一次性 Chat 调用 - 提供简单、可扩展的 REST 接口,便于前端/第三方集成 - 后续可以在此基础上扩展 streaming、会话管理等能力

func New

func New(deps *agent.Dependencies) *Server

New 创建一个 Server 实例。

func (*Server) BatchEvalHandler

func (s *Server) BatchEvalHandler() http.Handler

BatchEvalHandler 返回批量评估的HTTP handler

func (*Server) ChatHandler

func (s *Server) ChatHandler() http.Handler

ChatHandler 返回一个 HTTP handler,用于处理同步 Chat 请求。

路径示例:

POST /v1/agents/chat

请求体:

{
  "template_id": "assistant",
  "input": "你好,帮我总结一下 README",
  "metadata": {"user_id": "alice"},
  "middlewares": ["filesystem", "agent_memory"]
}

响应体:

{
  "agent_id": "agt-...",
  "text": "...",
  "status": "ok"
}

func (*Server) ChatStreamHandler

func (s *Server) ChatStreamHandler() http.Handler

ChatStreamHandler 提供基于 Server-Sent Events (SSE) 的流式 Chat 接口。

路径示例:

POST /v1/agents/chat/stream

请求体与 ChatHandler 相同,但响应为 text/event-stream。 每个事件均为一行 JSON:

data: {"cursor":1,"bookmark":{...},"event":{...}}\n\n

前端可以根据 event 字段中的具体类型(decoding types.*Event)来渲染流式思考/文本/工具调用等。

func (*Server) SessionEvalHandler

func (s *Server) SessionEvalHandler() http.Handler

SessionEvalHandler 返回一个 HTTP handler, 基于 Session 事件进行评估。

路径示例:

POST /v1/evals/session

请求体:

{
  "events": [...],                // session.Event JSON 列表
  "reference": "参考答案",
  "keywords": ["paris", "capital"],
  "scorers": ["keyword_coverage", "lexical_similarity"]
}

func (*Server) SkillsGetOrDeleteHandler

func (s *Server) SkillsGetOrDeleteHandler() http.Handler

SkillsGetOrDeleteHandler 处理:

  • GET /v1/skills/{id} 获取单个 Skill 的所有版本信息
  • DELETE /v1/skills/{id} 卸载 Skill (删除其所有目录)
  • GET /v1/skills/{id}/versions 列出指定 Skill 的所有版本
  • POST /v1/skills/{id}/versions 创建/更新指定版本
  • DELETE /v1/skills/{id}/versions/{version} 删除指定版本

func (*Server) SkillsListOrCreateHandler

func (s *Server) SkillsListOrCreateHandler() http.Handler

SkillsListOrCreateHandler 处理:

  • GET /v1/skills 列出所有 Skills
  • POST /v1/skills 安装或更新一个 Skill (JSON 形式)

这里使用简化的 JSON 协议, 方便集成: POST /v1/skills

{
  "id": "pdf-to-markdown",
  "files": [
    {"path": "pdf-to-markdown/SKILL.md", "content": "..."},
    {"path": "pdf-to-markdown/scripts/pdf2md.go", "content": "..."}
  ]
}

func (*Server) TextEvalHandler

func (s *Server) TextEvalHandler() http.Handler

TextEvalHandler 返回一个 HTTP handler, 用于处理文本评估请求。

路径示例:

POST /v1/evals/text

请求体:

{
  "answer": "Paris is the capital of France.",
  "reference": "Paris is the capital city of France, a country in Europe.",
  "keywords": ["paris", "capital", "france", "europe"],
  "scorers": ["keyword_coverage", "lexical_similarity"]
}

响应体:

{
  "scores": [
    {"name":"keyword_coverage","value":1.0,"details":{...}},
    {"name":"lexical_similarity","value":0.8,"details":{...}}
  ]
}

func (*Server) WorkflowDemoGetRunHandler

func (s *Server) WorkflowDemoGetRunHandler() http.Handler

WorkflowDemoGetRunHandler 返回指定 run_id 的工作流运行记录。

路径示例:

GET /v1/workflows/demo/runs?id=<run_id>

响应体:

{
  "id": "run-...",
  "workflow_id": "sequential_demo",
  "input": "处理用户数据",
  "events": [...],
  "eval_scores": [...],
  "created_at": "..."
}

func (*Server) WorkflowDemoRunEvalHandler

func (s *Server) WorkflowDemoRunEvalHandler() http.Handler

WorkflowDemoRunEvalHandler 返回一个 HTTP handler, 用于运行内置 demo 工作流并对最终回答进行评估。

路径示例:

POST /v1/workflows/demo/run-eval

请求体:

{
  "workflow_id": "sequential_demo",
  "input": "处理用户数据",
  "reference": "期望的总结结果...",
  "keywords": ["收集", "分析", "报告"],
  "scorers": ["keyword_coverage", "lexical_similarity"]
}

响应体:

{
  "events": [...],
  "eval_scores": [
    {"name": "keyword_coverage", "value": 0.75, ...},
    {"name": "lexical_similarity", "value": 0.82, ...}
  ]
}

func (*Server) WorkflowDemoRunHandler

func (s *Server) WorkflowDemoRunHandler() http.Handler

WorkflowDemoRunHandler 返回一个 HTTP handler, 用于运行内置的演示工作流。

路径示例:

POST /v1/workflows/demo/run

请求体:

{
  "workflow_id": "sequential_demo",
  "input": "处理用户数据"
}

响应体:

{
  "events": [
    {"id":"...","agent_id":"DataCollector","text":"...","metadata":{...}},
    ...
  ]
}

type SessionEvalRequest

type SessionEvalRequest struct {
	// Events 会话事件列表, 使用 pkg/session.Event 结构。
	Events []session.Event `json:"events"`
	// Reference 可选参考答案, 用于词汇相似度评估。
	Reference string `json:"reference,omitempty"`
	// Keywords 关键词列表, 用于关键词覆盖率评估。
	Keywords []string `json:"keywords,omitempty"`
	// Scorers 指定要启用的 scorer 名称, 为空时默认启用:
	// ["keyword_coverage", "lexical_similarity"]。
	Scorers []string `json:"scorers,omitempty"`
}

SessionEvalRequest 表示基于 Session 事件的评估请求。

type TextEvalRequest

type TextEvalRequest struct {
	// Answer 待评估的模型输出。
	Answer string `json:"answer"`
	// Context 可选的上下文信息, 当前实现不会直接使用, 预留扩展。
	Context []string `json:"context,omitempty"`
	// Reference 可选参考答案, 用于词汇相似度评估。
	Reference string `json:"reference,omitempty"`
	// Keywords 关键词列表, 用于关键词覆盖率评估。
	Keywords []string `json:"keywords,omitempty"`
	// Scorers 指定要启用的 scorer 名称, 为空时默认启用:
	// ["keyword_coverage", "lexical_similarity"]。
	Scorers []string `json:"scorers,omitempty"`
}

TextEvalRequest 表示一次文本评估请求。 该接口仅使用本地启发式 scorer, 不依赖外部 LLM。

type TextEvalResponse

type TextEvalResponse struct {
	Scores       []evals.ScoreResult `json:"scores"`
	ErrorMessage string              `json:"error_message,omitempty"`
}

TextEvalResponse 表示文本评估的响应。

type WorkflowEvent

type WorkflowEvent struct {
	ID        string         `json:"id"`
	Timestamp time.Time      `json:"timestamp"`
	AgentID   string         `json:"agent_id"`
	Branch    string         `json:"branch,omitempty"`
	Author    string         `json:"author"`
	Text      string         `json:"text"`
	Metadata  map[string]any `json:"metadata,omitempty"`
}

WorkflowEvent 表示通过 HTTP 返回的精简事件结构。

type WorkflowRunEvalRequest

type WorkflowRunEvalRequest struct {
	WorkflowRunRequest

	// Reference 可选参考答案, 用于词汇相似度评估。
	Reference string `json:"reference,omitempty"`
	// Keywords 可选关键词列表, 用于关键词覆盖率评估。
	Keywords []string `json:"keywords,omitempty"`
	// Scorers 指定要启用的 scorer 名称, 为空时默认启用:
	// ["keyword_coverage", "lexical_similarity"]。
	Scorers []string `json:"scorers,omitempty"`
}

WorkflowRunEvalRequest 在 WorkflowRunRequest 基础上增加可选的 eval 参数。

type WorkflowRunEvalResponse

type WorkflowRunEvalResponse struct {
	WorkflowRunResponse

	EvalScores []evals.ScoreResult `json:"eval_scores,omitempty"`
}

WorkflowRunEvalResponse 在 WorkflowRunResponse 基础上增加 eval_scores 字段。

type WorkflowRunRecord

type WorkflowRunRecord struct {
	ID           string              `json:"id"`
	WorkflowID   string              `json:"workflow_id"`
	Input        string              `json:"input"`
	Events       []WorkflowEvent     `json:"events"`
	EvalScores   []evals.ScoreResult `json:"eval_scores,omitempty"`
	ErrorMessage string              `json:"error_message,omitempty"`
	CreatedAt    time.Time           `json:"created_at"`
}

WorkflowRunRecord 表示持久化存储的一次工作流运行记录。

type WorkflowRunRequest

type WorkflowRunRequest struct {
	// WorkflowID 工作流标识:
	// - "sequential_demo"
	// - "parallel_demo"
	// - "loop_demo"
	// - "nested_demo"
	WorkflowID string `json:"workflow_id"`

	// Input 传递给工作流的输入消息。
	Input string `json:"input"`
}

WorkflowRunRequest 表示一次工作流运行请求。 当前仅提供基于 MockAgent 的演示工作流, 用于快速体验工作流编排与事件结构。

type WorkflowRunResponse

type WorkflowRunResponse struct {
	RunID        string          `json:"run_id,omitempty"`
	Events       []WorkflowEvent `json:"events"`
	ErrorMessage string          `json:"error_message,omitempty"`
}

WorkflowRunResponse 表示工作流运行的结果。

Jump to

Keyboard shortcuts

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