Skip to content

Commit d9d7728

Browse files
committed
refactor: organize init
1 parent f9b62b2 commit d9d7728

File tree

3 files changed

+60
-58
lines changed

3 files changed

+60
-58
lines changed

src/main.ts

Lines changed: 49 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -9,47 +9,66 @@ import { getModels } from "./services/copilot/get-models/service"
99
import { getCopilotToken } from "./services/copilot/get-token/copilot-token"
1010
import { getGitHubToken } from "./services/copilot/get-token/github-token"
1111

12-
if (!fs.existsSync(PATHS.PATH_CACHE_FILE)) {
13-
fs.mkdirSync(PATHS.DIR_CACHE, { recursive: true })
14-
await CACHE._write({})
12+
async function initializeGithubToken() {
13+
const EIGHT_HOURS = 8 * 60 * 60 * 1000
14+
const cachedGithubToken = await CACHE.get("github-token")
15+
16+
// If exists and at most 8 hours old
17+
if (
18+
cachedGithubToken &&
19+
Date.now() - cachedGithubToken.createdAt < EIGHT_HOURS
20+
) {
21+
return cachedGithubToken.value
22+
}
23+
24+
const newToken = await getGitHubToken()
25+
await CACHE.set("github-token", newToken)
26+
return newToken
1527
}
1628

17-
let githubToken: string
29+
async function initializeCopilotToken() {
30+
const { token, refresh_in } = await getCopilotToken()
31+
TOKENS.COPILOT_TOKEN = token
1832

19-
const cachedGithubToken = await CACHE.get("github-token")
33+
// refresh_in is in minutes
34+
// we're refreshing 100 minutes early
35+
const refreshInterval = (refresh_in - 100) * 60 * 1000
2036

21-
const EIGHT_HOURS = 8 * 60 * 60 * 1000
37+
setInterval(async () => {
38+
consola.start("Refreshing copilot token")
39+
const { token: newToken } = await getCopilotToken()
40+
TOKENS.COPILOT_TOKEN = newToken
41+
}, refreshInterval)
2242

23-
// If exists and at most 8 hours old
24-
if (
25-
cachedGithubToken &&
26-
Date.now() - cachedGithubToken.createdAt < EIGHT_HOURS
27-
) {
28-
githubToken = cachedGithubToken.value
29-
} else {
30-
githubToken = await getGitHubToken()
31-
await CACHE.set("github-token", githubToken)
43+
return token
3244
}
3345

34-
TOKENS.GITHUB_TOKEN = githubToken
46+
async function initializeCache() {
47+
if (!fs.existsSync(PATHS.PATH_CACHE_FILE)) {
48+
fs.mkdirSync(PATHS.DIR_CACHE, { recursive: true })
49+
await CACHE._write({})
50+
}
51+
}
3552

36-
const { token: copilotToken, refresh_in } = await getCopilotToken()
37-
TOKENS.COPILOT_TOKEN = copilotToken
53+
async function logAvailableModels() {
54+
const models = await getModels()
55+
consola.info(
56+
`Available models: \n${models.data.map((model) => `- ${model.id}`).join("\n")}`,
57+
)
58+
}
3859

39-
// refresh_in is in minutes
40-
// we're refreshing 100 minutes early
41-
const refreshInterval = (refresh_in - 100) * 60 * 1000
60+
async function initialize() {
61+
await initializeCache()
4262

43-
setInterval(async () => {
44-
consola.start("Refreshing copilot token")
45-
const { token: copilotToken } = await getCopilotToken()
46-
TOKENS.COPILOT_TOKEN = copilotToken
47-
}, refreshInterval)
63+
// Initialize tokens
64+
TOKENS.GITHUB_TOKEN = await initializeGithubToken()
65+
await initializeCopilotToken()
4866

49-
const models = await getModels()
67+
// Log available models
68+
await logAvailableModels()
69+
}
5070

51-
consola.info(
52-
`Available models: \n${models.data.map((model) => `- ${model.id}`).join("\n")}`,
53-
)
71+
// Initialize the application
72+
await initialize()
5473

5574
export default server

src/routes/chat-completions/route.ts

Lines changed: 9 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ chatCompletionsRoutes.post("/chat/completions", async (c) => {
1515

1616
payload.stream = false
1717

18-
consola.info(`Received request: ${JSON.stringify(payload).slice(0, 100)}`)
18+
consola.info(`Received request: ${JSON.stringify(payload).slice(0, 500)}`)
1919

2020
const response = await chatCompletions(payload).catch((error: unknown) => {
2121
if (error instanceof FetchError) {
@@ -36,9 +36,10 @@ chatCompletionsRoutes.post("/chat/completions", async (c) => {
3636
response.choices[0].message.content,
3737
)
3838

39-
let chunks: Array<ChatCompletionsChunk> = Array.from(segmentedMessages).map(
39+
const chunks: Array<ChatCompletionsChunk> = Array.from(segmentedMessages).map(
4040
(segment) => ({
4141
data: {
42+
object: "chat.completion.chunk",
4243
choices: [
4344
{
4445
delta: {
@@ -50,31 +51,16 @@ chatCompletionsRoutes.post("/chat/completions", async (c) => {
5051
],
5152
created: response.created,
5253
id: response.id,
53-
// Aider expects the model to be the same as the one used in the request
5454
model: payload.model,
55-
usage: response.usage,
55+
usage: null,
56+
system_fingerprint: "fp_44709d6fcb",
5657
},
5758
}),
5859
)
5960

60-
const usagePerChunk: ChatCompletionsChunk["data"]["usage"] = {
61-
completion_tokens: Math.round(
62-
response.usage.completion_tokens / chunks.length,
63-
),
64-
prompt_tokens: Math.round(response.usage.prompt_tokens / chunks.length),
65-
total_tokens: Math.round(response.usage.total_tokens / chunks.length),
66-
}
67-
68-
chunks = chunks.map((chunk) => ({
69-
...chunk,
70-
data: {
71-
...chunk.data,
72-
usage: usagePerChunk,
73-
},
74-
}))
75-
7661
chunks.push({
7762
data: {
63+
object: "chat.completion.chunk",
7864
choices: [
7965
{
8066
delta: {},
@@ -84,17 +70,13 @@ chatCompletionsRoutes.post("/chat/completions", async (c) => {
8470
],
8571
created: response.created,
8672
id: response.id,
87-
// Aider expects the model to be the same as the one used in the request
8873
model: payload.model,
89-
usage: {
90-
completion_tokens: 0,
91-
prompt_tokens: 0,
92-
total_tokens: 0,
93-
},
74+
usage: response.usage,
75+
system_fingerprint: "fp_44709d6fcb",
9476
},
9577
})
9678

97-
console.info(
79+
consola.info(
9880
`Streaming response, first chunk: ${JSON.stringify(chunks.at(0))}`,
9981
)
10082

src/services/copilot/chat-completions/types.streaming.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,11 +54,12 @@ interface Usage {
5454
interface ChatCompletionResponse {
5555
choices: [Choice]
5656
created: number
57+
object: "chat.completion.chunk"
5758
id: string
5859
model: string
5960
system_fingerprint?: string
6061
prompt_filter_results?: Array<PromptFilterResult>
61-
usage?: Usage
62+
usage?: Usage | null
6263
}
6364

6465
export interface ChatCompletionsChunk {

0 commit comments

Comments
 (0)