MCPcopy Index your code
hub / github.com/CodebuffAI/codebuff / handleOpenAINonStream

Function handleOpenAINonStream

web/src/llm-api/openai.ts:215–374  ·  view source on GitHub ↗
({
  body,
  userId,
  stripeCustomerId,
  agentId,
  fetch,
  logger,
  insertMessageBigquery,
}: {
  body: ChatCompletionRequestBody
  userId: string
  stripeCustomerId?: string | null
  agentId: string
  fetch: typeof globalThis.fetch
  logger: Logger
  insertMessageBigquery: InsertMessageBigqueryFn
})

Source from the content-addressed store, hash-verified

213}
214
215export async function handleOpenAINonStream({
216 body,
217 userId,
218 stripeCustomerId,
219 agentId,
220 fetch,
221 logger,
222 insertMessageBigquery,
223}: {
224 body: ChatCompletionRequestBody
225 userId: string
226 stripeCustomerId?: string | null
227 agentId: string
228 fetch: typeof globalThis.fetch
229 logger: Logger
230 insertMessageBigquery: InsertMessageBigqueryFn
231}) {
232 const startTime = new Date()
233 const { clientId, clientRequestId, costMode, n } = extractRequestMetadata({
234 body,
235 logger,
236 })
237 const auditRequest = createRequestAuditRecord(body)
238
239 const originalModel = body.model
240 const modelShortName = extractShortModelName(originalModel)
241 const openaiBody = buildOpenAIBody(body, modelShortName)
242 openaiBody.stream = false
243 if (n) openaiBody.n = n
244
245 const response = await fetch('https://api.openai.com/v1/chat/completions', {
246 method: 'POST',
247 headers: {
248 Authorization: `Bearer ${env.OPENAI_API_KEY}`,
249 'Content-Type': 'application/json',
250 },
251 body: JSON.stringify(openaiBody),
252 })
253
254 if (!response.ok) {
255 throw new OpenAIError(
256 response.status,
257 response.statusText,
258 await response.text(),
259 )
260 }
261
262 const data = await response.json()
263 const usage: OpenAIUsage = data.usage ?? {}
264 const usageData = extractUsageAndCost(usage, modelShortName)
265
266 if (n && n > 1) {
267 // Multi-response: aggregate all choices into a JSON array
268 const responseContents: string[] = []
269 if (data.choices && Array.isArray(data.choices)) {
270 for (const choice of data.choices) {
271 responseContents.push(choice.message?.content ?? '')
272 }

Callers 1

postChatCompletionsFunction · 0.90

Calls 9

extractRequestMetadataFunction · 0.90
insertMessageToBigQueryFunction · 0.90
consumeCreditsForMessageFunction · 0.90
createRequestAuditRecordFunction · 0.85
extractShortModelNameFunction · 0.85
buildOpenAIBodyFunction · 0.85
extractUsageAndCostFunction · 0.70
creditsToFakeCostFunction · 0.70
fetchFunction · 0.50

Tested by

no test coverage detected