Skip to content

Commit b3b4e94

Browse files
authored
Merge pull request #7 from lingrottin/main
Fix #6
2 parents c1540eb + aa8ecfd commit b3b4e94

File tree

1 file changed

+13
-21
lines changed

1 file changed

+13
-21
lines changed

src/llm/openai.ts

Lines changed: 13 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -190,9 +190,6 @@ function openaiResponse(options: { createClient: (req: ChatCompletionCreateParam
190190
}
191191

192192
export function openai(env: Record<string, string>): IChat {
193-
const client = new OpenAI({
194-
apiKey: env.OPENAI_API_KEY,
195-
})
196193
const oldModels = [
197194
'chatgpt-4o-latest',
198195
'codex-mini-latest',
@@ -263,27 +260,22 @@ export function openai(env: Record<string, string>): IChat {
263260
'o4-mini',
264261
'o4-mini-2025-04-16',
265262
]
263+
// 将 client 从一个值换成函数来惰性求值,这样只会在实际请求时(而不是创建列表时)创建 OpenAI 对象
264+
const client_builder = (model: string): IChat => {
265+
let base_client = new OpenAI({
266+
apiKey: env.OPENAI_API_KEY,
267+
})
268+
if (oldModels.includes(model)) {
269+
return openaiBase({ createClient: () => base_client })
270+
} else {
271+
return openaiResponse({ createClient: () => base_client })
272+
}
273+
}
266274
return {
267275
name: 'openai',
268276
supportModels: [...oldModels, ...newModels],
269277
requiredEnv: ['OPENAI_API_KEY'],
270-
invoke(req) {
271-
const oldCllient = openaiBase({ createClient: () => client })
272-
const newClient = openaiResponse({ createClient: () => client })
273-
if (oldModels.includes(req.model)) {
274-
return oldCllient.invoke(req)
275-
} else {
276-
return newClient.invoke(req)
277-
}
278-
},
279-
stream(req, signal) {
280-
const oldCllient = openaiBase({ createClient: () => client })
281-
const newClient = openaiResponse({ createClient: () => client })
282-
if (oldModels.includes(req.model)) {
283-
return oldCllient.stream(req, signal)
284-
} else {
285-
return newClient.stream(req, signal)
286-
}
287-
},
278+
invoke: (req) => client_builder(req.model).invoke(req),
279+
stream: (req, signal) => client_builder(req.model).stream(req, signal),
288280
}
289281
}

0 commit comments

Comments
 (0)