feat: add chatStream

This commit is contained in:
熊潇 2025-05-09 19:50:32 +08:00
parent 4a2d3e8d32
commit 2338242018
4 changed files with 15 additions and 5 deletions

View File

@ -1,5 +1,5 @@
import { OpenAI } from 'openai'; import { OpenAI } from 'openai';
import type { BaseChatInterface, ChatMessageComplete, ChatMessage, ChatMessageOptions, BaseChatUsageInterface } from './type.ts'; import type { BaseChatInterface, ChatMessageComplete, ChatMessage, ChatMessageOptions, BaseChatUsageInterface, ChatStream } from './type.ts';
export type BaseChatOptions<T = Record<string, any>> = { export type BaseChatOptions<T = Record<string, any>> = {
/** /**
@ -87,7 +87,7 @@ export class BaseChat implements BaseChatInterface, BaseChatUsageInterface {
if (createParams.response_format) { if (createParams.response_format) {
throw new Error('response_format is not supported in stream mode'); throw new Error('response_format is not supported in stream mode');
} }
return this.openai.chat.completions.create(createParams) as any; return this.openai.chat.completions.create(createParams) as unknown as ChatStream;
} }
/** /**

View File

@ -1,2 +1,10 @@
import { ChatStream } from './type.ts';
export * from './chat.ts'; export * from './chat.ts';
export * from './type.ts'; export * from './type.ts';
export const readStream = async (chatStream: ChatStream) => {
for await (const chunk of chatStream) {
console.log(chunk);
}
};

View File

@ -23,3 +23,5 @@ export interface BaseChatUsageInterface {
*/ */
completion_tokens: number; completion_tokens: number;
} }
export type ChatStream = AsyncGenerator<ChatMessageComplete, void, unknown>;

View File

@ -13,10 +13,10 @@ const main = async () => {
console.log(usage); console.log(usage);
}; };
// main(); main();
const mainChat = async () => { const mainChat = async () => {
const res = await siliconflow.chat([{ role: 'user', content: 'Hello, world! 1 + 1 equals ?' }]); const res = await siliconflow.chat([{ role: 'user', content: 'Hello, world! 1 + 1 equals ?' }]);
console.log(res); console.log(res);
}; };
mainChat(); // mainChat();