add query-ai

This commit is contained in:
2025-03-02 12:14:09 +08:00
parent 3a8396279b
commit 64aa095ffe
3 changed files with 80 additions and 4 deletions

58
src/query-ai.ts Normal file
View File

@@ -0,0 +1,58 @@
import OpenAI, { ClientOptions } from 'openai';
import type { RequestOptions } from 'openai/core.mjs';
type QueryOpts = {
/**
* OpenAI model name, example: deepseek-chat
*/
model: string;
/**
* OpenAI client options
* QueryAi.init() will be called with these options
*/
openAiOpts?: ClientOptions;
openai?: OpenAI;
};
export class QueryAI {
private openai: OpenAI;
model?: string;
constructor(opts?: QueryOpts) {
this.model = opts?.model;
if (opts?.openai) {
this.openai = opts.openai;
} else if (opts?.openAiOpts) {
this.init(opts?.openAiOpts);
}
}
init(opts: ClientOptions) {
this.openai = new OpenAI(opts);
}
async query(prompt: string, opts?: RequestOptions) {
return this.openai.chat.completions.create({
model: this.model,
messages: [
{
role: 'system',
content: prompt,
},
],
stream: false,
...opts,
});
}
async queryAsync(prompt: string, opts?: RequestOptions) {
return this.openai.chat.completions.create({
model: this.model,
messages: [
{
role: 'system',
content: prompt,
},
],
stream: true,
...opts,
});
}
}
export { OpenAI };