Skip to content

Commit 1654e64

Browse files
committed
refactor: Simplify error handling and remove unused logging features
1 parent b5f8ce6 commit 1654e64

File tree

3 files changed

+24
-269
lines changed

3 files changed

+24
-269
lines changed

src/routes/chat-completions/handler.ts

Lines changed: 2 additions & 81 deletions
Original file line numberDiff line numberDiff line change
@@ -1,107 +1,34 @@
11
import type { Context } from "hono"
22

3-
import consola from "consola"
43
import { streamSSE, type SSEMessage } from "hono/streaming"
54

65
import type { ChatCompletionsPayload } from "~/services/copilot/chat-completions/types"
7-
import type { ChatCompletionChunk } from "~/services/copilot/chat-completions/types-streaming"
86

97
import { isNullish } from "~/lib/is-nullish"
10-
import { logger } from "~/lib/logger"
11-
import { modelsCache } from "~/lib/models"
8+
import { state } from "~/lib/state"
129
import { createChatCompletions } from "~/services/copilot/chat-completions/service"
1310
import { chatCompletionsStream } from "~/services/copilot/chat-completions/service-streaming"
1411

15-
function createCondensedStreamingResponse(
16-
finalChunk: ChatCompletionChunk,
17-
collectedContent: string,
18-
) {
19-
return {
20-
id: finalChunk.id,
21-
model: finalChunk.model,
22-
created: finalChunk.created,
23-
object: "chat.completion",
24-
system_fingerprint: finalChunk.system_fingerprint,
25-
usage: finalChunk.usage,
26-
choices: [
27-
{
28-
index: 0,
29-
finish_reason: finalChunk.choices[0].finish_reason,
30-
message: {
31-
role: "assistant",
32-
content: collectedContent,
33-
},
34-
content_filter_results: finalChunk.choices[0].content_filter_results,
35-
},
36-
],
37-
}
38-
}
39-
4012
function handleStreaming(c: Context, payload: ChatCompletionsPayload) {
4113
return streamSSE(c, async (stream) => {
4214
const response = await chatCompletionsStream(payload)
4315

44-
// For collecting the complete streaming response
45-
let collectedContent = ""
46-
let finalChunk: ChatCompletionChunk | null = null
47-
4816
for await (const chunk of response) {
4917
await stream.writeSSE(chunk as SSEMessage)
50-
51-
if (!logger.options.enabled) continue
52-
53-
// Check if chunk data is "DONE" or not a valid JSON string
54-
if (!chunk.data || chunk.data === "[DONE]") {
55-
continue // Skip processing this chunk for logging
56-
}
57-
58-
try {
59-
const data = JSON.parse(chunk.data) as ChatCompletionChunk
60-
61-
// Keep track of the latest chunk for metadata
62-
finalChunk = data
63-
64-
// Accumulate content from each delta
65-
if (typeof data.choices[0].delta.content === "string") {
66-
collectedContent += data.choices[0].delta.content
67-
}
68-
} catch (error) {
69-
// Handle JSON parsing errors gracefully
70-
consola.error(`Error parsing SSE chunk data`, error)
71-
// Continue processing other chunks
72-
}
73-
}
74-
75-
// After streaming completes, log the condensed response
76-
if (finalChunk) {
77-
const condensedResponse = createCondensedStreamingResponse(
78-
finalChunk,
79-
collectedContent,
80-
)
81-
82-
await logger.logResponse("/chat/completions", condensedResponse, {})
8318
}
8419
})
8520
}
8621

8722
async function handleNonStreaming(c: Context, payload: ChatCompletionsPayload) {
8823
const response = await createChatCompletions(payload)
89-
90-
// Get response headers if any
91-
const responseHeaders = {} // Empty placeholder for response headers
92-
93-
// Log the non-streaming response with headers
94-
await logger.logResponse("/chat/completions", response, responseHeaders)
95-
9624
return c.json(response)
9725
}
9826

