MCPcopy Index your code
hub / github.com/apache/answer / ChatCompletions

Method ChatCompletions

internal/controller/ai_controller.go:189–269  ·  view source on GitHub ↗
(ctx *gin.Context)

Source from the content-addressed store, hash-verified

187}
188
189func (c *AIController) ChatCompletions(ctx *gin.Context) {
190 if !c.ensureAIChatEnabled(ctx) {
191 return
192 }
193 aiConfig, err := c.siteInfoService.GetSiteAI(context.Background())
194 if err != nil {
195 log.Errorf("Failed to get AI config: %v", err)
196 handler.HandleResponse(ctx, errors.BadRequest("AI service configuration error"), nil)
197 return
198 }
199
200 if !aiConfig.Enabled {
201 handler.HandleResponse(ctx, errors.ServiceUnavailable("AI service is not enabled"), nil)
202 return
203 }
204
205 aiProvider := aiConfig.GetProvider()
206
207 req := &ChatCompletionsRequest{}
208 if handler.BindAndCheck(ctx, req) {
209 return
210 }
211 req.UserID = middleware.GetLoginUserIDFromContext(ctx)
212
213 data, _ := json.Marshal(req)
214 log.Infof("ai chat request data: %s", string(data))
215
216 ctx.Header("Content-Type", "text/event-stream")
217 ctx.Header("Cache-Control", "no-cache")
218 ctx.Header("Connection", "keep-alive")
219 ctx.Header("Access-Control-Allow-Origin", "*")
220 ctx.Header("Access-Control-Allow-Headers", "Cache-Control")
221
222 ctx.Status(http.StatusOK)
223
224 w := ctx.Writer
225
226 if f, ok := w.(http.Flusher); ok {
227 f.Flush()
228 }
229
230 chatcmplID := "chatcmpl-" + token.GenerateToken()
231 created := time.Now().Unix()
232
233 firstResponse := StreamResponse{
234 ChatCompletionID: chatcmplID,
235 Object: "chat.completion.chunk",
236 Created: time.Now().Unix(),
237 Model: aiProvider.Model,
238 Choices: []StreamChoice{{Index: 0, Delta: Delta{Role: "assistant"}, FinishReason: nil}},
239 }
240
241 sendStreamData(w, firstResponse)
242
243 conversationCtx := c.initializeConversationContext(ctx, aiProvider.Model, req)
244 if conversationCtx == nil {
245 log.Error("Failed to initialize conversation context")
246 c.sendErrorResponse(w, chatcmplID, aiProvider.Model, "Failed to initialize conversation context")

Callers

nothing calls this directly

Calls 13

ensureAIChatEnabledMethod · 0.95
sendErrorResponseMethod · 0.95
redirectRequestToAIMethod · 0.95
HandleResponseFunction · 0.92
BindAndCheckFunction · 0.92
GenerateTokenFunction · 0.92
sendStreamDataFunction · 0.85
GetProviderMethod · 0.80
FlushMethod · 0.80

Tested by

no test coverage detected