MCPcopy Create free account
hub / github.com/coder/aibridge / ProcessRequest

Method ProcessRequest

intercept/chatcompletions/blocking.go:66–260  ·  view source on GitHub ↗
(w http.ResponseWriter, r *http.Request)

Source from the content-addressed store, hash-verified

64}
65
66func (i *BlockingInterception) ProcessRequest(w http.ResponseWriter, r *http.Request) (outErr error) {
67 if i.req == nil {
68 return xerrors.New("developer error: req is nil")
69 }
70
71 ctx, span := i.tracer.Start(r.Context(), "Intercept.ProcessRequest", trace.WithAttributes(tracing.InterceptionAttributesFromContext(r.Context())...))
72 defer tracing.EndSpanErr(span, &outErr)
73
74 svc := i.newCompletionsService()
75 logger := i.logger.With(slog.F("model", i.req.Model))
76
77 var (
78 cumulativeUsage openai.CompletionUsage
79 completion *openai.ChatCompletion
80 err error
81 )
82
83 i.injectTools()
84
85 prompt, err := i.req.lastUserPrompt()
86 if err != nil {
87 logger.Warn(ctx, "failed to retrieve last user prompt", slog.Error(err))
88 }
89
90 for {
91 // TODO add outer loop span (https://github.com/coder/aibridge/issues/67)
92
93 var opts []option.RequestOption
94 opts = append(opts, option.WithRequestTimeout(time.Second*600))
95
96 // TODO(ssncferreira): inject actor headers directly in the client-header
97 // middleware instead of using SDK options.
98 if actor := aibcontext.ActorFromContext(r.Context()); actor != nil && i.cfg.SendActorHeaders {
99 opts = append(opts, intercept.ActorHeadersAsOpenAIOpts(actor)...)
100 }
101
102 completion, err = i.newChatCompletion(ctx, svc, opts)
103 if err != nil {
104 break
105 }
106
107 if prompt != nil {
108 _ = i.recorder.RecordPromptUsage(ctx, &recorder.PromptUsageRecord{
109 InterceptionID: i.ID().String(),
110 MsgID: completion.ID,
111 Prompt: *prompt,
112 })
113 prompt = nil
114 }
115
116 lastUsage := completion.Usage
117 cumulativeUsage = sumUsage(cumulativeUsage, completion.Usage)
118
119 _ = i.recorder.RecordTokenUsage(ctx, &recorder.TokenUsageRecord{
120 InterceptionID: i.ID().String(),
121 MsgID: completion.ID,
122 Input: calculateActualInputTokenUsage(lastUsage),
123 Output: lastUsage.CompletionTokens,

Callers

nothing calls this directly

Calls 15

newChatCompletionMethod · 0.95
EndSpanErrFunction · 0.92
ActorHeadersAsOpenAIOptsFunction · 0.92
IsConnErrorFunction · 0.92
sumUsageFunction · 0.85
StartMethod · 0.80
newCompletionsServiceMethod · 0.80
unmarshalArgsMethod · 0.80
CallMethod · 0.80
HeaderMethod · 0.80

Tested by

no test coverage detected