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": "...", "stat
()
| 116 | // "status": "ok" |
| 117 | // } |
| 118 | func (s *Server) ChatHandler() http.Handler { |
| 119 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 120 | start := time.Now() |
| 121 | |
| 122 | if r.Method != http.MethodPost { |
| 123 | http.Error(w, "method not allowed", http.StatusMethodNotAllowed) |
| 124 | return |
| 125 | } |
| 126 | |
| 127 | var req ChatRequest |
| 128 | if err := json.NewDecoder(r.Body).Decode(&req); err != nil { |
| 129 | http.Error(w, "invalid JSON body", http.StatusBadRequest) |
| 130 | return |
| 131 | } |
| 132 | |
| 133 | if req.TemplateID == "" { |
| 134 | http.Error(w, "template_id is required", http.StatusBadRequest) |
| 135 | return |
| 136 | } |
| 137 | if req.Input == "" { |
| 138 | http.Error(w, "input is required", http.StatusBadRequest) |
| 139 | return |
| 140 | } |
| 141 | |
| 142 | ctx := r.Context() |
| 143 | // 为单次请求设置一个合理的超时,避免挂死。 |
| 144 | ctx, cancel := context.WithTimeout(ctx, 2*time.Minute) |
| 145 | defer cancel() |
| 146 | |
| 147 | agentConfig := &types.AgentConfig{ |
| 148 | TemplateID: req.TemplateID, |
| 149 | ModelConfig: req.ModelConfig, |
| 150 | Sandbox: req.Sandbox, |
| 151 | Middlewares: req.Middlewares, |
| 152 | Metadata: req.Metadata, |
| 153 | RoutingProfile: req.RoutingProfile, |
| 154 | } |
| 155 | |
| 156 | // 如果请求中携带了 SkillsPackage, 直接使用。 |
| 157 | // 否则如果提供了 Skills 列表, 则构造一个简单的本地 SkillsPackage, |
| 158 | // 将 EnabledSkills 映射为 req.Skills, Path 默认为当前工作目录。 |
| 159 | if req.SkillsPackage != nil { |
| 160 | agentConfig.SkillsPackage = req.SkillsPackage |
| 161 | } else if len(req.Skills) > 0 { |
| 162 | agentConfig.SkillsPackage = &types.SkillsPackageConfig{ |
| 163 | Source: "local", |
| 164 | Path: ".", // 相对于 Sandbox.WorkDir |
| 165 | SkillsDir: "skills", // 默认技能目录 |
| 166 | EnabledSkills: req.Skills, |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | ag, err := agent.Create(ctx, agentConfig, s.deps) |
| 171 | if err != nil { |
| 172 | logging.Error(ctx, "http.chat.error", map[string]any{ |
| 173 | "template_id": req.TemplateID, |
| 174 | "routing_profile": req.RoutingProfile, |
| 175 | "stage": "create_agent", |