|
1 | 1 | import consola from "consola" |
2 | 2 | import { Hono } from "hono" |
3 | | -import { streamSSE } from "hono/streaming" |
4 | 3 | import { FetchError } from "ofetch" |
5 | 4 |
|
6 | | -import type { ChatCompletionsPayload } from "~/services/copilot/chat-completions/types" |
| 5 | +import { ENV } from "~/config/env" |
7 | 6 |
|
8 | | -import { chatCompletions } from "~/services/copilot/chat-completions/service" |
| 7 | +import { handler } from "./handler" |
| 8 | +import { handlerStreaming } from "./handler-streaming" |
9 | 9 |
|
10 | | -import { createContentChunk, createFinalChunk, segmentResponse } from "./utils" |
| 10 | +export const completionRoutes = new Hono() |
11 | 11 |
|
12 | | -export const chatCompletionsRoutes = new Hono() |
13 | | - |
14 | | -chatCompletionsRoutes.post("/chat/completions", async (c) => { |
| 12 | +completionRoutes.post("/chat/completions", (c) => { |
15 | 13 | try { |
16 | | - const payload = await c.req.json<ChatCompletionsPayload>() |
17 | | - payload.stream = false |
18 | | - |
19 | | - consola.info(`Received request: ${JSON.stringify(payload).slice(0, 500)}`) |
20 | | - |
21 | | - const response = await chatCompletions(payload) |
22 | | - consola.info(`Response from Copilot: ${JSON.stringify(response)}`) |
23 | | - |
24 | | - const segments = segmentResponse(response.choices[0].message.content) |
25 | | - const chunks = segments.map((segment) => |
26 | | - createContentChunk(segment, response, payload.model), |
27 | | - ) |
28 | | - |
29 | | - chunks.push(createFinalChunk(response, payload.model)) |
30 | | - |
31 | | - consola.info( |
32 | | - `Streaming response, first chunk: ${JSON.stringify(chunks.at(0))}`, |
33 | | - ) |
34 | | - |
35 | | - return streamSSE(c, async (stream) => { |
36 | | - for (const chunk of chunks) { |
37 | | - await stream.writeSSE({ |
38 | | - data: JSON.stringify(chunk.data), |
39 | | - }) |
40 | | - await stream.sleep(1) // Simulated latency |
41 | | - } |
42 | | - }) |
| 14 | + if (ENV.ENABLE_STREAMING) { |
| 15 | + return handlerStreaming(c) |
| 16 | + } else { |
| 17 | + return handler(c) |
| 18 | + } |
43 | 19 | } catch (error) { |
44 | 20 | if (error instanceof FetchError) { |
45 | 21 | consola.error(`Request failed: ${error.message}`, error.response?._data) |
|
0 commit comments