9927
export async function handleCompletion(c: Context) {
100-
const models = modelsCache.getModels()
10128
let payload = await c.req.json<ChatCompletionsPayload>()
10229

10330
if (isNullish(payload.max_tokens)) {
104-
const selectedModel = models?.data.find(
31+
const selectedModel = state.models?.data.find(
10532
(model) => model.id === payload.model,
10633
)
10734

@@ -111,12 +38,6 @@ export async function handleCompletion(c: Context) {
11138
}
11239
}
11340

114-
// Convert request headers to a regular object from Headers
115-
const requestHeaders = c.req.header()
116-
117-
// Log the request at the beginning for both streaming and non-streaming cases
118-
await logger.logRequest("/chat/completions", "POST", payload, requestHeaders)
119-
12041
if (payload.stream) {
12142
return handleStreaming(c, payload)
12243
}
Lines changed: 22 additions & 149 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,6 @@
1-
import type { BlankEnv, BlankInput } from "hono/types"
2-
import type { ContentfulStatusCode } from "hono/utils/http-status"
3-
41
import consola from "consola"
5-
import { Hono, type Context } from "hono"
6-
import { FetchError } from "ofetch"
2+
import { Hono } from "hono"
73

8-
import { logger } from "../../lib/logger"
94
import { handleCompletion } from "./handler"
105

116
export const completionRoutes = new Hono()
@@ -15,149 +10,27 @@ completionRoutes.post("/", async (c) => {
1510
return await handleCompletion(c)
1611
} catch (error) {
1712
consola.error("Error occurred:", error)
18-
return handleError(c, error)
19-
}
20-
})
21-
22-
// Handle different error types with specific handlers
23-
async function handleError(
24-
c: Context<BlankEnv, "/", BlankInput>,
25-
error: unknown,
26-
) {
27-
if (error instanceof FetchError) {
28-
return handleFetchError(c, error)
29-
}
30-
31-
if (error instanceof Response) {
32-
return await handleResponseError(c, error)
33-
}
34-
35-
if (error instanceof Error) {
36-
return handleGenericError(c, error)
37-
}
38-
39-
// Fallback for unknown error types
40-
void logger.logResponse("/v1/chat/completions", {
41-
error: {
42-
message: "An unknown error occurred",
43-
type: "unknown_error",
44-
},
45-
})
46-
47-
return c.json(
48-
{
49-
error: {
50-
message: "An unknown error occurred",
51-
type: "unknown_error",
52-
},
53-
},
54-
500,
55-
)
56-
}
57-
58-
function handleFetchError(
59-
c: Context<BlankEnv, "/", BlankInput>,
60-
error: FetchError,
61-
) {
62-
const status = error.response?.status ?? 500
63-
const responseData = error.response?._data as unknown
64-
const headers: Record<string, string> = {}
65-
66-
// Forward all headers from the error response
67-
for (const [key, value] of error.response?.headers.entries()) {
68-
c.header(key, value)
69-
headers[key] = value
70-
}
71-
72-
// Log the error response
73-
void logger.logResponse(
74-
"/v1/chat/completions",
75-
{
76-
error: {
77-
message: error.message,
78-
type: "fetch_error",
79-
data: responseData,
80-
status,
81-
},
82-
},
83-
headers,
84-
)
8513

86-
return c.json(
87-
{
88-
error: {
89-
message: error.message,
90-
type: "fetch_error",
91-
data: responseData,
14+
if (error instanceof Response) {
15+
return c.json(
16+
{
17+
error: {
18+
message: error.message,
19+
type: "error",
20+
},
21+
},
22+
500,
23+
)
24+
}
25+
26+
return c.json(
27+
{
28+
error: {
29+
message: error.message,
30+
type: "error",
31+
},
9232
},
93-
},
94-
status as ContentfulStatusCode,
95-
)
96-
}
97-
98-
async function handleResponseError(
99-
c: Context<BlankEnv, "/", BlankInput>,
100-
error: Response,
101-
) {
102-
const errorText = await error.text()
103-
consola.error(
104-
`Request failed: ${error.status} ${error.statusText}: ${errorText}`,
105-
)
106-
107-
const headers: Record<string, string> = {}
108-
109-
// Forward all headers from the error response
110-
for (const [key, value] of error.headers.entries()) {
111-
c.header(key, value)
112-
headers[key] = value
33+
500,
34+
)
11335
}
114-
115-
// Log the error response
116-
void logger.logResponse(
117-
"/v1/chat/completions",
118-
{
119-
error: {
120-
message: error.statusText || "Request failed",
121-
type: "response_error",
122-
status: error.status,
123-
details: errorText,
124-
},
125-
},
126-
headers,
127-
)
128-
129-
return c.json(
130-
{
131-
error: {
132-
message: error.statusText || "Request failed",
133-
type: "response_error",
134-
status: error.status,
135-
details: errorText,
136-
},
137-
},
138-
error.status as ContentfulStatusCode,
139-
)
140-
}
141-
142-
function handleGenericError(
143-
c: Context<BlankEnv, "/", BlankInput>,
144-
error: Error,
145-
) {
146-
// Log the error response
147-
void logger.logResponse("/v1/chat/completions", {
148-
error: {
149-
message: error.message,
150-
type: "error",
151-
},
152-
})
153-
154-
return c.json(
155-
{
156-
error: {
157-
message: error.message,
158-
type: "error",
159-
},
160-
},
161-
500,
162-
)
163-
}
36+
})

src/services/api-instance.ts

Lines changed: 0 additions & 39 deletions
This file was deleted.

0 commit comments

Comments
 (0)