From a0a22696276b017a256bfa9c73ddb6ecb0bbc247 Mon Sep 17 00:00:00 2001 From: yhostc Date: Tue, 21 May 2024 14:11:46 +0800 Subject: [PATCH] chore: update --- packages/bodhi-adapter/dist/index.cjs | 9 +++++++-- packages/bodhi-adapter/dist/index.cjs.map | 2 +- packages/bodhi-adapter/dist/index.js | 9 +++++++-- packages/bodhi-adapter/dist/index.js.map | 2 +- packages/bodhi-adapter/package.json | 2 +- .../bodhi-adapter/src/provider/google/gemini.ts | 3 +++ .../bodhi-adapter/src/provider/google/vertex.ts | 6 +++++- packages/bodhi-adapter/test/aliyun-qwen.test.ts | 17 ++++++++++++++++- 8 files changed, 41 insertions(+), 9 deletions(-) diff --git a/packages/bodhi-adapter/dist/index.cjs b/packages/bodhi-adapter/dist/index.cjs index 02148fa..b39c2cc 100644 --- a/packages/bodhi-adapter/dist/index.cjs +++ b/packages/bodhi-adapter/dist/index.cjs @@ -520,7 +520,9 @@ ${part.text} choices.push({ index, role: 'assistant', parts, finish_reason: 'stop' }); }); } catch (err) { + console.log(`->candidates1`, JSON.stringify(candidates, null, 2)); console.warn(err); + console.log(`->candidates2`); } return choices; } @@ -584,7 +586,10 @@ var GoogleVertexAPI = class extends GoogleGeminiAPI { const parser = (0, import_eventsource_parser3.createParser)((event) => { if (event.type === 'event') { const res2 = JSON.parse(event.data); - const choices = this.convertChoices(res2.candidates); + if (!res2.candidates) { + console.log(`[vertex]debug`, res2); + } + const choices = this.convertChoices(res2.candidates || []); if (res2.usageMetadata) { Object.assign(usage, { prompt_tokens: res2.usageMetadata.promptTokenCount, @@ -635,7 +640,7 @@ var GoogleClaudeAPI = class extends ChatBaseAPI { return await auth.getAccessToken(); } models() { - return ['claude-3-sonnet@20240229', 'claude-3-haiku@20240307']; + return ['claude-3-sonnet@20240229', 'claude-3-haiku@20240307', 'gemini-1.5-flash-preview-0514']; } /** * Send message diff --git a/packages/bodhi-adapter/dist/index.cjs.map b/packages/bodhi-adapter/dist/index.cjs.map index 0c51f14..e737cdf 100644 --- a/packages/bodhi-adapter/dist/index.cjs.map +++ b/packages/bodhi-adapter/dist/index.cjs.map @@ -1 +1 @@ -{"version":3,"sources":["../src/index.ts","../src/types/provider.ts","../src/provider/openai/completions.ts","../src/types/chat.ts","../src/provider/base.ts","../src/provider/openai/assistants.ts","../src/provider/google/vertex.ts","../src/provider/google/gemini.ts","../src/provider/google/claude.ts","../src/provider/anthropic/claude.ts","../src/provider/anthropic/bedrock.ts","../src/provider/anthropic/auth.ts","../src/provider/aliyun/qwen.ts","../src/provider/aliyun/wanx.ts","../src/provider/moonshot/kimi.ts","../src/provider/qcloud/hunyuan.ts","../src/provider/deepseek/deepseek.ts","../src/provider/groq/completions.ts","../src/api/chat.ts","../src/api/image.ts"],"sourcesContent":["export * from './api';\nexport * from './types';\n","export enum Provider {\n GOOGLE_GEMINI = 'google-gemini',\n GOOGLE_VERTEX = 'google-vertex',\n GOOGLE_CLAUDE = 'google-claude',\n OPENAI_COMPLETIONS = 'openai-completion',\n OPENAI_ASSISTANTS = 'openai-assistant',\n ANTHROPIC_CLAUDE = 'anthropic-claude',\n ANTHROPIC_BEDROCK = 'anthropic-bedrock',\n ALIYUN_QWEN = 'aliyun-qwen',\n ALIYUN_WANX = 'aliyun-wanx',\n QCLOUD_HUNYUAN = 'qcloud-hunyuan',\n MOONSHOT_KIMI = 'moonshot-kimi',\n DEEPSEEK = 'deepseek',\n GROQ = 'groq',\n}\n","import fetchSSE from 'node-fetch';\nimport { v4 as uuidv4 } from 'uuid';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { ChatBaseAPI } from '../base';\nimport { openai } from './types';\n\nexport class OpenAICompletionsAPI extends ChatBaseAPI {\n protected provider: string = 'openai';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://api.openai.com/v1' }, opts);\n super(options);\n }\n\n public models(): string[] {\n return [\n 'gpt-3.5-turbo',\n 'gpt-3.5-turbo-0125',\n 'gpt-3.5-turbo-16k',\n 'gpt-3.5-turbo-instruct',\n 'gpt-4',\n 'gpt-4-0125-preview',\n 'gpt-4-turbo-preview',\n 'gpt-4-32k',\n ];\n }\n\n async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n\n return new Promise(async (resolove, reject) => {\n const url = `${this.baseURL}/chat/completions`;\n const params: openai.Request = await this.convertParams(options);\n // console.log(`[fetch]params`, JSON.stringify(params, null, 2));\n const res = await fetchSSE(url, {\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${this.apiKey}` },\n body: JSON.stringify(params),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.error?.message || 'request error', res.status));\n }\n\n // not stream\n if (params.stream === false) {\n const result = await res.json();\n const choices = this.convertChoices(result.choices);\n const usage = result?.usage;\n resolove({ id: uuidv4(), model: opts.model, choices, usage });\n } else {\n // streaming\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n const choicesList: types.chat.Choice[] = [];\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n if (event.type === 'event') {\n if (event.data !== '[DONE]') {\n try {\n const result = JSON.parse(event.data);\n const choices = this.convertChoices(result.choices);\n onProgress?.(choices);\n choicesList.push(...choices);\n } catch (e) {\n // ignore\n }\n }\n }\n });\n body.on('readable', async () => {\n let chunk: string | Buffer;\n while ((chunk = body.read())) {\n parser.feed(chunk.toString());\n }\n });\n\n body.on('end', async () => {\n const choices: types.chat.Choice[] = this.combineChoices(choicesList);\n const usage = this.caclulateUsage(opts.messages, choices);\n resolove({ id: uuidv4(), model: opts.model, choices, usage });\n });\n }\n });\n }\n\n /**\n * 转换为 Gemini 要求的请求参数\n * https://platform.openai.com/docs/api-reference/chat/create\n * @returns\n */\n private async convertParams(opts: types.chat.SendOptions): Promise {\n const params: openai.Request = {\n model: opts.model || 'gpt-3.5-turbo-0125',\n messages: await this.corvertContents(opts),\n temperature: opts?.temperature || 0.9,\n top_p: opts?.top_p || 1,\n // frequency_penalty: 0,\n // presence_penalty: 0,\n max_tokens: opts?.max_tokens || 1000,\n n: opts.n || 1,\n stop: opts?.stop_sequences || undefined,\n stream: true,\n };\n // tools\n if (opts.tools && opts.tools.length > 0) {\n Object.assign(params, { tools: opts.tools, stream: false });\n }\n return params;\n }\n\n private async corvertContents(opts: types.chat.SendOptions): Promise {\n return Promise.all(\n opts.messages.map(async (item) => {\n const parts: openai.Part[] = [];\n const tool_calls: openai.ToolCallPart[] = [];\n await Promise.all(\n item.parts.map(async (part: types.chat.Part) => {\n // text\n if (part.type === 'text') {\n parts.push({ type: 'text', text: part.text });\n }\n // file: docs\n if (part.type === 'file' && part?.extract) {\n parts.push({ type: 'text', text: part.extract });\n }\n // file, only support image, now\n if (part.type === 'file' && part.mimetype?.startsWith('image')) {\n // TODO: fetch 下载图片并转化buffer为base64\n // parts.push({ type: 'image_url', image_url: (part as types.chat.FilePart).url });\n parts.push({ type: 'image_url', image_url: { url: (part as types.chat.FilePart).url } });\n }\n // tools\n if (part.type === 'function_call' && part.id) {\n const { name, args } = part.function_call;\n tool_calls.push({ id: part.id, type: 'function', function: { name, arguments: args } });\n }\n }),\n );\n if (item.role === 'system') {\n return { role: 'system', content: this.filterTextPartsToString(parts) } as openai.Message;\n }\n if (item.role === 'assistant') {\n return {\n role: 'assistant',\n content: parts,\n tool_calls: tool_calls.length > 0 ? tool_calls : undefined,\n } as openai.Message;\n }\n return { role: 'user', content: parts } as openai.Message;\n }),\n );\n }\n\n private filterTextPartsToString(parts: openai.Part[]): string {\n return parts\n .filter((p) => p.type === 'text')\n .map((p) => (p as openai.TextPart).text)\n .join('');\n }\n\n protected convertChoices(candidates: openai.Choice[]): types.chat.Choice[] {\n const choices: types.chat.Choice[] = [];\n try {\n candidates.map(({ index, delta, message, finish_reason }: openai.Choice) => {\n const parts: types.chat.Part[] = [];\n let { content, tool_calls } = message || delta;\n if (delta) {\n content = delta.content;\n tool_calls = delta.tool_calls;\n }\n if (content) {\n parts.push({ type: 'text', text: content });\n }\n if (tool_calls) {\n tool_calls.map((call: any) => {\n const { name, arguments: args } = call.function;\n parts.push({ type: 'function_call', function_call: { name, args }, id: call.id });\n });\n }\n\n choices.push({ index, role: 'assistant', parts, finish_reason });\n });\n } catch (err) {\n console.warn(err);\n }\n return choices;\n }\n}\n","/**\n * Chat\n */\nexport namespace chat {\n export class ChatError extends Error {\n name: 'ChatError';\n code: number;\n constructor(message: string, code: number) {\n super(message);\n this.code = code;\n }\n }\n\n export type ChatOptions = {\n agent?: string;\n baseURL?: string;\n apiKey: string;\n apiSecret?: string;\n timeout?: number;\n };\n\n /**\n * Request\n */\n export type SendOptions = {\n model: string;\n messages: Message[];\n tools?: Tools[];\n temperature?: number;\n top_p?: number;\n top_k?: number;\n n?: number;\n max_tokens?: number;\n stop_sequences?: string[];\n stream?: boolean;\n onProgress?: (event: any) => void;\n };\n\n /* Message */\n export type Message = { role: string; parts: Part[] };\n\n export type Part = TextPart | FilePart | ToolPart;\n export type TextPart = { type: 'text'; text: string };\n export type FilePart = { type: 'file'; mimetype: string; url: string; id: string; extract?: string };\n export type ToolPart = FunctionCallTool | FunctionTool;\n\n /* Tools */\n export type Tools = FunctionTool;\n export type FunctionCallTool = {\n type: 'function_call';\n function_call: { name: string; args: any };\n id?: string | undefined;\n };\n export type FunctionTool = { type: 'function'; function: Function };\n\n export type Function = {\n name: string;\n description: string;\n parameters: { type: string; properties: any; required: string[] };\n };\n\n /**\n * Response\n */\n export type ChatResponse = {\n id: string;\n model: string;\n choices: Choice[];\n usage: Usage;\n };\n\n export type Choice = {\n index: number;\n role: string;\n parts: Part[];\n finish_reason: 'stop' | 'function_call' | string | null;\n };\n\n export type Usage = { prompt_tokens: number; completion_tokens: number; total_tokens: number };\n}\n","import { get_encoding } from 'tiktoken';\nimport fetch from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport * as types from '@/types';\n\nexport class ChatBaseAPI {\n protected provider: string = '';\n\n protected agent?: string = '';\n protected baseURL: string = '';\n protected apiKey: string = '';\n protected apiSecret?: string = '';\n protected timeout?: number = 10000;\n\n constructor(opts: types.chat.ChatOptions) {\n opts.agent && (this.agent = opts.agent);\n opts.baseURL && (this.baseURL = opts.baseURL);\n opts.apiKey && (this.apiKey = opts.apiKey);\n opts.apiSecret && (this.apiSecret = opts.apiSecret);\n opts.timeout && (this.timeout = opts.timeout);\n }\n\n public models(): string[] {\n throw new Error('Not implemented');\n }\n\n public async sendMessage(opts: types.chat.SendOptions | types.image.SendOptions): Promise {\n throw new Error('Not implemented');\n }\n\n public async getTaskResult(task_id: string): Promise {\n throw new Error('Not implemented');\n }\n\n protected async fetchFile(url: string) {\n const response = await fetch(url, {\n headers: {\n 'user-agent':\n 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',\n },\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n });\n const buffer = await response.buffer();\n const base64 = buffer.toString('base64');\n const mimeType = response.headers.get('content-type') as string;\n return { mimeType, data: base64 };\n }\n\n protected combineChoices(choices: types.chat.Choice[]): types.chat.Choice[] {\n return choices.reduce((acc: types.chat.Choice[], item: types.chat.Choice) => {\n const existingItem = acc.find((i: types.chat.Choice) => i.index === item.index);\n if (existingItem) {\n item.parts.forEach((part: types.chat.Part) => {\n if (part.type === 'text') {\n const existingPart = existingItem.parts.find((p: types.chat.Part) => p.type === 'text');\n if (existingPart) {\n (existingPart as types.chat.TextPart).text += (part as types.chat.TextPart).text;\n } else {\n existingItem.parts.push(part);\n }\n } else if (part.type === 'function_call') {\n const existingPart = existingItem.parts.find((p: types.chat.Part) => p.type === 'function_call');\n if (existingPart) {\n (existingPart as types.chat.FunctionCallTool).function_call.name +=\n (part as types.chat.FunctionCallTool).function_call.name || '';\n (existingPart as types.chat.FunctionCallTool).function_call.args +=\n (part as types.chat.FunctionCallTool).function_call.args || '';\n } else {\n existingItem.parts.push(part);\n }\n } else {\n const existingPart = existingItem.parts.find(\n (p: types.chat.Part) => JSON.stringify(p) === JSON.stringify(part),\n );\n if (!existingPart) {\n existingItem.parts.push(part);\n }\n }\n });\n\n // finish_reason\n existingItem.finish_reason = item.finish_reason;\n } else {\n acc.push(item);\n }\n return acc;\n }, []);\n }\n\n protected caclulateUsage(messages: types.chat.Message[], choices: types.chat.Choice[]): types.chat.Usage {\n const parts: types.chat.Part[] = messages.flatMap((item) => item.parts);\n const prompt_tokens = parts\n .filter((p) => p.type === 'text' || (p.type === 'file' && p.extract))\n .reduce((acc: number, item) => {\n return acc + this.getTokenCount((item as types.chat.TextPart)?.text || (item as types.chat.FilePart)?.extract);\n }, 0);\n const completion_tokens = choices.reduce((acc: number, item: types.chat.Choice) => {\n return acc + this.getTokenCount(item.parts.map((part) => (part as types.chat.TextPart).text).join(''));\n }, 0);\n return { prompt_tokens, completion_tokens, total_tokens: prompt_tokens + completion_tokens };\n }\n\n protected getTokenCount(text: string) {\n return get_encoding('cl100k_base').encode(text).length;\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { ChatBaseAPI } from '../base';\n\nexport class OpenAIAssistantsAPI extends ChatBaseAPI {\n protected provider: string = 'openai';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://api.openai.com/v1' }, opts);\n super(options);\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { v4 as uuidv4 } from 'uuid';\nimport { GoogleAuth } from 'google-auth-library';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { GoogleGeminiAPI } from './gemini';\nimport { gemini } from './types';\n\nexport class GoogleVertexAPI extends GoogleGeminiAPI {\n protected provider: string = 'google';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign(\n {\n baseURL: 'https://us-central1-aiplatform.googleapis.com/v1/projects/bodhi-415003/locations/us-central1',\n },\n opts,\n );\n super(options);\n }\n\n public models(): string[] {\n return ['gemini-1.0-pro', 'gemini-1.5-pro-preview-0409'];\n }\n\n /**\n * 根据服务账号获取 access token\n */\n private async getToken(): Promise {\n const auth: GoogleAuth = new GoogleAuth({\n credentials: { client_email: this.apiKey, private_key: this.apiSecret },\n scopes: 'https://www.googleapis.com/auth/cloud-platform',\n });\n return (await auth.getAccessToken()) as string;\n }\n\n /**\n * 发送消息\n * @param opts \n * Reference: https://cloud.google.com/vertex-ai/docs/reference/rest/v1/GenerateContentResponse\n * Reference: https://cloud.google.com/vertex-ai/docs/generative-ai/model-reference/gemini?hl=zh-cn\n * Multi-modal: https://cloud.google.com/vertex-ai/docs/generative-ai/multimodal/send-multimodal-prompts?hl=zh-cn#gemini-send-multimodal-samples-drest\n * Tools: https://cloud.google.com/vertex-ai/docs/generative-ai/multimodal/function-calling?hl=zh-cn\n * @returns\n */\n public async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n\n return new Promise(async (resolove, reject) => {\n const token = await this.getToken();\n const model = this.detechModel(opts);\n const url = `${this.baseURL}/publishers/google/models/${model}:streamGenerateContent?alt=sse`;\n const params: gemini.Request = await this.convertParams(options);\n // console.log(`[fetch]params`, model, url, opts.messages);\n\n const res = await fetchSSE(url, {\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },\n body: JSON.stringify(params),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.error?.message || 'request error', res.status));\n }\n\n // only get content from node-fetch\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n // streaming\n const choicesList: types.chat.Choice[] = [];\n const usage: types.chat.Usage = { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n if (event.type === 'event') {\n const res = JSON.parse(event.data);\n const choices = this.convertChoices(res.candidates);\n if (res.usageMetadata) {\n Object.assign(usage, {\n prompt_tokens: res.usageMetadata.promptTokenCount,\n completion_tokens: res.usageMetadata.candidatesTokenCount,\n total_tokens: res.usageMetadata.totalTokenCount,\n });\n }\n onProgress?.(choices);\n choicesList.push(...choices);\n }\n });\n body.on('readable', async () => {\n let chunk: string | Buffer;\n while ((chunk = body.read())) {\n parser.feed(chunk.toString());\n }\n });\n\n // finished\n body.on('end', () => {\n const choices: types.chat.Choice[] = this.combineChoices(choicesList);\n // TODO: Google AI Gemini not found usageMetadata, but vertex founded.\n resolove({ id: uuidv4(), model: opts.model, choices, usage });\n });\n });\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { v4 as uuidv4 } from 'uuid';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { gemini } from './types';\nimport { ChatBaseAPI } from '../base';\n\nexport class GoogleGeminiAPI extends ChatBaseAPI {\n protected provider: string = 'google';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://generativelanguage.googleapis.com/v1beta' }, opts);\n super(options);\n }\n\n public models(): string[] {\n return ['gemini-pro', 'gemini-pro-vision', 'gemini-1.5-pro-latest'];\n }\n\n /**\n *\n * https://ai.google.dev/docs/gemini_api_overview?hl=zh-cn#curl_3\n * @param opts\n * @returns\n */\n public async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n return new Promise(async (resolove, reject) => {\n const params: gemini.Request = await this.convertParams(options);\n const model = this.detechModel(opts);\n const url = `${this.baseURL}/models/${model}:streamGenerateContent?alt=sse`;\n // console.log(`[fetch]params`, url, JSON.stringify(params, null, 2));\n\n const res = await fetchSSE(url, {\n headers: { 'Content-Type': 'application/json', 'x-goog-api-key': this.apiKey },\n body: JSON.stringify(params),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n // console.log(`[fetch]result`, res);\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.error?.message || 'request error', res.status));\n }\n\n // only get content from node-fetch\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n // streaming\n const choicesList: types.chat.Choice[] = [];\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n if (event.type === 'event') {\n const res = JSON.parse(event.data);\n // console.log(`->`, JSON.stringify(res));\n const choices = this.convertChoices(res.candidates);\n onProgress?.(choices);\n\n choicesList.push(...choices);\n }\n });\n body.on('readable', async () => {\n let chunk: string | Buffer;\n while ((chunk = body.read())) {\n parser.feed(chunk.toString());\n }\n });\n\n body.on('end', () => {\n const choices: types.chat.Choice[] = this.combineChoices(choicesList);\n // TODO: Google AI Gemini not found usageMetadata, but vertex founded.\n const usage = { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };\n resolove({ id: uuidv4(), model: opts.model, choices, usage });\n });\n });\n }\n\n protected detechModel(opts: types.chat.SendOptions): string {\n const hasMedia = opts.messages.some((item) =>\n item.parts.some(\n (part) =>\n part.type === 'file' &&\n (part.mimetype.startsWith('image') || part.mimetype.startsWith('video') || part.mimetype.startsWith('audio')),\n ),\n );\n return hasMedia && opts.model === 'gemini-1.0-pro' ? 'gemini-1.0-pro-vision' : opts.model;\n }\n\n /**\n * 转换为 Gemini 要求的请求参数\n * https://cloud.google.com/vertex-ai/docs/reference/rest/v1/GenerateContentResponse\n * @returns\n */\n protected async convertParams(opts: types.chat.SendOptions): Promise {\n return {\n contents: await this.corvertContents(opts),\n // systemInstruction: await this.corvertSystemContent(opts),\n tools: this.corvertTools(opts),\n safety_settings: [\n // { category: 'BLOCK_NONE', threshold: 'HARM_CATEGORY_UNSPECIFIED' },\n ],\n generationConfig: {\n temperature: opts.temperature || 0.9, // gemini-pro:0.9, gemini-pro-vision:0.4\n topP: opts.top_p || 1, // gemini-pro:none, gemini-pro-vision:32\n // topK: Math.round((opts.top_k || 0.025) * 40) || 32,\n candidateCount: opts.n || 1,\n maxOutputTokens: opts.max_tokens || 2048, // gemini-pro:2048, gemini-pro-vision:8192\n stopSequences: opts.stop_sequences || undefined,\n },\n };\n }\n\n protected async corvertContents(opts: types.chat.SendOptions): Promise {\n // filter system role\n const rows = await Promise.all(\n opts.messages\n .filter((item) => ['user', 'assistant'].includes(item.role))\n .map(async (item) => {\n const parts: gemini.Part[] = [];\n await Promise.all(\n item.parts.map(async (part: types.chat.Part) => {\n // text\n if (part.type === 'text') {\n parts.push({ text: part.text });\n }\n // file\n if (part.type === 'file') {\n if (part?.extract) {\n parts.push({ text: part.extract });\n } else {\n const { mimetype: mimeType, url } = part as types.chat.FilePart;\n if (url.startsWith('gs://')) {\n parts.push({ fileData: { mimeType, fileUri: url } });\n } else {\n try {\n parts.push({ inlineData: await this.fetchFile(url) });\n } catch (err) {}\n }\n }\n }\n // tools\n if (part.type === 'function_call') {\n const { name, args } = part.function_call;\n parts.push({ functionCall: { name, args } });\n }\n }),\n );\n item.role = item.role === 'assistant' ? 'model' : item.role;\n return { role: item.role, parts } as gemini.Content;\n }),\n );\n\n // Compatible with system role\n // insert system text part to rows's first user parts\n const system = opts.messages.filter((item) => item.role === 'system');\n if (system.length > 0) {\n const textParts = system[0].parts.filter((part) => 'text' in part) as gemini.TextPart[];\n rows[0].parts.unshift(...textParts.map((part) => ({ text: `[instructions]\\n${part.text}\\n\\n[user prompt]\\n` })));\n }\n\n return rows;\n }\n\n protected corvertTools(opts: types.chat.SendOptions): gemini.Tools[] {\n const tools: gemini.Tools[] = [];\n if (opts.tools) {\n opts.tools.map((item) => {\n if (item.type === 'function') {\n tools.push({ functionDeclarations: [item.function] });\n }\n });\n }\n return tools;\n }\n\n protected convertChoices(candidates: gemini.Candidate[]): types.chat.Choice[] {\n const choices: types.chat.Choice[] = [];\n try {\n candidates.map(({ index, content, finishReason }: gemini.Candidate) => {\n const parts: types.chat.Part[] = [];\n content.parts.map((part: any) => {\n if ('text' in part) {\n parts.push({ type: 'text', text: part.text });\n }\n if ('functionCall' in part) {\n parts.push({ type: 'function_call', function_call: part.functionCall });\n }\n });\n choices.push({ index, role: 'assistant', parts, finish_reason: 'stop' });\n });\n } catch (err) {\n console.warn(err);\n }\n return choices;\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { GoogleAuth } from 'google-auth-library';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { claude } from '../anthropic/types';\nimport { ChatBaseAPI } from '../base';\n\nexport class GoogleClaudeAPI extends ChatBaseAPI {\n protected provider: string = 'google';\n\n constructor(opts: types.chat.ChatOptions) {\n // available models: claude-instant-1p2(100K tokens), claude-2p0(200K tokens)\n // available regions: us-central1(60QPM), asia-southeast1(60QPM)\n const options = Object.assign(\n { baseURL: 'https://us-central1-aiplatform.googleapis.com/v1/projects/bodhi-415003/locations/us-central1' },\n opts,\n );\n super(options);\n }\n\n /**\n * 根据服务账号获取 access token\n */\n private async getToken(): Promise {\n const auth: GoogleAuth = new GoogleAuth({\n credentials: { client_email: this.apiKey, private_key: this.apiSecret },\n scopes: 'https://www.googleapis.com/auth/cloud-platform',\n });\n return (await auth.getAccessToken()) as string;\n }\n\n public models(): string[] {\n return ['claude-3-sonnet@20240229', 'claude-3-haiku@20240307'];\n }\n\n /**\n * Send message\n * https://docs.anthropic.com/claude/reference/messages_post\n * @param opts\n * @returns\n */\n public async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n return new Promise(async (resolove, reject) => {\n const token = await this.getToken();\n const url = `${this.baseURL}/publishers/anthropic/models/${opts.model}:streamRawPredict?alt=sse`;\n const params: claude.Request = await this.convertParams(options);\n // console.log(`->url`, url, JSON.stringify(params));\n const res = await fetchSSE(url, {\n headers: { 'content-type': 'application/json', Authorization: `Bearer ${token}` },\n body: JSON.stringify(params),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.error?.message || 'request error', res.status));\n }\n\n // only get content from node-fetch\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n let response: types.chat.ChatResponse;\n const choicesList: types.chat.Choice[] = [];\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n if (event.type === 'event') {\n const res: claude.Response = JSON.parse(event.data);\n response = this.convertResult(response, res);\n const choices = this.convertChoices(res);\n if (choices.length > 0) {\n onProgress?.(choices);\n choicesList.push(...choices);\n }\n }\n });\n body.on('readable', async () => {\n let chunk: string | Buffer;\n while ((chunk = body.read())) {\n parser.feed(chunk.toString());\n }\n });\n\n body.on('end', () => {\n response.choices = this.combineChoices(choicesList);\n resolove(response);\n });\n });\n }\n\n /**\n * https://docs.anthropic.com/claude/reference/messages-streaming\n * @returns\n */\n private async convertParams(opts: types.chat.SendOptions): Promise {\n return {\n messages: await this.corvertContents(opts),\n system: this.corvertSystem(opts),\n temperature: opts.temperature || 0.8,\n top_p: opts.top_p || 1,\n // top_k: opts.top_k || 1,\n max_tokens: opts.max_tokens || 1024,\n stop_sequences: opts.stop_sequences || [],\n stream: true,\n anthropic_version: 'vertex-2023-10-16',\n };\n }\n\n protected corvertSystem(opts: types.chat.SendOptions): string {\n return opts.messages\n .filter((item) => item.role === 'system')\n .map((item) =>\n item.parts\n .filter((p: types.chat.Part) => p.type === 'text')\n .map((p) => (p as types.chat.TextPart).text)\n .join(''),\n )\n .join('\\n');\n }\n\n protected async corvertContents(opts: types.chat.SendOptions): Promise {\n return Promise.all(\n opts.messages\n .filter((item) => item.role !== 'system')\n .map(async (item) => {\n const parts: claude.Part[] = [];\n await Promise.all(\n item.parts.map(async (part: types.chat.Part) => {\n // text\n if (part.type === 'text') {\n parts.push({ type: 'text', text: part.text });\n }\n // file, only support image, now\n if (part.type === 'file' && part?.extract) {\n parts.push({ type: 'text', text: part.extract });\n }\n if (part.type === 'file' && part.mimetype?.startsWith('image')) {\n try {\n const { mimeType: media_type, data } = await this.fetchFile((part as types.chat.FilePart).url);\n parts.push({ type: 'image', source: { type: 'base64', media_type, data } });\n } catch (err) {\n // console.warn(``);\n }\n }\n }),\n );\n return { role: item.role, content: parts } as claude.Content;\n }),\n );\n }\n\n private convertResult(response, res: claude.Response): types.chat.ChatResponse {\n try {\n if (res.type === 'message_start') {\n const { message: m } = res;\n const { input_tokens: prompt_tokens, output_tokens: completion_tokens } = m.usage;\n response = {\n id: m.id,\n model: m.model,\n choices: [],\n usage: { prompt_tokens, completion_tokens, total_tokens: prompt_tokens + completion_tokens },\n };\n }\n\n if (res.type === 'message_delta') {\n const { output_tokens } = res.usage;\n response.usage.completion_tokens = output_tokens;\n response.usage.total_tokens = response.usage.prompt_tokens + output_tokens;\n }\n } catch (err) {\n console.warn(err);\n }\n return response;\n }\n\n private convertChoices(res: claude.Response): types.chat.Choice[] {\n const choices: types.chat.Choice[] = [];\n try {\n if (res.type === 'content_block_start') {\n const { index, content_block: c } = res;\n choices.push({ index, role: 'assistant', parts: [{ type: 'text', text: c.text }], finish_reason: null });\n }\n\n if (res.type === 'content_block_delta') {\n const { index, delta: d } = res;\n choices.push({ index, role: 'assistant', parts: [{ type: 'text', text: d.text }], finish_reason: null });\n }\n\n if (res.type === 'content_block_stop') {\n const { index } = res;\n choices.push({ index, role: 'assistant', parts: [], finish_reason: 'stop' });\n }\n } catch (err) {\n console.warn(err);\n }\n return choices;\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { claude } from './types';\nimport { ChatBaseAPI } from '../base';\n\nexport class AnthropicClaudeAPI extends ChatBaseAPI {\n protected provider: string = 'anthropic';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://api.anthropic.com' }, opts);\n super(options);\n }\n\n public models(): string[] {\n return [\n 'claude-3-opus-20240229',\n 'claude-3-sonnet-20240229',\n 'claude-3-haiku-20240307',\n 'claude-2.1',\n 'claude-2.0',\n 'claude-instant-1.2',\n ];\n }\n\n /**\n * Send message\n * https://docs.anthropic.com/claude/reference/messages_post\n * @param opts\n * @returns\n */\n public async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n return new Promise(async (resolove, reject) => {\n const url = `${this.baseURL}/v1/messages`;\n const params: claude.Request = await this.convertParams(options);\n const res = await fetchSSE(url, {\n headers: {\n 'content-type': 'application/json',\n 'anthropic-version': '2023-06-01',\n 'x-api-key': this.apiKey,\n },\n body: JSON.stringify(params),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.error?.message || 'request error', res.status));\n }\n\n // only get content from node-fetch\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n let response: types.chat.ChatResponse;\n const choicesList: types.chat.Choice[] = [];\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n if (event.type === 'event') {\n const res: claude.Response = JSON.parse(event.data);\n response = this.convertResult(response, res);\n const choices = this.convertChoices(res);\n if (choices.length > 0) {\n onProgress?.(choices);\n choicesList.push(...choices);\n }\n }\n });\n body.on('readable', async () => {\n let chunk: string | Buffer;\n while ((chunk = body.read())) {\n parser.feed(chunk.toString());\n }\n });\n\n body.on('end', () => {\n response.choices = this.combineChoices(choicesList);\n resolove(response);\n });\n });\n }\n\n /**\n * https://docs.anthropic.com/claude/reference/messages-streaming\n * @returns\n */\n private async convertParams(opts: types.chat.SendOptions): Promise {\n return {\n model: opts.model || 'claude-3-haiku-20240307',\n messages: await this.corvertContents(opts),\n system: this.corvertSystem(opts),\n temperature: opts.temperature || 0.8,\n top_p: opts.top_p || 1,\n // top_k: opts.top_k || 1,\n max_tokens: opts.max_tokens || 1024,\n // metadata:\n stop_sequences: opts.stop_sequences || [],\n stream: true,\n };\n }\n\n protected corvertSystem(opts: types.chat.SendOptions): string {\n return opts.messages\n .filter((item) => item.role === 'system')\n .map((item) =>\n item.parts\n .filter((p: types.chat.Part) => p.type === 'text')\n .map((p) => (p as types.chat.TextPart).text)\n .join(''),\n )\n .join('\\n');\n }\n\n protected async corvertContents(opts: types.chat.SendOptions): Promise {\n return Promise.all(\n opts.messages\n .filter((item) => item.role !== 'system')\n .map(async (item) => {\n const parts: claude.Part[] = [];\n await Promise.all(\n item.parts.map(async (part: types.chat.Part) => {\n // text\n if (part.type === 'text') {\n parts.push({ type: 'text', text: part.text });\n }\n // file, only support image, now\n if (part.type === 'file' && part?.extract) {\n parts.push({ type: 'text', text: part.extract });\n }\n if (part.type === 'file' && part.mimetype?.startsWith('image')) {\n try {\n const { mimeType: media_type, data } = await this.fetchFile((part as types.chat.FilePart).url);\n parts.push({ type: 'image', source: { type: 'base64', media_type, data } });\n } catch (err) {\n // console.warn(``);\n }\n }\n }),\n );\n return { role: item.role, content: parts } as claude.Content;\n }),\n );\n }\n\n private convertResult(response, res: claude.Response): types.chat.ChatResponse {\n try {\n if (res.type === 'message_start') {\n const { message: m } = res;\n const { input_tokens: prompt_tokens, output_tokens: completion_tokens } = m.usage;\n response = {\n id: m.id,\n model: m.model,\n choices: [],\n usage: { prompt_tokens, completion_tokens, total_tokens: prompt_tokens + completion_tokens },\n };\n }\n\n if (res.type === 'message_delta') {\n const { output_tokens } = res.usage;\n response.usage.completion_tokens = output_tokens;\n response.usage.total_tokens = response.usage.prompt_tokens + output_tokens;\n }\n } catch (err) {\n console.warn(err);\n }\n return response;\n }\n\n private convertChoices(res: claude.Response): types.chat.Choice[] {\n const choices: types.chat.Choice[] = [];\n try {\n if (res.type === 'content_block_start') {\n const { index, content_block: c } = res;\n choices.push({ index, role: 'assistant', parts: [{ type: 'text', text: c.text }], finish_reason: null });\n }\n\n if (res.type === 'content_block_delta') {\n const { index, delta: d } = res;\n choices.push({ index, role: 'assistant', parts: [{ type: 'text', text: d.text }], finish_reason: null });\n }\n\n if (res.type === 'content_block_stop') {\n const { index } = res;\n choices.push({ index, role: 'assistant', parts: [], finish_reason: 'stop' });\n }\n } catch (err) {\n console.warn(err);\n }\n return choices;\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { ChatBaseAPI } from '../base';\nimport { requestWithAuth, toUtf8 } from './auth';\n\nexport class AnthropicBedrockAPI extends ChatBaseAPI {\n protected provider: string = 'anthropic';\n\n constructor(opts: types.chat.ChatOptions) {\n super(Object.assign({ baseURL: `https://bedrock-runtime.ap-northeast-1.amazonaws.com` }, opts));\n }\n\n public models(): string[] {\n return ['anthropic.claude-v2:1', 'anthropic.claude-v2', 'anthropic.claude-v1', 'anthropic.claude-instant-v1'];\n }\n\n /**\n * Send message\n * https://docs.anthropic.com/claude/reference/messages_post\n * @param opts\n * @returns\n */\n public async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n\n return new Promise(async (resolove, reject) => {\n const url = new URL(`${this.baseURL}/model/${opts.model}/invoke-with-response-stream`);\n // 预请求并签名\n const req = await requestWithAuth(\n { region: 'ap-northeast-1', service: 'bedrock', accessKeyId: this.apiKey, secretAccessKey: this.apiSecret },\n {\n method: 'POST',\n protocol: url.protocol,\n path: url.pathname,\n headers: {\n host: url.hostname,\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n 'User-Agent': 'AnthropicBedrock/JS 0.6.1',\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': '0.6.1',\n 'X-Stainless-OS': 'MacOS',\n 'X-Stainless-Arch': 'arm64',\n 'X-Stainless-Runtime': 'node',\n 'X-Stainless-Runtime-Version': 'v19.4.0',\n },\n body: JSON.stringify(this.convertParams(options), null, 2),\n },\n );\n // 请求\n const res = await fetchSSE(url, {\n headers: req.headers,\n body: req.body,\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: req.method,\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.message || 'request error', res.status));\n }\n\n // only get content from node-fetch\n let response: any;\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n // if (event.type === 'event') {\n // response = JSON.parse(event.data);\n // onProgress?.(response);\n // }\n console.log(`[bedrock]`, event);\n });\n\n body.on('readable', async () => {\n // 解析SSE 并进行utf8解码\n // let chunk: string | Buffer;\n // while ((chunk = body.read())) {\n // console.log(`[bedrock]`, chunk.toString());\n // // parser.feed(chunk.toString());\n // }\n\n let event;\n while (null !== (event = body.read())) {\n if (Buffer.isBuffer(event)) {\n console.log(`[bedrock]`, event.toString('utf8'));\n }\n }\n });\n\n body.on('end', () => {\n resolove(response);\n });\n });\n }\n\n /**\n * https://docs.anthropic.com/claude/reference/messages-streaming\n * @returns\n */\n private convertParams(opts: types.chat.SendOptions) {\n return {\n prompt: '\\n\\nHuman: Hey Claude! How can I recursively list all files in a directory in Rust?\\n\\nAssistant:',\n temperature: 1,\n // top_k: 250,\n // top_p: 0.999,\n max_tokens_to_sample: 500,\n anthropic_version: 'bedrock-2023-05-31',\n };\n }\n\n // 将 Gemini 的结果转换为你的数据格式\n private convertResult(result: any) {\n return {\n // 根据你的数据格式,从 Gemini 的结果中提取数据\n history: result.contents,\n // 其他数据...\n };\n }\n}\n","import { SignatureV4 } from '@smithy/signature-v4';\nimport { HttpRequest } from '@aws-sdk/protocol-http';\nimport { Sha256 } from '@aws-crypto/sha256-js';\n\nexport const toUtf8 = (input: Uint8Array): string => new TextDecoder('utf-8').decode(input);\n\nexport async function requestWithAuth(options: any, request: any): Promise {\n const { accessKeyId, secretAccessKey, region, service } = options;\n const credentials = { accessKeyId, secretAccessKey };\n // sign request\n const signed = await new SignatureV4({ region, service, sha256: Sha256, credentials }).sign(new HttpRequest(request));\n return signed as HttpRequest;\n}\n","import fetchSSE from 'node-fetch';\nimport { v4 as uuidv4 } from 'uuid';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { ChatBaseAPI } from '../base';\nimport { aliyun } from './types';\n\nexport class AliyunQwenAPI extends ChatBaseAPI {\n protected provider: string = 'google';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://dashscope.aliyuncs.com/api/v1' }, opts);\n super(options);\n }\n\n public models(): string[] {\n return ['qwen-turbo', 'qwen-plus', 'qwen-max'];\n }\n\n /**\n *\n * https://ai.google.dev/docs/gemini_api_overview?hl=zh-cn#curl_3\n * @param opts\n * @returns\n */\n public async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n return new Promise(async (resolove, reject) => {\n // 如果消息存在图片, 则自动切换到 multimodal\n const isMulti =\n opts.model !== 'qwen-turbo' &&\n opts.messages.some((item) => item.parts.some((part) => ['image'].includes(part.type)));\n const model = isMulti ? opts.model.replace('-', '-vl-') : opts.model;\n const url = `${this.baseURL}/services/aigc/${isMulti ? 'multimodal' : 'text'}-generation/generation`;\n const params: aliyun.Request = await this.convertParams(model, options);\n // console.log(`[fetch]params`, JSON.stringify(params, null, 2));\n\n const res = await fetchSSE(url, {\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`,\n 'X-DashScope-SSE': 'enable',\n },\n body: JSON.stringify(params),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.message || 'request error', res.status));\n }\n\n // only get content from node-fetch\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n // streaming\n const choicesList: types.chat.Choice[] = [];\n const usage: types.chat.Usage = { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n if (event.type === 'event') {\n const res = JSON.parse(event.data);\n // console.log(`->`, JSON.stringify(res));\n // success\n if (res?.output) {\n const choices = this.convertChoices(res.output.choices);\n onProgress?.(choices);\n\n if (res.usage) {\n const u = res.usage;\n Object.assign(usage, {\n prompt_tokens: u.input_tokens,\n completion_tokens: u.output_tokens,\n total_tokens: u.total_tokens ? u.total_tokens : u.input_tokens + u.output_tokens,\n });\n }\n choicesList.push(...choices);\n }\n\n // error\n if (res?.code) {\n reject(new types.chat.ChatError(res?.message, 500));\n }\n }\n });\n body.on('readable', async () => {\n let chunk: string | Buffer;\n while ((chunk = body.read())) {\n parser.feed(chunk.toString());\n }\n });\n\n body.on('end', () => {\n const choices: types.chat.Choice[] = this.combineChoices(choicesList);\n resolove({ id: uuidv4(), model: opts.model, choices, usage });\n });\n });\n }\n\n /**\n * Aliyun Qwen API\n * https://help.aliyun.com/zh/dashscope/developer-reference/api-details\n * @returns\n */\n private async convertParams(model, opts: types.chat.SendOptions): Promise {\n const params = {\n model: model || 'qwen-turbo',\n input: {\n messages: await this.corvertContents(opts),\n },\n parameters: {\n temperature: (opts.temperature || 0.85) * 2 - 0.1,\n top_p: opts.top_p || 0.8,\n // top_k: Math.round((opts.top_k || 0.025) * 100) || undefined,\n max_tokens: opts.max_tokens || 1500,\n incremental_output: true,\n enable_search: true,\n },\n };\n // fix different model\n if (model.indexOf('vl') === -1) {\n Object.assign(params.parameters, {\n temperature: opts.temperature || 1,\n max_tokens: opts.max_tokens || 1500,\n enable_search: true,\n stop: opts.stop_sequences || undefined,\n result_format: 'message',\n });\n }\n return params;\n }\n\n private async corvertContents(opts: types.chat.SendOptions): Promise {\n return Promise.all(\n opts.messages.map(async (item) => {\n const parts: aliyun.Part[] = [];\n await Promise.all(\n item.parts.map(async (part: types.chat.Part) => {\n // text\n if (part.type === 'text') {\n parts.push({ text: part.text });\n }\n // file: docs\n if (part.type === 'file' && part?.extract) {\n parts.push({ text: part.extract });\n }\n\n // file, only support image, now\n if (part.type === 'file' && part.mimetype?.startsWith('image')) {\n parts.push({ image: (part as types.chat.FilePart).url });\n }\n }),\n );\n // fix different model\n let content: string | aliyun.Part[] = parts;\n if (!['qwen-vl-plus'].includes(opts.model)) {\n content = parts\n .map((item: any) => {\n return 'text' in item ? item.text : '';\n })\n .join('\\n');\n }\n return { role: item.role, content: parts } as aliyun.Content;\n }),\n );\n }\n\n protected convertChoices(candidates: aliyun.Choice[]): types.chat.Choice[] {\n const choices: types.chat.Choice[] = [];\n try {\n candidates.map(({ message, finish_reason }: aliyun.Choice) => {\n const parts: types.chat.Part[] = [];\n // for text\n if (typeof message.content === 'string') {\n parts.push({ type: 'text', text: message.content });\n }\n // for multimodal\n if (typeof message.content === 'object' && message.content instanceof Array) {\n message.content.map((part: any) => {\n if ('text' in part) {\n parts.push({ type: 'text', text: part.text });\n }\n });\n }\n choices.push({ index: 0, role: 'assistant', parts, finish_reason: 'stop' });\n });\n } catch (err) {\n console.warn(err);\n }\n return choices;\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { ChatBaseAPI } from '../base';\n\nexport class AliyunWanxAPI extends ChatBaseAPI {\n protected provider: string = 'google';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://dashscope.aliyuncs.com/api/v1' }, opts);\n super(options);\n }\n\n public models(): string[] {\n return ['wanx-v1'];\n }\n\n /**\n * https://help.aliyun.com/zh/dashscope/developer-reference/api-details-9\n * @param opts\n * @returns\n */\n public async sendMessage(opts: types.image.SendOptions) {\n return new Promise(async (resolove, reject) => {\n const url = `${this.baseURL}/services/aigc/text2image/image-synthesis`;\n const res = await fetchSSE(url, {\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`,\n 'X-DashScope-Async': 'enable',\n },\n body: JSON.stringify(this.convertParams(opts)),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.message || 'request error', res.status));\n }\n\n try {\n const { output } = await res.json();\n if (output.task_status === 'FAILED') {\n reject(new types.chat.ChatError(output.message, res.status));\n }\n resolove(output);\n } catch (err) {\n reject(new types.chat.ChatError('request error', res.status));\n }\n });\n }\n\n public async getTaskResult(task_id: string) {\n const url = `${this.baseURL}/tasks/${task_id}`;\n return new Promise(async (resolove, reject) => {\n const res = await fetchSSE(url, {\n headers: { Authorization: `Bearer ${this.apiKey}` },\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n });\n\n try {\n const { output } = await res.json();\n if (output.task_status === 'FAILED') {\n reject(new types.chat.ChatError(output.message, res.status));\n }\n\n resolove(output);\n } catch (err) {\n reject(new types.chat.ChatError('request error', res.status));\n }\n });\n }\n\n /**\n * https://help.aliyun.com/zh/dashscope/developer-reference/api-details-9\n * @returns\n */\n private convertParams(opts: types.image.SendOptions) {\n return {\n model: opts.model || 'wanx-v1',\n input: {\n prompt: opts.prompt,\n },\n parameters: {\n style: '',\n size: '1024*1024',\n n: 4,\n seed: 42,\n },\n };\n }\n\n // 将 Gemini 的结果转换为你的数据格式\n private convertResult(result: any) {\n return {\n // 根据你的数据格式,从 Gemini 的结果中提取数据\n history: result.contents,\n // 其他数据...\n };\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { v4 as uuidv4 } from 'uuid';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { ChatBaseAPI } from '../base';\nimport { kimi } from './types';\n\nexport class MoonshotKimiAPI extends ChatBaseAPI {\n protected provider: string = 'moonshot';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://api.moonshot.cn/v1' }, opts);\n super(options);\n }\n\n public models(): string[] {\n return ['moonshot-v1-8k', 'moonshot-v1-32k', 'moonshot-v1-128k'];\n }\n\n async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n\n return new Promise(async (resolove, reject) => {\n const url = `${this.baseURL}/chat/completions`;\n const params: kimi.Request = await this.convertParams(options);\n // console.log(`[fetch]params`, JSON.stringify(params, null, 2));\n\n const res = await fetchSSE(url, {\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${this.apiKey}` },\n body: JSON.stringify(params),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.error?.message || 'request error', res.status));\n return;\n }\n\n // not stream\n let usage = { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };\n if (params.stream === false) {\n const result = await res.json();\n const choices = this.convertChoices(result.choices);\n resolove({ id: uuidv4(), model: opts.model, choices, usage: result.usage });\n } else {\n // streaming\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n const choicesList: types.chat.Choice[] = [];\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n if (event.type === 'event') {\n if (event.data !== '[DONE]') {\n try {\n const result = JSON.parse(event.data);\n const choices = this.convertChoices(result.choices);\n usage = this.convertChoicesUsage(result.choices, usage);\n onProgress?.(choices);\n choicesList.push(...choices);\n } catch (e) {\n // ignore\n }\n }\n }\n });\n body.on('readable', async () => {\n let chunk: string | Buffer;\n while ((chunk = body.read())) {\n parser.feed(chunk.toString());\n }\n });\n\n // console.log(`->`, choicesList);\n body.on('end', async () => {\n const choices: types.chat.Choice[] = this.combineChoices(choicesList);\n resolove({ id: uuidv4(), model: opts.model, choices, usage });\n });\n }\n });\n }\n\n /**\n * 转换为 Gemini 要求的请求参数\n * https://platform.openai.com/docs/api-reference/chat/create\n * @returns\n */\n private async convertParams(opts: types.chat.SendOptions): Promise {\n const params: kimi.Request = {\n model: opts.model || 'moonshot-v1-8k',\n messages: await this.corvertContents(opts),\n temperature: opts?.temperature || 0.9,\n top_p: opts?.top_p || 1.0,\n // frequency_penalty: 0,\n // presence_penalty: 0,\n max_tokens: opts?.max_tokens || 1000,\n n: opts.n || 1,\n stop: opts?.stop_sequences || undefined,\n stream: opts?.stream != undefined ? opts.stream : true,\n };\n // tools\n if (opts.tools && opts.tools.length > 0) {\n Object.assign(params, { tools: opts.tools, stream: false });\n }\n return params;\n }\n\n private async corvertContents(opts: types.chat.SendOptions): Promise {\n return Promise.all(\n opts.messages.map(async (item) => {\n const parts: string[] = [];\n await Promise.all(\n item.parts.map(async (part: types.chat.Part) => {\n // text\n if (part.type === 'text') {\n parts.push(part.text);\n }\n // file, only support image, now\n if (part.type === 'file' && part?.extract) {\n parts.push(part.extract);\n }\n }),\n );\n\n return { role: item.role, content: parts.join('\\n') } as kimi.Message;\n }),\n );\n }\n\n protected convertChoices(candidates: kimi.Choice[]): types.chat.Choice[] {\n const choices: types.chat.Choice[] = [];\n try {\n candidates.map(({ index, delta, message, finish_reason }: kimi.Choice) => {\n const parts: types.chat.Part[] = [];\n let { content } = message || delta;\n if (delta) {\n content = delta.content;\n }\n if (content) {\n parts.push({ type: 'text', text: content });\n }\n\n choices.push({ index, role: 'assistant', parts, finish_reason });\n });\n } catch (err) {\n console.warn(err);\n }\n return choices;\n }\n\n protected convertChoicesUsage(candidates: kimi.Choice[], initial: types.chat.Usage): types.chat.Usage {\n candidates.map(({ usage }: kimi.Choice) => {\n if (usage) {\n initial.prompt_tokens += usage.prompt_tokens;\n initial.completion_tokens += usage.completion_tokens;\n initial.total_tokens += usage.total_tokens;\n }\n });\n return initial;\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { v4 as uuidv4 } from 'uuid';\nimport * as tencentcloud from 'tencentcloud-sdk-nodejs';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { ChatBaseAPI } from '../base';\nimport { hunyuan } from './types';\n\nexport class QcloudHunyuanAPI extends ChatBaseAPI {\n protected provider: string = 'tencent';\n private client: any;\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://hunyuan.tencentcloudapi.com' }, opts);\n super(options);\n\n // init tencentcloud client\n this.client = new tencentcloud.hunyuan.v20230901.Client({\n credential: { secretId: this.apiKey, secretKey: this.apiSecret },\n profile: {\n signMethod: 'TC3-HMAC-SHA256',\n httpProfile: { reqMethod: 'POST', reqTimeout: 30, endpoint: 'hunyuan.tencentcloudapi.com' },\n },\n });\n }\n\n public models(): string[] {\n return ['hunyuan-lite', 'hunyuan-standard', 'hunyuan-pro'];\n }\n\n /**\n * tencent hunyuan\n * https://cloud.tencent.com/document/api/1729/101836\n * @param opts\n * @returns\n */\n public async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n return new Promise(async (resolove, reject) => {\n if (!this.models().includes(opts.model)) {\n reject(new Error(`model ${opts.model} is not supported`));\n }\n\n const params = await this.convertParams(options);\n const response = await this.client.ChatCompletions(params);\n\n // streaming\n let id = uuidv4();\n const choicesList: types.chat.Choice[] = [];\n const usage: types.chat.Usage = { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };\n for await (let message of response) {\n const res = JSON.parse(message.data);\n id = res.Id;\n const choices = this.convertChoices(res.Choices);\n if (res.Usage) {\n Object.assign(usage, {\n prompt_tokens: res.Usage.PromptTokens,\n completion_tokens: res.Usage.CompletionTokens,\n total_tokens: res.Usage.TotalTokens,\n });\n }\n onProgress?.(choices);\n choicesList.push(...choices);\n }\n\n // finished\n const choices: types.chat.Choice[] = this.combineChoices(choicesList);\n resolove({ id, model: opts.model, choices, usage });\n });\n }\n\n /**\n * 转换请求参数\n * @returns\n */\n private async convertParams(opts: types.chat.SendOptions) {\n return {\n Model: opts.model,\n TopP: opts.top_p || 1.0,\n Temperature: opts.temperature || 1.0,\n Messages: await this.corvertContents(opts),\n Stream: true,\n };\n }\n\n private async corvertContents(opts: types.chat.SendOptions): Promise {\n return Promise.all(\n opts.messages.map(async (item) => {\n const parts: string[] = [];\n await Promise.all(\n item.parts.map(async (part: types.chat.Part) => {\n // text\n if (part.type === 'text') {\n parts.push(part.text);\n }\n // file, only support image, now\n if (part.type === 'file' && part?.extract) {\n parts.push(part.extract);\n }\n }),\n );\n return { Role: item.role, Content: parts.join('/n') } as hunyuan.Content;\n }),\n );\n }\n\n protected convertChoices(candidates: hunyuan.Choice[]): types.chat.Choice[] {\n const choices: types.chat.Choice[] = [];\n try {\n candidates.map(({ Delta, FinishReason }: hunyuan.Choice, index) => {\n const parts: types.chat.Part[] = [];\n parts.push({ type: 'text', text: Delta.Content });\n choices.push({ index, role: 'assistant', parts, finish_reason: 'stop' });\n });\n } catch (err) {\n console.warn(err);\n }\n return choices;\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { v4 as uuidv4 } from 'uuid';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { ChatBaseAPI } from '../base';\nimport { deepseek } from './types';\n\nexport class DeepSeekAPI extends ChatBaseAPI {\n protected provider: string = 'moonshot';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://api.deepseek.com' }, opts);\n super(options);\n }\n\n public models(): string[] {\n return ['deepseek-chat'];\n }\n\n async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n\n return new Promise(async (resolove, reject) => {\n const url = `${this.baseURL}/chat/completions`;\n const params: deepseek.Request = await this.convertParams(options);\n // console.log(`[fetch]params`, JSON.stringify(params, null, 2));\n\n const res = await fetchSSE(url, {\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${this.apiKey}` },\n body: JSON.stringify(params),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.error?.message || 'request error', res.status));\n }\n\n // not stream\n if (params.stream === false) {\n const result = await res.json();\n const choices = this.convertChoices(result.choices);\n const usage = result?.usage;\n resolove({ id: uuidv4(), model: opts.model, choices, usage });\n } else {\n // streaming\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n let result;\n const choicesList: types.chat.Choice[] = [];\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n if (event.type === 'event') {\n if (event.data !== '[DONE]') {\n try {\n result = JSON.parse(event.data);\n const choices = this.convertChoices(result.choices);\n onProgress?.(choices);\n choicesList.push(...choices);\n } catch (e) {\n // ignore\n }\n }\n }\n });\n body.on('readable', async () => {\n let chunk: string | Buffer;\n while ((chunk = body.read())) {\n parser.feed(chunk.toString());\n }\n });\n\n body.on('end', async () => {\n const choices: types.chat.Choice[] = this.combineChoices(choicesList);\n resolove({ id: uuidv4(), model: opts.model, choices, usage: result.usage });\n });\n }\n });\n }\n\n /**\n * https://platform.deepseek.com/api-docs/zh-cn/api/create-chat-completion/index.html\n * @returns\n */\n private async convertParams(opts: types.chat.SendOptions): Promise {\n const params: deepseek.Request = {\n model: opts.model || 'moonshot-v1-8k',\n messages: await this.corvertContents(opts),\n temperature: opts?.temperature || 0.9,\n top_p: opts?.top_p || 1.0,\n // frequency_penalty: 0,\n // presence_penalty: 0,\n max_tokens: opts?.max_tokens || 1000,\n // n: opts.n || 1,\n stop: opts?.stop_sequences || undefined,\n stream: true,\n };\n // tools\n if (opts.tools && opts.tools.length > 0) {\n Object.assign(params, { tools: opts.tools, stream: false });\n }\n return params;\n }\n\n private async corvertContents(opts: types.chat.SendOptions): Promise {\n return Promise.all(\n opts.messages.map(async (item) => {\n const parts: string[] = [];\n await Promise.all(\n item.parts.map(async (part: types.chat.Part) => {\n // text\n if (part.type === 'text') {\n parts.push(part.text);\n }\n // file, only support image, now\n if (part.type === 'file' && part?.extract) {\n parts.push(part.extract);\n }\n }),\n );\n\n return { role: item.role, content: parts.join('\\n') } as deepseek.Message;\n }),\n );\n }\n\n protected convertChoices(candidates: deepseek.Choice[]): types.chat.Choice[] {\n const choices: types.chat.Choice[] = [];\n try {\n candidates.map(({ index, delta, message, finish_reason }: deepseek.Choice) => {\n const parts: types.chat.Part[] = [];\n let { content } = message || delta;\n if (delta) {\n content = delta.content;\n }\n if (content) {\n parts.push({ type: 'text', text: content });\n }\n\n choices.push({ index, role: 'assistant', parts, finish_reason });\n });\n } catch (err) {\n console.warn(err);\n }\n return choices;\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { v4 as uuidv4 } from 'uuid';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { ChatBaseAPI } from '../base';\nimport { groq } from './types';\n\nexport class GroqCompletionsAPI extends ChatBaseAPI {\n protected provider: string = 'groq';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://api.groq.com/openai/v1' }, opts);\n super(options);\n }\n\n public models(): string[] {\n return ['llama3-8b-8192', 'llama3-70b-8192', 'mixtral-8x7b-32768', 'gemma-7b-it'];\n }\n\n async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n\n return new Promise(async (resolove, reject) => {\n const url = `${this.baseURL}/chat/completions`;\n const params: groq.Request = await this.convertParams(options);\n // console.log(`[fetch]params`, JSON.stringify(params, null, 2));\n const res = await fetchSSE(url, {\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${this.apiKey}` },\n body: JSON.stringify(params),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.error?.message || 'request error', res.status));\n }\n\n // not stream\n if (params.stream === false) {\n const result = await res.json();\n const choices = this.convertChoices(result.choices);\n const usage = result?.usage;\n resolove({ id: uuidv4(), model: opts.model, choices, usage });\n } else {\n // streaming\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n let result;\n const choicesList: types.chat.Choice[] = [];\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n if (event.type === 'event') {\n if (event.data !== '[DONE]') {\n try {\n result = JSON.parse(event.data);\n const choices = this.convertChoices(result.choices);\n onProgress?.(choices);\n choicesList.push(...choices);\n } catch (e) {\n // ignore\n }\n }\n }\n });\n body.on('readable', async () => {\n let chunk: string | Buffer;\n while ((chunk = body.read())) {\n parser.feed(chunk.toString());\n }\n });\n\n body.on('end', async () => {\n const choices: types.chat.Choice[] = this.combineChoices(choicesList);\n const { prompt_tokens, completion_tokens, total_tokens } = result?.x_groq?.usage;\n const usage = { prompt_tokens, completion_tokens, total_tokens };\n resolove({ id: uuidv4(), model: opts.model, choices, usage });\n });\n }\n });\n }\n\n /**\n * 转换为 Gemini 要求的请求参数\n * https://platform.groq.com/docs/api-reference/chat/create\n * @returns\n */\n private async convertParams(opts: types.chat.SendOptions): Promise {\n const params: groq.Request = {\n model: opts.model || 'gpt-3.5-turbo-0125',\n messages: await this.corvertContents(opts),\n temperature: opts?.temperature || 0.9,\n top_p: opts?.top_p || 1,\n // frequency_penalty: 0,\n // presence_penalty: 0,\n max_tokens: opts?.max_tokens || 1000,\n n: opts.n || 1,\n stop: opts?.stop_sequences || undefined,\n stream: true,\n };\n // tools\n if (opts.tools && opts.tools.length > 0) {\n Object.assign(params, { tools: opts.tools, stream: false });\n }\n return params;\n }\n\n private async corvertContents(opts: types.chat.SendOptions): Promise {\n return Promise.all(\n opts.messages.map(async (item) => {\n const parts: groq.Part[] = [];\n const tool_calls: groq.ToolCallPart[] = [];\n await Promise.all(\n item.parts.map(async (part: types.chat.Part) => {\n // text\n if (part.type === 'text') {\n parts.push({ type: 'text', text: part.text });\n }\n // file: docs\n if (part.type === 'file' && part?.extract) {\n parts.push({ type: 'text', text: part.extract });\n }\n\n // file, only support image, now\n if (part.type === 'file' && part.mimetype?.startsWith('image')) {\n parts.push({ type: 'image_url', image_url: { url: (part as types.chat.FilePart).url } });\n }\n // tools\n if (part.type === 'function_call' && part.id) {\n const { name, args } = part.function_call;\n tool_calls.push({ id: part.id, type: 'function', function: { name, arguments: args } });\n }\n }),\n );\n if (item.role === 'system') {\n return { role: 'system', content: this.filterTextPartsToString(parts) } as groq.Message;\n }\n if (item.role === 'assistant') {\n return {\n role: 'assistant',\n content: parts,\n tool_calls: tool_calls.length > 0 ? tool_calls : undefined,\n } as groq.Message;\n }\n return { role: 'user', content: parts } as groq.Message;\n }),\n );\n }\n\n private filterTextPartsToString(parts: groq.Part[]): string {\n return parts\n .filter((p) => p.type === 'text')\n .map((p) => (p as groq.TextPart).text)\n .join('');\n }\n\n protected convertChoices(candidates: groq.Choice[]): types.chat.Choice[] {\n const choices: types.chat.Choice[] = [];\n try {\n candidates.map(({ index, delta, message, finish_reason }: groq.Choice) => {\n const parts: types.chat.Part[] = [];\n let { content, tool_calls } = message || delta;\n if (delta) {\n content = delta.content;\n tool_calls = delta.tool_calls;\n }\n if (content) {\n parts.push({ type: 'text', text: content });\n }\n if (tool_calls) {\n tool_calls.map((call: any) => {\n const { name, arguments: args } = call.function;\n parts.push({ type: 'function_call', function_call: { name, args }, id: call.id });\n });\n }\n\n choices.push({ index, role: 'assistant', parts, finish_reason });\n });\n } catch (err) {\n console.warn(err);\n }\n return choices;\n }\n}\n","import { OpenAICompletionsAPI, OpenAIAssistantsAPI, GoogleClaudeAPI } from '@/provider';\nimport { MoonshotKimiAPI, QcloudHunyuanAPI, DeepSeekAPI } from '@/provider';\nimport { GoogleVertexAPI, GoogleGeminiAPI } from '@/provider';\nimport { AnthropicClaudeAPI, AnthropicBedrockAPI } from '@/provider';\nimport { AliyunQwenAPI, AliyunWanxAPI } from '@/provider';\nimport { ChatBaseAPI } from '@/provider/base';\nimport { GroqCompletionsAPI } from '@/provider/groq';\nimport * as types from '@/types';\n\nexport class ChatAPI {\n private provider: ChatBaseAPI | null = null;\n\n constructor(provider: string, opts: types.chat.ChatOptions) {\n switch (provider) {\n case types.Provider.GOOGLE_VERTEX:\n this.provider = new GoogleVertexAPI(opts);\n break;\n case types.Provider.GOOGLE_GEMINI:\n this.provider = new GoogleGeminiAPI(opts);\n break;\n case types.Provider.GOOGLE_CLAUDE:\n this.provider = new GoogleClaudeAPI(opts);\n break;\n case types.Provider.OPENAI_COMPLETIONS:\n this.provider = new OpenAICompletionsAPI(opts);\n break;\n case types.Provider.OPENAI_ASSISTANTS:\n this.provider = new OpenAIAssistantsAPI(opts);\n break;\n case types.Provider.ALIYUN_QWEN:\n this.provider = new AliyunQwenAPI(opts);\n break;\n case types.Provider.ALIYUN_WANX:\n this.provider = new AliyunWanxAPI(opts);\n break;\n case types.Provider.ANTHROPIC_CLAUDE:\n this.provider = new AnthropicClaudeAPI(opts);\n break;\n case types.Provider.ANTHROPIC_BEDROCK:\n this.provider = new AnthropicBedrockAPI(opts);\n break;\n case types.Provider.QCLOUD_HUNYUAN:\n this.provider = new QcloudHunyuanAPI(opts);\n break;\n case types.Provider.MOONSHOT_KIMI:\n this.provider = new MoonshotKimiAPI(opts);\n break;\n case types.Provider.DEEPSEEK:\n this.provider = new DeepSeekAPI(opts);\n break;\n case types.Provider.GROQ:\n this.provider = new GroqCompletionsAPI(opts);\n break;\n default:\n throw new Error(`Unsupported supplier: ${provider}`);\n }\n }\n\n public async sendMessage(opts: types.chat.SendOptions | types.image.SendOptions) {\n if (!this.provider) {\n throw new Error('Provider is not initialized');\n }\n return await this.provider.sendMessage(opts);\n }\n}\n","import { AliyunWanxAPI } from '@/provider';\nimport { ChatBaseAPI } from '@/provider/base';\n\nimport * as types from '@/types';\n\nexport class ImageAPI {\n private provider: ChatBaseAPI | null = null;\n\n constructor(provider: string, opts: types.chat.ChatOptions) {\n switch (provider) {\n case types.Provider.ALIYUN_WANX:\n this.provider = new AliyunWanxAPI(opts);\n break;\n default:\n throw new Error(`Unsupported supplier: ${provider}`);\n }\n }\n\n public async sendMessage(opts: types.image.SendOptions) {\n if (!this.provider) {\n throw new Error('Provider is not initialized');\n }\n return await this.provider.sendMessage(opts);\n }\n\n public async getTaskResult(task_id: string) {\n if (!this.provider) {\n throw new Error('Provider is not initialized');\n }\n return await this.provider.getTaskResult(task_id);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAO,IAAK,WAAL,kBAAKA,cAAL;AACL,EAAAA,UAAA,mBAAgB;AAChB,EAAAA,UAAA,mBAAgB;AAChB,EAAAA,UAAA,mBAAgB;AAChB,EAAAA,UAAA,wBAAqB;AACrB,EAAAA,UAAA,uBAAoB;AACpB,EAAAA,UAAA,sBAAmB;AACnB,EAAAA,UAAA,uBAAoB;AACpB,EAAAA,UAAA,iBAAc;AACd,EAAAA,UAAA,iBAAc;AACd,EAAAA,UAAA,oBAAiB;AACjB,EAAAA,UAAA,mBAAgB;AAChB,EAAAA,UAAA,cAAW;AACX,EAAAA,UAAA,UAAO;AAbG,SAAAA;AAAA,GAAA;;;ACAZ,IAAAC,qBAAqB;AACrB,kBAA6B;AAC7B,IAAAC,4BAAgC;AAChC,gCAAsE;;;ACA/D,IAAU;AAAA,CAAV,CAAUC,UAAV;AAAA,EACE,MAAM,kBAAkB,MAAM;AAAA,IAGnC,YAAY,SAAiB,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AAW,IAAI,cAAc,IAAI;AACtC;AAAA,MACF;AACE,cAAM,IAAI,MAAM,yBAAyB,QAAQ,EAAE;AAAA,IACvD;AAAA,EACF;AAAA,EAEA,MAAa,YAAY,MAA+B;AACtD,QAAI,CAAC,KAAK,UAAU;AAClB,YAAM,IAAI,MAAM,6BAA6B;AAAA,IAC/C;AACA,WAAO,MAAM,KAAK,SAAS,YAAY,IAAI;AAAA,EAC7C;AAAA,EAEA,MAAa,cAAc,SAAiB;AAC1C,QAAI,CAAC,KAAK,UAAU;AAClB,YAAM,IAAI,MAAM,6BAA6B;AAAA,IAC/C;AACA,WAAO,MAAM,KAAK,SAAS,cAAc,OAAO;AAAA,EAClD;AACF;","names":["Provider","import_node_fetch","import_https_proxy_agent","chat","fetch","fetchSSE","uuidv4","import_node_fetch","import_uuid","import_https_proxy_agent","import_eventsource_parser","import_node_fetch","import_uuid","import_https_proxy_agent","import_eventsource_parser","fetchSSE","res","uuidv4","fetchSSE","res","uuidv4","import_node_fetch","import_google_auth_library","import_https_proxy_agent","import_eventsource_parser","fetchSSE","res","import_node_fetch","import_https_proxy_agent","import_eventsource_parser","fetchSSE","res","import_node_fetch","import_https_proxy_agent","import_eventsource_parser","fetchSSE","import_node_fetch","import_uuid","import_https_proxy_agent","import_eventsource_parser","fetchSSE","res","uuidv4","item","import_node_fetch","import_https_proxy_agent","fetchSSE","import_node_fetch","import_uuid","import_https_proxy_agent","import_eventsource_parser","fetchSSE","uuidv4","import_uuid","uuidv4","choices","import_node_fetch","import_uuid","import_https_proxy_agent","import_eventsource_parser","fetchSSE","uuidv4","import_node_fetch","import_uuid","import_https_proxy_agent","import_eventsource_parser","fetchSSE","uuidv4"]} \ No newline at end of file +{"version":3,"sources":["../src/index.ts","../src/types/provider.ts","../src/provider/openai/completions.ts","../src/types/chat.ts","../src/provider/base.ts","../src/provider/openai/assistants.ts","../src/provider/google/vertex.ts","../src/provider/google/gemini.ts","../src/provider/google/claude.ts","../src/provider/anthropic/claude.ts","../src/provider/anthropic/bedrock.ts","../src/provider/anthropic/auth.ts","../src/provider/aliyun/qwen.ts","../src/provider/aliyun/wanx.ts","../src/provider/moonshot/kimi.ts","../src/provider/qcloud/hunyuan.ts","../src/provider/deepseek/deepseek.ts","../src/provider/groq/completions.ts","../src/api/chat.ts","../src/api/image.ts"],"sourcesContent":["export * from './api';\nexport * from './types';\n","export enum Provider {\n GOOGLE_GEMINI = 'google-gemini',\n GOOGLE_VERTEX = 'google-vertex',\n GOOGLE_CLAUDE = 'google-claude',\n OPENAI_COMPLETIONS = 'openai-completion',\n OPENAI_ASSISTANTS = 'openai-assistant',\n ANTHROPIC_CLAUDE = 'anthropic-claude',\n ANTHROPIC_BEDROCK = 'anthropic-bedrock',\n ALIYUN_QWEN = 'aliyun-qwen',\n ALIYUN_WANX = 'aliyun-wanx',\n QCLOUD_HUNYUAN = 'qcloud-hunyuan',\n MOONSHOT_KIMI = 'moonshot-kimi',\n DEEPSEEK = 'deepseek',\n GROQ = 'groq',\n}\n","import fetchSSE from 'node-fetch';\nimport { v4 as uuidv4 } from 'uuid';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { ChatBaseAPI } from '../base';\nimport { openai } from './types';\n\nexport class OpenAICompletionsAPI extends ChatBaseAPI {\n protected provider: string = 'openai';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://api.openai.com/v1' }, opts);\n super(options);\n }\n\n public models(): string[] {\n return [\n 'gpt-3.5-turbo',\n 'gpt-3.5-turbo-0125',\n 'gpt-3.5-turbo-16k',\n 'gpt-3.5-turbo-instruct',\n 'gpt-4',\n 'gpt-4-0125-preview',\n 'gpt-4-turbo-preview',\n 'gpt-4-32k',\n ];\n }\n\n async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n\n return new Promise(async (resolove, reject) => {\n const url = `${this.baseURL}/chat/completions`;\n const params: openai.Request = await this.convertParams(options);\n // console.log(`[fetch]params`, JSON.stringify(params, null, 2));\n const res = await fetchSSE(url, {\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${this.apiKey}` },\n body: JSON.stringify(params),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.error?.message || 'request error', res.status));\n }\n\n // not stream\n if (params.stream === false) {\n const result = await res.json();\n const choices = this.convertChoices(result.choices);\n const usage = result?.usage;\n resolove({ id: uuidv4(), model: opts.model, choices, usage });\n } else {\n // streaming\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n const choicesList: types.chat.Choice[] = [];\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n if (event.type === 'event') {\n if (event.data !== '[DONE]') {\n try {\n const result = JSON.parse(event.data);\n const choices = this.convertChoices(result.choices);\n onProgress?.(choices);\n choicesList.push(...choices);\n } catch (e) {\n // ignore\n }\n }\n }\n });\n body.on('readable', async () => {\n let chunk: string | Buffer;\n while ((chunk = body.read())) {\n parser.feed(chunk.toString());\n }\n });\n\n body.on('end', async () => {\n const choices: types.chat.Choice[] = this.combineChoices(choicesList);\n const usage = this.caclulateUsage(opts.messages, choices);\n resolove({ id: uuidv4(), model: opts.model, choices, usage });\n });\n }\n });\n }\n\n /**\n * 转换为 Gemini 要求的请求参数\n * https://platform.openai.com/docs/api-reference/chat/create\n * @returns\n */\n private async convertParams(opts: types.chat.SendOptions): Promise {\n const params: openai.Request = {\n model: opts.model || 'gpt-3.5-turbo-0125',\n messages: await this.corvertContents(opts),\n temperature: opts?.temperature || 0.9,\n top_p: opts?.top_p || 1,\n // frequency_penalty: 0,\n // presence_penalty: 0,\n max_tokens: opts?.max_tokens || 1000,\n n: opts.n || 1,\n stop: opts?.stop_sequences || undefined,\n stream: true,\n };\n // tools\n if (opts.tools && opts.tools.length > 0) {\n Object.assign(params, { tools: opts.tools, stream: false });\n }\n return params;\n }\n\n private async corvertContents(opts: types.chat.SendOptions): Promise {\n return Promise.all(\n opts.messages.map(async (item) => {\n const parts: openai.Part[] = [];\n const tool_calls: openai.ToolCallPart[] = [];\n await Promise.all(\n item.parts.map(async (part: types.chat.Part) => {\n // text\n if (part.type === 'text') {\n parts.push({ type: 'text', text: part.text });\n }\n // file: docs\n if (part.type === 'file' && part?.extract) {\n parts.push({ type: 'text', text: part.extract });\n }\n // file, only support image, now\n if (part.type === 'file' && part.mimetype?.startsWith('image')) {\n // TODO: fetch 下载图片并转化buffer为base64\n // parts.push({ type: 'image_url', image_url: (part as types.chat.FilePart).url });\n parts.push({ type: 'image_url', image_url: { url: (part as types.chat.FilePart).url } });\n }\n // tools\n if (part.type === 'function_call' && part.id) {\n const { name, args } = part.function_call;\n tool_calls.push({ id: part.id, type: 'function', function: { name, arguments: args } });\n }\n }),\n );\n if (item.role === 'system') {\n return { role: 'system', content: this.filterTextPartsToString(parts) } as openai.Message;\n }\n if (item.role === 'assistant') {\n return {\n role: 'assistant',\n content: parts,\n tool_calls: tool_calls.length > 0 ? tool_calls : undefined,\n } as openai.Message;\n }\n return { role: 'user', content: parts } as openai.Message;\n }),\n );\n }\n\n private filterTextPartsToString(parts: openai.Part[]): string {\n return parts\n .filter((p) => p.type === 'text')\n .map((p) => (p as openai.TextPart).text)\n .join('');\n }\n\n protected convertChoices(candidates: openai.Choice[]): types.chat.Choice[] {\n const choices: types.chat.Choice[] = [];\n try {\n candidates.map(({ index, delta, message, finish_reason }: openai.Choice) => {\n const parts: types.chat.Part[] = [];\n let { content, tool_calls } = message || delta;\n if (delta) {\n content = delta.content;\n tool_calls = delta.tool_calls;\n }\n if (content) {\n parts.push({ type: 'text', text: content });\n }\n if (tool_calls) {\n tool_calls.map((call: any) => {\n const { name, arguments: args } = call.function;\n parts.push({ type: 'function_call', function_call: { name, args }, id: call.id });\n });\n }\n\n choices.push({ index, role: 'assistant', parts, finish_reason });\n });\n } catch (err) {\n console.warn(err);\n }\n return choices;\n }\n}\n","/**\n * Chat\n */\nexport namespace chat {\n export class ChatError extends Error {\n name: 'ChatError';\n code: number;\n constructor(message: string, code: number) {\n super(message);\n this.code = code;\n }\n }\n\n export type ChatOptions = {\n agent?: string;\n baseURL?: string;\n apiKey: string;\n apiSecret?: string;\n timeout?: number;\n };\n\n /**\n * Request\n */\n export type SendOptions = {\n model: string;\n messages: Message[];\n tools?: Tools[];\n temperature?: number;\n top_p?: number;\n top_k?: number;\n n?: number;\n max_tokens?: number;\n stop_sequences?: string[];\n stream?: boolean;\n onProgress?: (event: any) => void;\n };\n\n /* Message */\n export type Message = { role: string; parts: Part[] };\n\n export type Part = TextPart | FilePart | ToolPart;\n export type TextPart = { type: 'text'; text: string };\n export type FilePart = { type: 'file'; mimetype: string; url: string; id: string; extract?: string };\n export type ToolPart = FunctionCallTool | FunctionTool;\n\n /* Tools */\n export type Tools = FunctionTool;\n export type FunctionCallTool = {\n type: 'function_call';\n function_call: { name: string; args: any };\n id?: string | undefined;\n };\n export type FunctionTool = { type: 'function'; function: Function };\n\n export type Function = {\n name: string;\n description: string;\n parameters: { type: string; properties: any; required: string[] };\n };\n\n /**\n * Response\n */\n export type ChatResponse = {\n id: string;\n model: string;\n choices: Choice[];\n usage: Usage;\n };\n\n export type Choice = {\n index: number;\n role: string;\n parts: Part[];\n finish_reason: 'stop' | 'function_call' | string | null;\n };\n\n export type Usage = { prompt_tokens: number; completion_tokens: number; total_tokens: number };\n}\n","import { get_encoding } from 'tiktoken';\nimport fetch from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport * as types from '@/types';\n\nexport class ChatBaseAPI {\n protected provider: string = '';\n\n protected agent?: string = '';\n protected baseURL: string = '';\n protected apiKey: string = '';\n protected apiSecret?: string = '';\n protected timeout?: number = 10000;\n\n constructor(opts: types.chat.ChatOptions) {\n opts.agent && (this.agent = opts.agent);\n opts.baseURL && (this.baseURL = opts.baseURL);\n opts.apiKey && (this.apiKey = opts.apiKey);\n opts.apiSecret && (this.apiSecret = opts.apiSecret);\n opts.timeout && (this.timeout = opts.timeout);\n }\n\n public models(): string[] {\n throw new Error('Not implemented');\n }\n\n public async sendMessage(opts: types.chat.SendOptions | types.image.SendOptions): Promise {\n throw new Error('Not implemented');\n }\n\n public async getTaskResult(task_id: string): Promise {\n throw new Error('Not implemented');\n }\n\n protected async fetchFile(url: string) {\n const response = await fetch(url, {\n headers: {\n 'user-agent':\n 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',\n },\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n });\n const buffer = await response.buffer();\n const base64 = buffer.toString('base64');\n const mimeType = response.headers.get('content-type') as string;\n return { mimeType, data: base64 };\n }\n\n protected combineChoices(choices: types.chat.Choice[]): types.chat.Choice[] {\n return choices.reduce((acc: types.chat.Choice[], item: types.chat.Choice) => {\n const existingItem = acc.find((i: types.chat.Choice) => i.index === item.index);\n if (existingItem) {\n item.parts.forEach((part: types.chat.Part) => {\n if (part.type === 'text') {\n const existingPart = existingItem.parts.find((p: types.chat.Part) => p.type === 'text');\n if (existingPart) {\n (existingPart as types.chat.TextPart).text += (part as types.chat.TextPart).text;\n } else {\n existingItem.parts.push(part);\n }\n } else if (part.type === 'function_call') {\n const existingPart = existingItem.parts.find((p: types.chat.Part) => p.type === 'function_call');\n if (existingPart) {\n (existingPart as types.chat.FunctionCallTool).function_call.name +=\n (part as types.chat.FunctionCallTool).function_call.name || '';\n (existingPart as types.chat.FunctionCallTool).function_call.args +=\n (part as types.chat.FunctionCallTool).function_call.args || '';\n } else {\n existingItem.parts.push(part);\n }\n } else {\n const existingPart = existingItem.parts.find(\n (p: types.chat.Part) => JSON.stringify(p) === JSON.stringify(part),\n );\n if (!existingPart) {\n existingItem.parts.push(part);\n }\n }\n });\n\n // finish_reason\n existingItem.finish_reason = item.finish_reason;\n } else {\n acc.push(item);\n }\n return acc;\n }, []);\n }\n\n protected caclulateUsage(messages: types.chat.Message[], choices: types.chat.Choice[]): types.chat.Usage {\n const parts: types.chat.Part[] = messages.flatMap((item) => item.parts);\n const prompt_tokens = parts\n .filter((p) => p.type === 'text' || (p.type === 'file' && p.extract))\n .reduce((acc: number, item) => {\n return acc + this.getTokenCount((item as types.chat.TextPart)?.text || (item as types.chat.FilePart)?.extract);\n }, 0);\n const completion_tokens = choices.reduce((acc: number, item: types.chat.Choice) => {\n return acc + this.getTokenCount(item.parts.map((part) => (part as types.chat.TextPart).text).join(''));\n }, 0);\n return { prompt_tokens, completion_tokens, total_tokens: prompt_tokens + completion_tokens };\n }\n\n protected getTokenCount(text: string) {\n return get_encoding('cl100k_base').encode(text).length;\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { ChatBaseAPI } from '../base';\n\nexport class OpenAIAssistantsAPI extends ChatBaseAPI {\n protected provider: string = 'openai';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://api.openai.com/v1' }, opts);\n super(options);\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { v4 as uuidv4 } from 'uuid';\nimport { GoogleAuth } from 'google-auth-library';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { GoogleGeminiAPI } from './gemini';\nimport { gemini } from './types';\n\nexport class GoogleVertexAPI extends GoogleGeminiAPI {\n protected provider: string = 'google';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign(\n {\n baseURL: 'https://us-central1-aiplatform.googleapis.com/v1/projects/bodhi-415003/locations/us-central1',\n },\n opts,\n );\n super(options);\n }\n\n public models(): string[] {\n return ['gemini-1.0-pro', 'gemini-1.5-pro-preview-0409'];\n }\n\n /**\n * 根据服务账号获取 access token\n */\n private async getToken(): Promise {\n const auth: GoogleAuth = new GoogleAuth({\n credentials: { client_email: this.apiKey, private_key: this.apiSecret },\n scopes: 'https://www.googleapis.com/auth/cloud-platform',\n });\n return (await auth.getAccessToken()) as string;\n }\n\n /**\n * 发送消息\n * @param opts \n * Reference: https://cloud.google.com/vertex-ai/docs/reference/rest/v1/GenerateContentResponse\n * Reference: https://cloud.google.com/vertex-ai/docs/generative-ai/model-reference/gemini?hl=zh-cn\n * Multi-modal: https://cloud.google.com/vertex-ai/docs/generative-ai/multimodal/send-multimodal-prompts?hl=zh-cn#gemini-send-multimodal-samples-drest\n * Tools: https://cloud.google.com/vertex-ai/docs/generative-ai/multimodal/function-calling?hl=zh-cn\n * @returns\n */\n public async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n\n return new Promise(async (resolove, reject) => {\n const token = await this.getToken();\n const model = this.detechModel(opts);\n const url = `${this.baseURL}/publishers/google/models/${model}:streamGenerateContent?alt=sse`;\n const params: gemini.Request = await this.convertParams(options);\n // console.log(`[fetch]params`, model, url, opts.messages);\n\n const res = await fetchSSE(url, {\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },\n body: JSON.stringify(params),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.error?.message || 'request error', res.status));\n }\n\n // only get content from node-fetch\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n // streaming\n const choicesList: types.chat.Choice[] = [];\n const usage: types.chat.Usage = { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n if (event.type === 'event') {\n const res = JSON.parse(event.data);\n if (!res.candidates) {\n console.log(`[vertex]debug`, res);\n }\n const choices = this.convertChoices(res.candidates || []);\n if (res.usageMetadata) {\n Object.assign(usage, {\n prompt_tokens: res.usageMetadata.promptTokenCount,\n completion_tokens: res.usageMetadata.candidatesTokenCount,\n total_tokens: res.usageMetadata.totalTokenCount,\n });\n }\n onProgress?.(choices);\n choicesList.push(...choices);\n }\n });\n body.on('readable', async () => {\n let chunk: string | Buffer;\n while ((chunk = body.read())) {\n parser.feed(chunk.toString());\n }\n });\n\n // finished\n body.on('end', () => {\n const choices: types.chat.Choice[] = this.combineChoices(choicesList);\n // TODO: Google AI Gemini not found usageMetadata, but vertex founded.\n resolove({ id: uuidv4(), model: opts.model, choices, usage });\n });\n });\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { v4 as uuidv4 } from 'uuid';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { gemini } from './types';\nimport { ChatBaseAPI } from '../base';\n\nexport class GoogleGeminiAPI extends ChatBaseAPI {\n protected provider: string = 'google';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://generativelanguage.googleapis.com/v1beta' }, opts);\n super(options);\n }\n\n public models(): string[] {\n return ['gemini-pro', 'gemini-pro-vision', 'gemini-1.5-pro-latest'];\n }\n\n /**\n *\n * https://ai.google.dev/docs/gemini_api_overview?hl=zh-cn#curl_3\n * @param opts\n * @returns\n */\n public async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n return new Promise(async (resolove, reject) => {\n const params: gemini.Request = await this.convertParams(options);\n const model = this.detechModel(opts);\n const url = `${this.baseURL}/models/${model}:streamGenerateContent?alt=sse`;\n // console.log(`[fetch]params`, url, JSON.stringify(params, null, 2));\n\n const res = await fetchSSE(url, {\n headers: { 'Content-Type': 'application/json', 'x-goog-api-key': this.apiKey },\n body: JSON.stringify(params),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n // console.log(`[fetch]result`, res);\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.error?.message || 'request error', res.status));\n }\n\n // only get content from node-fetch\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n // streaming\n const choicesList: types.chat.Choice[] = [];\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n if (event.type === 'event') {\n const res = JSON.parse(event.data);\n // console.log(`->`, JSON.stringify(res));\n const choices = this.convertChoices(res.candidates);\n onProgress?.(choices);\n\n choicesList.push(...choices);\n }\n });\n body.on('readable', async () => {\n let chunk: string | Buffer;\n while ((chunk = body.read())) {\n parser.feed(chunk.toString());\n }\n });\n\n body.on('end', () => {\n const choices: types.chat.Choice[] = this.combineChoices(choicesList);\n // TODO: Google AI Gemini not found usageMetadata, but vertex founded.\n const usage = { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };\n resolove({ id: uuidv4(), model: opts.model, choices, usage });\n });\n });\n }\n\n protected detechModel(opts: types.chat.SendOptions): string {\n const hasMedia = opts.messages.some((item) =>\n item.parts.some(\n (part) =>\n part.type === 'file' &&\n (part.mimetype.startsWith('image') || part.mimetype.startsWith('video') || part.mimetype.startsWith('audio')),\n ),\n );\n return hasMedia && opts.model === 'gemini-1.0-pro' ? 'gemini-1.0-pro-vision' : opts.model;\n }\n\n /**\n * 转换为 Gemini 要求的请求参数\n * https://cloud.google.com/vertex-ai/docs/reference/rest/v1/GenerateContentResponse\n * @returns\n */\n protected async convertParams(opts: types.chat.SendOptions): Promise {\n return {\n contents: await this.corvertContents(opts),\n // systemInstruction: await this.corvertSystemContent(opts),\n tools: this.corvertTools(opts),\n safety_settings: [\n // { category: 'BLOCK_NONE', threshold: 'HARM_CATEGORY_UNSPECIFIED' },\n ],\n generationConfig: {\n temperature: opts.temperature || 0.9, // gemini-pro:0.9, gemini-pro-vision:0.4\n topP: opts.top_p || 1, // gemini-pro:none, gemini-pro-vision:32\n // topK: Math.round((opts.top_k || 0.025) * 40) || 32,\n candidateCount: opts.n || 1,\n maxOutputTokens: opts.max_tokens || 2048, // gemini-pro:2048, gemini-pro-vision:8192\n stopSequences: opts.stop_sequences || undefined,\n },\n };\n }\n\n protected async corvertContents(opts: types.chat.SendOptions): Promise {\n // filter system role\n const rows = await Promise.all(\n opts.messages\n .filter((item) => ['user', 'assistant'].includes(item.role))\n .map(async (item) => {\n const parts: gemini.Part[] = [];\n await Promise.all(\n item.parts.map(async (part: types.chat.Part) => {\n // text\n if (part.type === 'text') {\n parts.push({ text: part.text });\n }\n // file\n if (part.type === 'file') {\n if (part?.extract) {\n parts.push({ text: part.extract });\n } else {\n const { mimetype: mimeType, url } = part as types.chat.FilePart;\n if (url.startsWith('gs://')) {\n parts.push({ fileData: { mimeType, fileUri: url } });\n } else {\n try {\n parts.push({ inlineData: await this.fetchFile(url) });\n } catch (err) {}\n }\n }\n }\n // tools\n if (part.type === 'function_call') {\n const { name, args } = part.function_call;\n parts.push({ functionCall: { name, args } });\n }\n }),\n );\n item.role = item.role === 'assistant' ? 'model' : item.role;\n return { role: item.role, parts } as gemini.Content;\n }),\n );\n\n // Compatible with system role\n // insert system text part to rows's first user parts\n const system = opts.messages.filter((item) => item.role === 'system');\n if (system.length > 0) {\n const textParts = system[0].parts.filter((part) => 'text' in part) as gemini.TextPart[];\n rows[0].parts.unshift(...textParts.map((part) => ({ text: `[instructions]\\n${part.text}\\n\\n[user prompt]\\n` })));\n }\n\n return rows;\n }\n\n protected corvertTools(opts: types.chat.SendOptions): gemini.Tools[] {\n const tools: gemini.Tools[] = [];\n if (opts.tools) {\n opts.tools.map((item) => {\n if (item.type === 'function') {\n tools.push({ functionDeclarations: [item.function] });\n }\n });\n }\n return tools;\n }\n\n protected convertChoices(candidates: gemini.Candidate[]): types.chat.Choice[] {\n const choices: types.chat.Choice[] = [];\n\n try {\n candidates.map(({ index, content, finishReason }: gemini.Candidate) => {\n const parts: types.chat.Part[] = [];\n content.parts.map((part: any) => {\n if ('text' in part) {\n parts.push({ type: 'text', text: part.text });\n }\n if ('functionCall' in part) {\n parts.push({ type: 'function_call', function_call: part.functionCall });\n }\n });\n choices.push({ index, role: 'assistant', parts, finish_reason: 'stop' });\n });\n } catch (err) {\n console.log(`->candidates1`, JSON.stringify(candidates, null, 2));\n console.warn(err);\n console.log(`->candidates2`);\n }\n return choices;\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { GoogleAuth } from 'google-auth-library';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { claude } from '../anthropic/types';\nimport { ChatBaseAPI } from '../base';\n\nexport class GoogleClaudeAPI extends ChatBaseAPI {\n protected provider: string = 'google';\n\n constructor(opts: types.chat.ChatOptions) {\n // available models: claude-instant-1p2(100K tokens), claude-2p0(200K tokens)\n // available regions: us-central1(60QPM), asia-southeast1(60QPM)\n const options = Object.assign(\n { baseURL: 'https://us-central1-aiplatform.googleapis.com/v1/projects/bodhi-415003/locations/us-central1' },\n opts,\n );\n super(options);\n }\n\n /**\n * 根据服务账号获取 access token\n */\n private async getToken(): Promise {\n const auth: GoogleAuth = new GoogleAuth({\n credentials: { client_email: this.apiKey, private_key: this.apiSecret },\n scopes: 'https://www.googleapis.com/auth/cloud-platform',\n });\n return (await auth.getAccessToken()) as string;\n }\n\n public models(): string[] {\n return ['claude-3-sonnet@20240229', 'claude-3-haiku@20240307', 'gemini-1.5-flash-preview-0514'];\n }\n\n /**\n * Send message\n * https://docs.anthropic.com/claude/reference/messages_post\n * @param opts\n * @returns\n */\n public async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n return new Promise(async (resolove, reject) => {\n const token = await this.getToken();\n const url = `${this.baseURL}/publishers/anthropic/models/${opts.model}:streamRawPredict?alt=sse`;\n const params: claude.Request = await this.convertParams(options);\n // console.log(`->url`, url, JSON.stringify(params));\n const res = await fetchSSE(url, {\n headers: { 'content-type': 'application/json', Authorization: `Bearer ${token}` },\n body: JSON.stringify(params),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.error?.message || 'request error', res.status));\n }\n\n // only get content from node-fetch\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n let response: types.chat.ChatResponse;\n const choicesList: types.chat.Choice[] = [];\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n if (event.type === 'event') {\n const res: claude.Response = JSON.parse(event.data);\n response = this.convertResult(response, res);\n const choices = this.convertChoices(res);\n if (choices.length > 0) {\n onProgress?.(choices);\n choicesList.push(...choices);\n }\n }\n });\n body.on('readable', async () => {\n let chunk: string | Buffer;\n while ((chunk = body.read())) {\n parser.feed(chunk.toString());\n }\n });\n\n body.on('end', () => {\n response.choices = this.combineChoices(choicesList);\n resolove(response);\n });\n });\n }\n\n /**\n * https://docs.anthropic.com/claude/reference/messages-streaming\n * @returns\n */\n private async convertParams(opts: types.chat.SendOptions): Promise {\n return {\n messages: await this.corvertContents(opts),\n system: this.corvertSystem(opts),\n temperature: opts.temperature || 0.8,\n top_p: opts.top_p || 1,\n // top_k: opts.top_k || 1,\n max_tokens: opts.max_tokens || 1024,\n stop_sequences: opts.stop_sequences || [],\n stream: true,\n anthropic_version: 'vertex-2023-10-16',\n };\n }\n\n protected corvertSystem(opts: types.chat.SendOptions): string {\n return opts.messages\n .filter((item) => item.role === 'system')\n .map((item) =>\n item.parts\n .filter((p: types.chat.Part) => p.type === 'text')\n .map((p) => (p as types.chat.TextPart).text)\n .join(''),\n )\n .join('\\n');\n }\n\n protected async corvertContents(opts: types.chat.SendOptions): Promise {\n return Promise.all(\n opts.messages\n .filter((item) => item.role !== 'system')\n .map(async (item) => {\n const parts: claude.Part[] = [];\n await Promise.all(\n item.parts.map(async (part: types.chat.Part) => {\n // text\n if (part.type === 'text') {\n parts.push({ type: 'text', text: part.text });\n }\n // file, only support image, now\n if (part.type === 'file' && part?.extract) {\n parts.push({ type: 'text', text: part.extract });\n }\n if (part.type === 'file' && part.mimetype?.startsWith('image')) {\n try {\n const { mimeType: media_type, data } = await this.fetchFile((part as types.chat.FilePart).url);\n parts.push({ type: 'image', source: { type: 'base64', media_type, data } });\n } catch (err) {\n // console.warn(``);\n }\n }\n }),\n );\n return { role: item.role, content: parts } as claude.Content;\n }),\n );\n }\n\n private convertResult(response, res: claude.Response): types.chat.ChatResponse {\n try {\n if (res.type === 'message_start') {\n const { message: m } = res;\n const { input_tokens: prompt_tokens, output_tokens: completion_tokens } = m.usage;\n response = {\n id: m.id,\n model: m.model,\n choices: [],\n usage: { prompt_tokens, completion_tokens, total_tokens: prompt_tokens + completion_tokens },\n };\n }\n\n if (res.type === 'message_delta') {\n const { output_tokens } = res.usage;\n response.usage.completion_tokens = output_tokens;\n response.usage.total_tokens = response.usage.prompt_tokens + output_tokens;\n }\n } catch (err) {\n console.warn(err);\n }\n return response;\n }\n\n private convertChoices(res: claude.Response): types.chat.Choice[] {\n const choices: types.chat.Choice[] = [];\n try {\n if (res.type === 'content_block_start') {\n const { index, content_block: c } = res;\n choices.push({ index, role: 'assistant', parts: [{ type: 'text', text: c.text }], finish_reason: null });\n }\n\n if (res.type === 'content_block_delta') {\n const { index, delta: d } = res;\n choices.push({ index, role: 'assistant', parts: [{ type: 'text', text: d.text }], finish_reason: null });\n }\n\n if (res.type === 'content_block_stop') {\n const { index } = res;\n choices.push({ index, role: 'assistant', parts: [], finish_reason: 'stop' });\n }\n } catch (err) {\n console.warn(err);\n }\n return choices;\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { claude } from './types';\nimport { ChatBaseAPI } from '../base';\n\nexport class AnthropicClaudeAPI extends ChatBaseAPI {\n protected provider: string = 'anthropic';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://api.anthropic.com' }, opts);\n super(options);\n }\n\n public models(): string[] {\n return [\n 'claude-3-opus-20240229',\n 'claude-3-sonnet-20240229',\n 'claude-3-haiku-20240307',\n 'claude-2.1',\n 'claude-2.0',\n 'claude-instant-1.2',\n ];\n }\n\n /**\n * Send message\n * https://docs.anthropic.com/claude/reference/messages_post\n * @param opts\n * @returns\n */\n public async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n return new Promise(async (resolove, reject) => {\n const url = `${this.baseURL}/v1/messages`;\n const params: claude.Request = await this.convertParams(options);\n const res = await fetchSSE(url, {\n headers: {\n 'content-type': 'application/json',\n 'anthropic-version': '2023-06-01',\n 'x-api-key': this.apiKey,\n },\n body: JSON.stringify(params),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.error?.message || 'request error', res.status));\n }\n\n // only get content from node-fetch\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n let response: types.chat.ChatResponse;\n const choicesList: types.chat.Choice[] = [];\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n if (event.type === 'event') {\n const res: claude.Response = JSON.parse(event.data);\n response = this.convertResult(response, res);\n const choices = this.convertChoices(res);\n if (choices.length > 0) {\n onProgress?.(choices);\n choicesList.push(...choices);\n }\n }\n });\n body.on('readable', async () => {\n let chunk: string | Buffer;\n while ((chunk = body.read())) {\n parser.feed(chunk.toString());\n }\n });\n\n body.on('end', () => {\n response.choices = this.combineChoices(choicesList);\n resolove(response);\n });\n });\n }\n\n /**\n * https://docs.anthropic.com/claude/reference/messages-streaming\n * @returns\n */\n private async convertParams(opts: types.chat.SendOptions): Promise {\n return {\n model: opts.model || 'claude-3-haiku-20240307',\n messages: await this.corvertContents(opts),\n system: this.corvertSystem(opts),\n temperature: opts.temperature || 0.8,\n top_p: opts.top_p || 1,\n // top_k: opts.top_k || 1,\n max_tokens: opts.max_tokens || 1024,\n // metadata:\n stop_sequences: opts.stop_sequences || [],\n stream: true,\n };\n }\n\n protected corvertSystem(opts: types.chat.SendOptions): string {\n return opts.messages\n .filter((item) => item.role === 'system')\n .map((item) =>\n item.parts\n .filter((p: types.chat.Part) => p.type === 'text')\n .map((p) => (p as types.chat.TextPart).text)\n .join(''),\n )\n .join('\\n');\n }\n\n protected async corvertContents(opts: types.chat.SendOptions): Promise {\n return Promise.all(\n opts.messages\n .filter((item) => item.role !== 'system')\n .map(async (item) => {\n const parts: claude.Part[] = [];\n await Promise.all(\n item.parts.map(async (part: types.chat.Part) => {\n // text\n if (part.type === 'text') {\n parts.push({ type: 'text', text: part.text });\n }\n // file, only support image, now\n if (part.type === 'file' && part?.extract) {\n parts.push({ type: 'text', text: part.extract });\n }\n if (part.type === 'file' && part.mimetype?.startsWith('image')) {\n try {\n const { mimeType: media_type, data } = await this.fetchFile((part as types.chat.FilePart).url);\n parts.push({ type: 'image', source: { type: 'base64', media_type, data } });\n } catch (err) {\n // console.warn(``);\n }\n }\n }),\n );\n return { role: item.role, content: parts } as claude.Content;\n }),\n );\n }\n\n private convertResult(response, res: claude.Response): types.chat.ChatResponse {\n try {\n if (res.type === 'message_start') {\n const { message: m } = res;\n const { input_tokens: prompt_tokens, output_tokens: completion_tokens } = m.usage;\n response = {\n id: m.id,\n model: m.model,\n choices: [],\n usage: { prompt_tokens, completion_tokens, total_tokens: prompt_tokens + completion_tokens },\n };\n }\n\n if (res.type === 'message_delta') {\n const { output_tokens } = res.usage;\n response.usage.completion_tokens = output_tokens;\n response.usage.total_tokens = response.usage.prompt_tokens + output_tokens;\n }\n } catch (err) {\n console.warn(err);\n }\n return response;\n }\n\n private convertChoices(res: claude.Response): types.chat.Choice[] {\n const choices: types.chat.Choice[] = [];\n try {\n if (res.type === 'content_block_start') {\n const { index, content_block: c } = res;\n choices.push({ index, role: 'assistant', parts: [{ type: 'text', text: c.text }], finish_reason: null });\n }\n\n if (res.type === 'content_block_delta') {\n const { index, delta: d } = res;\n choices.push({ index, role: 'assistant', parts: [{ type: 'text', text: d.text }], finish_reason: null });\n }\n\n if (res.type === 'content_block_stop') {\n const { index } = res;\n choices.push({ index, role: 'assistant', parts: [], finish_reason: 'stop' });\n }\n } catch (err) {\n console.warn(err);\n }\n return choices;\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { ChatBaseAPI } from '../base';\nimport { requestWithAuth, toUtf8 } from './auth';\n\nexport class AnthropicBedrockAPI extends ChatBaseAPI {\n protected provider: string = 'anthropic';\n\n constructor(opts: types.chat.ChatOptions) {\n super(Object.assign({ baseURL: `https://bedrock-runtime.ap-northeast-1.amazonaws.com` }, opts));\n }\n\n public models(): string[] {\n return ['anthropic.claude-v2:1', 'anthropic.claude-v2', 'anthropic.claude-v1', 'anthropic.claude-instant-v1'];\n }\n\n /**\n * Send message\n * https://docs.anthropic.com/claude/reference/messages_post\n * @param opts\n * @returns\n */\n public async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n\n return new Promise(async (resolove, reject) => {\n const url = new URL(`${this.baseURL}/model/${opts.model}/invoke-with-response-stream`);\n // 预请求并签名\n const req = await requestWithAuth(\n { region: 'ap-northeast-1', service: 'bedrock', accessKeyId: this.apiKey, secretAccessKey: this.apiSecret },\n {\n method: 'POST',\n protocol: url.protocol,\n path: url.pathname,\n headers: {\n host: url.hostname,\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n 'User-Agent': 'AnthropicBedrock/JS 0.6.1',\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': '0.6.1',\n 'X-Stainless-OS': 'MacOS',\n 'X-Stainless-Arch': 'arm64',\n 'X-Stainless-Runtime': 'node',\n 'X-Stainless-Runtime-Version': 'v19.4.0',\n },\n body: JSON.stringify(this.convertParams(options), null, 2),\n },\n );\n // 请求\n const res = await fetchSSE(url, {\n headers: req.headers,\n body: req.body,\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: req.method,\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.message || 'request error', res.status));\n }\n\n // only get content from node-fetch\n let response: any;\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n // if (event.type === 'event') {\n // response = JSON.parse(event.data);\n // onProgress?.(response);\n // }\n console.log(`[bedrock]`, event);\n });\n\n body.on('readable', async () => {\n // 解析SSE 并进行utf8解码\n // let chunk: string | Buffer;\n // while ((chunk = body.read())) {\n // console.log(`[bedrock]`, chunk.toString());\n // // parser.feed(chunk.toString());\n // }\n\n let event;\n while (null !== (event = body.read())) {\n if (Buffer.isBuffer(event)) {\n console.log(`[bedrock]`, event.toString('utf8'));\n }\n }\n });\n\n body.on('end', () => {\n resolove(response);\n });\n });\n }\n\n /**\n * https://docs.anthropic.com/claude/reference/messages-streaming\n * @returns\n */\n private convertParams(opts: types.chat.SendOptions) {\n return {\n prompt: '\\n\\nHuman: Hey Claude! How can I recursively list all files in a directory in Rust?\\n\\nAssistant:',\n temperature: 1,\n // top_k: 250,\n // top_p: 0.999,\n max_tokens_to_sample: 500,\n anthropic_version: 'bedrock-2023-05-31',\n };\n }\n\n // 将 Gemini 的结果转换为你的数据格式\n private convertResult(result: any) {\n return {\n // 根据你的数据格式,从 Gemini 的结果中提取数据\n history: result.contents,\n // 其他数据...\n };\n }\n}\n","import { SignatureV4 } from '@smithy/signature-v4';\nimport { HttpRequest } from '@aws-sdk/protocol-http';\nimport { Sha256 } from '@aws-crypto/sha256-js';\n\nexport const toUtf8 = (input: Uint8Array): string => new TextDecoder('utf-8').decode(input);\n\nexport async function requestWithAuth(options: any, request: any): Promise {\n const { accessKeyId, secretAccessKey, region, service } = options;\n const credentials = { accessKeyId, secretAccessKey };\n // sign request\n const signed = await new SignatureV4({ region, service, sha256: Sha256, credentials }).sign(new HttpRequest(request));\n return signed as HttpRequest;\n}\n","import fetchSSE from 'node-fetch';\nimport { v4 as uuidv4 } from 'uuid';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { ChatBaseAPI } from '../base';\nimport { aliyun } from './types';\n\nexport class AliyunQwenAPI extends ChatBaseAPI {\n protected provider: string = 'google';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://dashscope.aliyuncs.com/api/v1' }, opts);\n super(options);\n }\n\n public models(): string[] {\n return ['qwen-turbo', 'qwen-plus', 'qwen-max'];\n }\n\n /**\n *\n * https://ai.google.dev/docs/gemini_api_overview?hl=zh-cn#curl_3\n * @param opts\n * @returns\n */\n public async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n return new Promise(async (resolove, reject) => {\n // 如果消息存在图片, 则自动切换到 multimodal\n const isMulti =\n opts.model !== 'qwen-turbo' &&\n opts.messages.some((item) => item.parts.some((part) => ['image'].includes(part.type)));\n const model = isMulti ? opts.model.replace('-', '-vl-') : opts.model;\n const url = `${this.baseURL}/services/aigc/${isMulti ? 'multimodal' : 'text'}-generation/generation`;\n const params: aliyun.Request = await this.convertParams(model, options);\n // console.log(`[fetch]params`, JSON.stringify(params, null, 2));\n\n const res = await fetchSSE(url, {\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`,\n 'X-DashScope-SSE': 'enable',\n },\n body: JSON.stringify(params),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.message || 'request error', res.status));\n }\n\n // only get content from node-fetch\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n // streaming\n const choicesList: types.chat.Choice[] = [];\n const usage: types.chat.Usage = { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n if (event.type === 'event') {\n const res = JSON.parse(event.data);\n // console.log(`->`, JSON.stringify(res));\n // success\n if (res?.output) {\n const choices = this.convertChoices(res.output.choices);\n onProgress?.(choices);\n\n if (res.usage) {\n const u = res.usage;\n Object.assign(usage, {\n prompt_tokens: u.input_tokens,\n completion_tokens: u.output_tokens,\n total_tokens: u.total_tokens ? u.total_tokens : u.input_tokens + u.output_tokens,\n });\n }\n choicesList.push(...choices);\n }\n\n // error\n if (res?.code) {\n reject(new types.chat.ChatError(res?.message, 500));\n }\n }\n });\n body.on('readable', async () => {\n let chunk: string | Buffer;\n while ((chunk = body.read())) {\n parser.feed(chunk.toString());\n }\n });\n\n body.on('end', () => {\n const choices: types.chat.Choice[] = this.combineChoices(choicesList);\n resolove({ id: uuidv4(), model: opts.model, choices, usage });\n });\n });\n }\n\n /**\n * Aliyun Qwen API\n * https://help.aliyun.com/zh/dashscope/developer-reference/api-details\n * @returns\n */\n private async convertParams(model, opts: types.chat.SendOptions): Promise {\n const params = {\n model: model || 'qwen-turbo',\n input: {\n messages: await this.corvertContents(opts),\n },\n parameters: {\n temperature: (opts.temperature || 0.85) * 2 - 0.1,\n top_p: opts.top_p || 0.8,\n // top_k: Math.round((opts.top_k || 0.025) * 100) || undefined,\n max_tokens: opts.max_tokens || 1500,\n incremental_output: true,\n enable_search: true,\n },\n };\n // fix different model\n if (model.indexOf('vl') === -1) {\n Object.assign(params.parameters, {\n temperature: opts.temperature || 1,\n max_tokens: opts.max_tokens || 1500,\n enable_search: true,\n stop: opts.stop_sequences || undefined,\n result_format: 'message',\n });\n }\n return params;\n }\n\n private async corvertContents(opts: types.chat.SendOptions): Promise {\n return Promise.all(\n opts.messages.map(async (item) => {\n const parts: aliyun.Part[] = [];\n await Promise.all(\n item.parts.map(async (part: types.chat.Part) => {\n // text\n if (part.type === 'text') {\n parts.push({ text: part.text });\n }\n // file: docs\n if (part.type === 'file' && part?.extract) {\n parts.push({ text: part.extract });\n }\n\n // file, only support image, now\n if (part.type === 'file' && part.mimetype?.startsWith('image')) {\n parts.push({ image: (part as types.chat.FilePart).url });\n }\n }),\n );\n // fix different model\n let content: string | aliyun.Part[] = parts;\n if (!['qwen-vl-plus'].includes(opts.model)) {\n content = parts\n .map((item: any) => {\n return 'text' in item ? item.text : '';\n })\n .join('\\n');\n }\n return { role: item.role, content: parts } as aliyun.Content;\n }),\n );\n }\n\n protected convertChoices(candidates: aliyun.Choice[]): types.chat.Choice[] {\n const choices: types.chat.Choice[] = [];\n try {\n candidates.map(({ message, finish_reason }: aliyun.Choice) => {\n const parts: types.chat.Part[] = [];\n // for text\n if (typeof message.content === 'string') {\n parts.push({ type: 'text', text: message.content });\n }\n // for multimodal\n if (typeof message.content === 'object' && message.content instanceof Array) {\n message.content.map((part: any) => {\n if ('text' in part) {\n parts.push({ type: 'text', text: part.text });\n }\n });\n }\n choices.push({ index: 0, role: 'assistant', parts, finish_reason: 'stop' });\n });\n } catch (err) {\n console.warn(err);\n }\n return choices;\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { ChatBaseAPI } from '../base';\n\nexport class AliyunWanxAPI extends ChatBaseAPI {\n protected provider: string = 'google';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://dashscope.aliyuncs.com/api/v1' }, opts);\n super(options);\n }\n\n public models(): string[] {\n return ['wanx-v1'];\n }\n\n /**\n * https://help.aliyun.com/zh/dashscope/developer-reference/api-details-9\n * @param opts\n * @returns\n */\n public async sendMessage(opts: types.image.SendOptions) {\n return new Promise(async (resolove, reject) => {\n const url = `${this.baseURL}/services/aigc/text2image/image-synthesis`;\n const res = await fetchSSE(url, {\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`,\n 'X-DashScope-Async': 'enable',\n },\n body: JSON.stringify(this.convertParams(opts)),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.message || 'request error', res.status));\n }\n\n try {\n const { output } = await res.json();\n if (output.task_status === 'FAILED') {\n reject(new types.chat.ChatError(output.message, res.status));\n }\n resolove(output);\n } catch (err) {\n reject(new types.chat.ChatError('request error', res.status));\n }\n });\n }\n\n public async getTaskResult(task_id: string) {\n const url = `${this.baseURL}/tasks/${task_id}`;\n return new Promise(async (resolove, reject) => {\n const res = await fetchSSE(url, {\n headers: { Authorization: `Bearer ${this.apiKey}` },\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n });\n\n try {\n const { output } = await res.json();\n if (output.task_status === 'FAILED') {\n reject(new types.chat.ChatError(output.message, res.status));\n }\n\n resolove(output);\n } catch (err) {\n reject(new types.chat.ChatError('request error', res.status));\n }\n });\n }\n\n /**\n * https://help.aliyun.com/zh/dashscope/developer-reference/api-details-9\n * @returns\n */\n private convertParams(opts: types.image.SendOptions) {\n return {\n model: opts.model || 'wanx-v1',\n input: {\n prompt: opts.prompt,\n },\n parameters: {\n style: '',\n size: '1024*1024',\n n: 4,\n seed: 42,\n },\n };\n }\n\n // 将 Gemini 的结果转换为你的数据格式\n private convertResult(result: any) {\n return {\n // 根据你的数据格式,从 Gemini 的结果中提取数据\n history: result.contents,\n // 其他数据...\n };\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { v4 as uuidv4 } from 'uuid';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { ChatBaseAPI } from '../base';\nimport { kimi } from './types';\n\nexport class MoonshotKimiAPI extends ChatBaseAPI {\n protected provider: string = 'moonshot';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://api.moonshot.cn/v1' }, opts);\n super(options);\n }\n\n public models(): string[] {\n return ['moonshot-v1-8k', 'moonshot-v1-32k', 'moonshot-v1-128k'];\n }\n\n async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n\n return new Promise(async (resolove, reject) => {\n const url = `${this.baseURL}/chat/completions`;\n const params: kimi.Request = await this.convertParams(options);\n // console.log(`[fetch]params`, JSON.stringify(params, null, 2));\n\n const res = await fetchSSE(url, {\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${this.apiKey}` },\n body: JSON.stringify(params),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.error?.message || 'request error', res.status));\n return;\n }\n\n // not stream\n let usage = { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };\n if (params.stream === false) {\n const result = await res.json();\n const choices = this.convertChoices(result.choices);\n resolove({ id: uuidv4(), model: opts.model, choices, usage: result.usage });\n } else {\n // streaming\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n const choicesList: types.chat.Choice[] = [];\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n if (event.type === 'event') {\n if (event.data !== '[DONE]') {\n try {\n const result = JSON.parse(event.data);\n const choices = this.convertChoices(result.choices);\n usage = this.convertChoicesUsage(result.choices, usage);\n onProgress?.(choices);\n choicesList.push(...choices);\n } catch (e) {\n // ignore\n }\n }\n }\n });\n body.on('readable', async () => {\n let chunk: string | Buffer;\n while ((chunk = body.read())) {\n parser.feed(chunk.toString());\n }\n });\n\n // console.log(`->`, choicesList);\n body.on('end', async () => {\n const choices: types.chat.Choice[] = this.combineChoices(choicesList);\n resolove({ id: uuidv4(), model: opts.model, choices, usage });\n });\n }\n });\n }\n\n /**\n * 转换为 Gemini 要求的请求参数\n * https://platform.openai.com/docs/api-reference/chat/create\n * @returns\n */\n private async convertParams(opts: types.chat.SendOptions): Promise {\n const params: kimi.Request = {\n model: opts.model || 'moonshot-v1-8k',\n messages: await this.corvertContents(opts),\n temperature: opts?.temperature || 0.9,\n top_p: opts?.top_p || 1.0,\n // frequency_penalty: 0,\n // presence_penalty: 0,\n max_tokens: opts?.max_tokens || 1000,\n n: opts.n || 1,\n stop: opts?.stop_sequences || undefined,\n stream: opts?.stream != undefined ? opts.stream : true,\n };\n // tools\n if (opts.tools && opts.tools.length > 0) {\n Object.assign(params, { tools: opts.tools, stream: false });\n }\n return params;\n }\n\n private async corvertContents(opts: types.chat.SendOptions): Promise {\n return Promise.all(\n opts.messages.map(async (item) => {\n const parts: string[] = [];\n await Promise.all(\n item.parts.map(async (part: types.chat.Part) => {\n // text\n if (part.type === 'text') {\n parts.push(part.text);\n }\n // file, only support image, now\n if (part.type === 'file' && part?.extract) {\n parts.push(part.extract);\n }\n }),\n );\n\n return { role: item.role, content: parts.join('\\n') } as kimi.Message;\n }),\n );\n }\n\n protected convertChoices(candidates: kimi.Choice[]): types.chat.Choice[] {\n const choices: types.chat.Choice[] = [];\n try {\n candidates.map(({ index, delta, message, finish_reason }: kimi.Choice) => {\n const parts: types.chat.Part[] = [];\n let { content } = message || delta;\n if (delta) {\n content = delta.content;\n }\n if (content) {\n parts.push({ type: 'text', text: content });\n }\n\n choices.push({ index, role: 'assistant', parts, finish_reason });\n });\n } catch (err) {\n console.warn(err);\n }\n return choices;\n }\n\n protected convertChoicesUsage(candidates: kimi.Choice[], initial: types.chat.Usage): types.chat.Usage {\n candidates.map(({ usage }: kimi.Choice) => {\n if (usage) {\n initial.prompt_tokens += usage.prompt_tokens;\n initial.completion_tokens += usage.completion_tokens;\n initial.total_tokens += usage.total_tokens;\n }\n });\n return initial;\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { v4 as uuidv4 } from 'uuid';\nimport * as tencentcloud from 'tencentcloud-sdk-nodejs';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { ChatBaseAPI } from '../base';\nimport { hunyuan } from './types';\n\nexport class QcloudHunyuanAPI extends ChatBaseAPI {\n protected provider: string = 'tencent';\n private client: any;\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://hunyuan.tencentcloudapi.com' }, opts);\n super(options);\n\n // init tencentcloud client\n this.client = new tencentcloud.hunyuan.v20230901.Client({\n credential: { secretId: this.apiKey, secretKey: this.apiSecret },\n profile: {\n signMethod: 'TC3-HMAC-SHA256',\n httpProfile: { reqMethod: 'POST', reqTimeout: 30, endpoint: 'hunyuan.tencentcloudapi.com' },\n },\n });\n }\n\n public models(): string[] {\n return ['hunyuan-lite', 'hunyuan-standard', 'hunyuan-pro'];\n }\n\n /**\n * tencent hunyuan\n * https://cloud.tencent.com/document/api/1729/101836\n * @param opts\n * @returns\n */\n public async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n return new Promise(async (resolove, reject) => {\n if (!this.models().includes(opts.model)) {\n reject(new Error(`model ${opts.model} is not supported`));\n }\n\n const params = await this.convertParams(options);\n const response = await this.client.ChatCompletions(params);\n\n // streaming\n let id = uuidv4();\n const choicesList: types.chat.Choice[] = [];\n const usage: types.chat.Usage = { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };\n for await (let message of response) {\n const res = JSON.parse(message.data);\n id = res.Id;\n const choices = this.convertChoices(res.Choices);\n if (res.Usage) {\n Object.assign(usage, {\n prompt_tokens: res.Usage.PromptTokens,\n completion_tokens: res.Usage.CompletionTokens,\n total_tokens: res.Usage.TotalTokens,\n });\n }\n onProgress?.(choices);\n choicesList.push(...choices);\n }\n\n // finished\n const choices: types.chat.Choice[] = this.combineChoices(choicesList);\n resolove({ id, model: opts.model, choices, usage });\n });\n }\n\n /**\n * 转换请求参数\n * @returns\n */\n private async convertParams(opts: types.chat.SendOptions) {\n return {\n Model: opts.model,\n TopP: opts.top_p || 1.0,\n Temperature: opts.temperature || 1.0,\n Messages: await this.corvertContents(opts),\n Stream: true,\n };\n }\n\n private async corvertContents(opts: types.chat.SendOptions): Promise {\n return Promise.all(\n opts.messages.map(async (item) => {\n const parts: string[] = [];\n await Promise.all(\n item.parts.map(async (part: types.chat.Part) => {\n // text\n if (part.type === 'text') {\n parts.push(part.text);\n }\n // file, only support image, now\n if (part.type === 'file' && part?.extract) {\n parts.push(part.extract);\n }\n }),\n );\n return { Role: item.role, Content: parts.join('/n') } as hunyuan.Content;\n }),\n );\n }\n\n protected convertChoices(candidates: hunyuan.Choice[]): types.chat.Choice[] {\n const choices: types.chat.Choice[] = [];\n try {\n candidates.map(({ Delta, FinishReason }: hunyuan.Choice, index) => {\n const parts: types.chat.Part[] = [];\n parts.push({ type: 'text', text: Delta.Content });\n choices.push({ index, role: 'assistant', parts, finish_reason: 'stop' });\n });\n } catch (err) {\n console.warn(err);\n }\n return choices;\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { v4 as uuidv4 } from 'uuid';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { ChatBaseAPI } from '../base';\nimport { deepseek } from './types';\n\nexport class DeepSeekAPI extends ChatBaseAPI {\n protected provider: string = 'moonshot';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://api.deepseek.com' }, opts);\n super(options);\n }\n\n public models(): string[] {\n return ['deepseek-chat'];\n }\n\n async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n\n return new Promise(async (resolove, reject) => {\n const url = `${this.baseURL}/chat/completions`;\n const params: deepseek.Request = await this.convertParams(options);\n // console.log(`[fetch]params`, JSON.stringify(params, null, 2));\n\n const res = await fetchSSE(url, {\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${this.apiKey}` },\n body: JSON.stringify(params),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.error?.message || 'request error', res.status));\n }\n\n // not stream\n if (params.stream === false) {\n const result = await res.json();\n const choices = this.convertChoices(result.choices);\n const usage = result?.usage;\n resolove({ id: uuidv4(), model: opts.model, choices, usage });\n } else {\n // streaming\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n let result;\n const choicesList: types.chat.Choice[] = [];\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n if (event.type === 'event') {\n if (event.data !== '[DONE]') {\n try {\n result = JSON.parse(event.data);\n const choices = this.convertChoices(result.choices);\n onProgress?.(choices);\n choicesList.push(...choices);\n } catch (e) {\n // ignore\n }\n }\n }\n });\n body.on('readable', async () => {\n let chunk: string | Buffer;\n while ((chunk = body.read())) {\n parser.feed(chunk.toString());\n }\n });\n\n body.on('end', async () => {\n const choices: types.chat.Choice[] = this.combineChoices(choicesList);\n resolove({ id: uuidv4(), model: opts.model, choices, usage: result.usage });\n });\n }\n });\n }\n\n /**\n * https://platform.deepseek.com/api-docs/zh-cn/api/create-chat-completion/index.html\n * @returns\n */\n private async convertParams(opts: types.chat.SendOptions): Promise {\n const params: deepseek.Request = {\n model: opts.model || 'moonshot-v1-8k',\n messages: await this.corvertContents(opts),\n temperature: opts?.temperature || 0.9,\n top_p: opts?.top_p || 1.0,\n // frequency_penalty: 0,\n // presence_penalty: 0,\n max_tokens: opts?.max_tokens || 1000,\n // n: opts.n || 1,\n stop: opts?.stop_sequences || undefined,\n stream: true,\n };\n // tools\n if (opts.tools && opts.tools.length > 0) {\n Object.assign(params, { tools: opts.tools, stream: false });\n }\n return params;\n }\n\n private async corvertContents(opts: types.chat.SendOptions): Promise {\n return Promise.all(\n opts.messages.map(async (item) => {\n const parts: string[] = [];\n await Promise.all(\n item.parts.map(async (part: types.chat.Part) => {\n // text\n if (part.type === 'text') {\n parts.push(part.text);\n }\n // file, only support image, now\n if (part.type === 'file' && part?.extract) {\n parts.push(part.extract);\n }\n }),\n );\n\n return { role: item.role, content: parts.join('\\n') } as deepseek.Message;\n }),\n );\n }\n\n protected convertChoices(candidates: deepseek.Choice[]): types.chat.Choice[] {\n const choices: types.chat.Choice[] = [];\n try {\n candidates.map(({ index, delta, message, finish_reason }: deepseek.Choice) => {\n const parts: types.chat.Part[] = [];\n let { content } = message || delta;\n if (delta) {\n content = delta.content;\n }\n if (content) {\n parts.push({ type: 'text', text: content });\n }\n\n choices.push({ index, role: 'assistant', parts, finish_reason });\n });\n } catch (err) {\n console.warn(err);\n }\n return choices;\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { v4 as uuidv4 } from 'uuid';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { ChatBaseAPI } from '../base';\nimport { groq } from './types';\n\nexport class GroqCompletionsAPI extends ChatBaseAPI {\n protected provider: string = 'groq';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://api.groq.com/openai/v1' }, opts);\n super(options);\n }\n\n public models(): string[] {\n return ['llama3-8b-8192', 'llama3-70b-8192', 'mixtral-8x7b-32768', 'gemma-7b-it'];\n }\n\n async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n\n return new Promise(async (resolove, reject) => {\n const url = `${this.baseURL}/chat/completions`;\n const params: groq.Request = await this.convertParams(options);\n // console.log(`[fetch]params`, JSON.stringify(params, null, 2));\n const res = await fetchSSE(url, {\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${this.apiKey}` },\n body: JSON.stringify(params),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.error?.message || 'request error', res.status));\n }\n\n // not stream\n if (params.stream === false) {\n const result = await res.json();\n const choices = this.convertChoices(result.choices);\n const usage = result?.usage;\n resolove({ id: uuidv4(), model: opts.model, choices, usage });\n } else {\n // streaming\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n let result;\n const choicesList: types.chat.Choice[] = [];\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n if (event.type === 'event') {\n if (event.data !== '[DONE]') {\n try {\n result = JSON.parse(event.data);\n const choices = this.convertChoices(result.choices);\n onProgress?.(choices);\n choicesList.push(...choices);\n } catch (e) {\n // ignore\n }\n }\n }\n });\n body.on('readable', async () => {\n let chunk: string | Buffer;\n while ((chunk = body.read())) {\n parser.feed(chunk.toString());\n }\n });\n\n body.on('end', async () => {\n const choices: types.chat.Choice[] = this.combineChoices(choicesList);\n const { prompt_tokens, completion_tokens, total_tokens } = result?.x_groq?.usage;\n const usage = { prompt_tokens, completion_tokens, total_tokens };\n resolove({ id: uuidv4(), model: opts.model, choices, usage });\n });\n }\n });\n }\n\n /**\n * 转换为 Gemini 要求的请求参数\n * https://platform.groq.com/docs/api-reference/chat/create\n * @returns\n */\n private async convertParams(opts: types.chat.SendOptions): Promise {\n const params: groq.Request = {\n model: opts.model || 'gpt-3.5-turbo-0125',\n messages: await this.corvertContents(opts),\n temperature: opts?.temperature || 0.9,\n top_p: opts?.top_p || 1,\n // frequency_penalty: 0,\n // presence_penalty: 0,\n max_tokens: opts?.max_tokens || 1000,\n n: opts.n || 1,\n stop: opts?.stop_sequences || undefined,\n stream: true,\n };\n // tools\n if (opts.tools && opts.tools.length > 0) {\n Object.assign(params, { tools: opts.tools, stream: false });\n }\n return params;\n }\n\n private async corvertContents(opts: types.chat.SendOptions): Promise {\n return Promise.all(\n opts.messages.map(async (item) => {\n const parts: groq.Part[] = [];\n const tool_calls: groq.ToolCallPart[] = [];\n await Promise.all(\n item.parts.map(async (part: types.chat.Part) => {\n // text\n if (part.type === 'text') {\n parts.push({ type: 'text', text: part.text });\n }\n // file: docs\n if (part.type === 'file' && part?.extract) {\n parts.push({ type: 'text', text: part.extract });\n }\n\n // file, only support image, now\n if (part.type === 'file' && part.mimetype?.startsWith('image')) {\n parts.push({ type: 'image_url', image_url: { url: (part as types.chat.FilePart).url } });\n }\n // tools\n if (part.type === 'function_call' && part.id) {\n const { name, args } = part.function_call;\n tool_calls.push({ id: part.id, type: 'function', function: { name, arguments: args } });\n }\n }),\n );\n if (item.role === 'system') {\n return { role: 'system', content: this.filterTextPartsToString(parts) } as groq.Message;\n }\n if (item.role === 'assistant') {\n return {\n role: 'assistant',\n content: parts,\n tool_calls: tool_calls.length > 0 ? tool_calls : undefined,\n } as groq.Message;\n }\n return { role: 'user', content: parts } as groq.Message;\n }),\n );\n }\n\n private filterTextPartsToString(parts: groq.Part[]): string {\n return parts\n .filter((p) => p.type === 'text')\n .map((p) => (p as groq.TextPart).text)\n .join('');\n }\n\n protected convertChoices(candidates: groq.Choice[]): types.chat.Choice[] {\n const choices: types.chat.Choice[] = [];\n try {\n candidates.map(({ index, delta, message, finish_reason }: groq.Choice) => {\n const parts: types.chat.Part[] = [];\n let { content, tool_calls } = message || delta;\n if (delta) {\n content = delta.content;\n tool_calls = delta.tool_calls;\n }\n if (content) {\n parts.push({ type: 'text', text: content });\n }\n if (tool_calls) {\n tool_calls.map((call: any) => {\n const { name, arguments: args } = call.function;\n parts.push({ type: 'function_call', function_call: { name, args }, id: call.id });\n });\n }\n\n choices.push({ index, role: 'assistant', parts, finish_reason });\n });\n } catch (err) {\n console.warn(err);\n }\n return choices;\n }\n}\n","import { OpenAICompletionsAPI, OpenAIAssistantsAPI, GoogleClaudeAPI } from '@/provider';\nimport { MoonshotKimiAPI, QcloudHunyuanAPI, DeepSeekAPI } from '@/provider';\nimport { GoogleVertexAPI, GoogleGeminiAPI } from '@/provider';\nimport { AnthropicClaudeAPI, AnthropicBedrockAPI } from '@/provider';\nimport { AliyunQwenAPI, AliyunWanxAPI } from '@/provider';\nimport { ChatBaseAPI } from '@/provider/base';\nimport { GroqCompletionsAPI } from '@/provider/groq';\nimport * as types from '@/types';\n\nexport class ChatAPI {\n private provider: ChatBaseAPI | null = null;\n\n constructor(provider: string, opts: types.chat.ChatOptions) {\n switch (provider) {\n case types.Provider.GOOGLE_VERTEX:\n this.provider = new GoogleVertexAPI(opts);\n break;\n case types.Provider.GOOGLE_GEMINI:\n this.provider = new GoogleGeminiAPI(opts);\n break;\n case types.Provider.GOOGLE_CLAUDE:\n this.provider = new GoogleClaudeAPI(opts);\n break;\n case types.Provider.OPENAI_COMPLETIONS:\n this.provider = new OpenAICompletionsAPI(opts);\n break;\n case types.Provider.OPENAI_ASSISTANTS:\n this.provider = new OpenAIAssistantsAPI(opts);\n break;\n case types.Provider.ALIYUN_QWEN:\n this.provider = new AliyunQwenAPI(opts);\n break;\n case types.Provider.ALIYUN_WANX:\n this.provider = new AliyunWanxAPI(opts);\n break;\n case types.Provider.ANTHROPIC_CLAUDE:\n this.provider = new AnthropicClaudeAPI(opts);\n break;\n case types.Provider.ANTHROPIC_BEDROCK:\n this.provider = new AnthropicBedrockAPI(opts);\n break;\n case types.Provider.QCLOUD_HUNYUAN:\n this.provider = new QcloudHunyuanAPI(opts);\n break;\n case types.Provider.MOONSHOT_KIMI:\n this.provider = new MoonshotKimiAPI(opts);\n break;\n case types.Provider.DEEPSEEK:\n this.provider = new DeepSeekAPI(opts);\n break;\n case types.Provider.GROQ:\n this.provider = new GroqCompletionsAPI(opts);\n break;\n default:\n throw new Error(`Unsupported supplier: ${provider}`);\n }\n }\n\n public async sendMessage(opts: types.chat.SendOptions | types.image.SendOptions) {\n if (!this.provider) {\n throw new Error('Provider is not initialized');\n }\n return await this.provider.sendMessage(opts);\n }\n}\n","import { AliyunWanxAPI } from '@/provider';\nimport { ChatBaseAPI } from '@/provider/base';\n\nimport * as types from '@/types';\n\nexport class ImageAPI {\n private provider: ChatBaseAPI | null = null;\n\n constructor(provider: string, opts: types.chat.ChatOptions) {\n switch (provider) {\n case types.Provider.ALIYUN_WANX:\n this.provider = new AliyunWanxAPI(opts);\n break;\n default:\n throw new Error(`Unsupported supplier: ${provider}`);\n }\n }\n\n public async sendMessage(opts: types.image.SendOptions) {\n if (!this.provider) {\n throw new Error('Provider is not initialized');\n }\n return await this.provider.sendMessage(opts);\n }\n\n public async getTaskResult(task_id: string) {\n if (!this.provider) {\n throw new Error('Provider is not initialized');\n }\n return await this.provider.getTaskResult(task_id);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAO,IAAK,WAAL,kBAAKA,cAAL;AACL,EAAAA,UAAA,mBAAgB;AAChB,EAAAA,UAAA,mBAAgB;AAChB,EAAAA,UAAA,mBAAgB;AAChB,EAAAA,UAAA,wBAAqB;AACrB,EAAAA,UAAA,uBAAoB;AACpB,EAAAA,UAAA,sBAAmB;AACnB,EAAAA,UAAA,uBAAoB;AACpB,EAAAA,UAAA,iBAAc;AACd,EAAAA,UAAA,iBAAc;AACd,EAAAA,UAAA,oBAAiB;AACjB,EAAAA,UAAA,mBAAgB;AAChB,EAAAA,UAAA,cAAW;AACX,EAAAA,UAAA,UAAO;AAbG,SAAAA;AAAA,GAAA;;;ACAZ,IAAAC,qBAAqB;AACrB,kBAA6B;AAC7B,IAAAC,4BAAgC;AAChC,gCAAsE;;;ACA/D,IAAU;AAAA,CAAV,CAAUC,UAAV;AAAA,EACE,MAAM,kBAAkB,MAAM;AAAA,IAGnC,YAAY,SAAiB,MAAc;AACzC,YAAM,OAAO;AACb,WAAK,OAAO;AAAA,IACd;AAAA,EACF;AAPO,EAAAA,MAAM;AAAA,GADE;;;ACHjB,sBAA6B;AAC7B,wBAAkB;AAClB,+BAAgC;AAG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AGrC,YAAQ,UAAU;AAAA,MAChB;AACE,aAAK,WAAW,IAAI,cAAc,IAAI;AACtC;AAAA,MACF;AACE,cAAM,IAAI,MAAM,yBAAyB,QAAQ,EAAE;AAAA,IACvD;AAAA,EACF;AAAA,EAEA,MAAa,YAAY,MAA+B;AACtD,QAAI,CAAC,KAAK,UAAU;AAClB,YAAM,IAAI,MAAM,6BAA6B;AAAA,IAC/C;AACA,WAAO,MAAM,KAAK,SAAS,YAAY,IAAI;AAAA,EAC7C;AAAA,EAEA,MAAa,cAAc,SAAiB;AAC1C,QAAI,CAAC,KAAK,UAAU;AAClB,YAAM,IAAI,MAAM,6BAA6B;AAAA,IAC/C;AACA,WAAO,MAAM,KAAK,SAAS,cAAc,OAAO;AAAA,EAClD;AACF;","names":["Provider","import_node_fetch","import_https_proxy_agent","chat","fetch","fetchSSE","uuidv4","import_node_fetch","import_uuid","import_https_proxy_agent","import_eventsource_parser","import_node_fetch","import_uuid","import_https_proxy_agent","import_eventsource_parser","fetchSSE","res","uuidv4","fetchSSE","res","uuidv4","import_node_fetch","import_google_auth_library","import_https_proxy_agent","import_eventsource_parser","fetchSSE","res","import_node_fetch","import_https_proxy_agent","import_eventsource_parser","fetchSSE","res","import_node_fetch","import_https_proxy_agent","import_eventsource_parser","fetchSSE","import_node_fetch","import_uuid","import_https_proxy_agent","import_eventsource_parser","fetchSSE","res","uuidv4","item","import_node_fetch","import_https_proxy_agent","fetchSSE","import_node_fetch","import_uuid","import_https_proxy_agent","import_eventsource_parser","fetchSSE","uuidv4","import_uuid","uuidv4","choices","import_node_fetch","import_uuid","import_https_proxy_agent","import_eventsource_parser","fetchSSE","uuidv4","import_node_fetch","import_uuid","import_https_proxy_agent","import_eventsource_parser","fetchSSE","uuidv4"]} \ No newline at end of file diff --git a/packages/bodhi-adapter/dist/index.js b/packages/bodhi-adapter/dist/index.js index cba7f8f..0c1de26 100644 --- a/packages/bodhi-adapter/dist/index.js +++ b/packages/bodhi-adapter/dist/index.js @@ -476,7 +476,9 @@ ${part.text} choices.push({ index, role: 'assistant', parts, finish_reason: 'stop' }); }); } catch (err) { + console.log(`->candidates1`, JSON.stringify(candidates, null, 2)); console.warn(err); + console.log(`->candidates2`); } return choices; } @@ -540,7 +542,10 @@ var GoogleVertexAPI = class extends GoogleGeminiAPI { const parser = createParser3((event) => { if (event.type === 'event') { const res2 = JSON.parse(event.data); - const choices = this.convertChoices(res2.candidates); + if (!res2.candidates) { + console.log(`[vertex]debug`, res2); + } + const choices = this.convertChoices(res2.candidates || []); if (res2.usageMetadata) { Object.assign(usage, { prompt_tokens: res2.usageMetadata.promptTokenCount, @@ -591,7 +596,7 @@ var GoogleClaudeAPI = class extends ChatBaseAPI { return await auth.getAccessToken(); } models() { - return ['claude-3-sonnet@20240229', 'claude-3-haiku@20240307']; + return ['claude-3-sonnet@20240229', 'claude-3-haiku@20240307', 'gemini-1.5-flash-preview-0514']; } /** * Send message diff --git a/packages/bodhi-adapter/dist/index.js.map b/packages/bodhi-adapter/dist/index.js.map index 3c610c4..df4e8f1 100644 --- a/packages/bodhi-adapter/dist/index.js.map +++ b/packages/bodhi-adapter/dist/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/types/provider.ts","../src/provider/openai/completions.ts","../src/types/chat.ts","../src/provider/base.ts","../src/provider/openai/assistants.ts","../src/provider/google/vertex.ts","../src/provider/google/gemini.ts","../src/provider/google/claude.ts","../src/provider/anthropic/claude.ts","../src/provider/anthropic/bedrock.ts","../src/provider/anthropic/auth.ts","../src/provider/aliyun/qwen.ts","../src/provider/aliyun/wanx.ts","../src/provider/moonshot/kimi.ts","../src/provider/qcloud/hunyuan.ts","../src/provider/deepseek/deepseek.ts","../src/provider/groq/completions.ts","../src/api/chat.ts","../src/api/image.ts"],"sourcesContent":["export enum Provider {\n GOOGLE_GEMINI = 'google-gemini',\n GOOGLE_VERTEX = 'google-vertex',\n GOOGLE_CLAUDE = 'google-claude',\n OPENAI_COMPLETIONS = 'openai-completion',\n OPENAI_ASSISTANTS = 'openai-assistant',\n ANTHROPIC_CLAUDE = 'anthropic-claude',\n ANTHROPIC_BEDROCK = 'anthropic-bedrock',\n ALIYUN_QWEN = 'aliyun-qwen',\n ALIYUN_WANX = 'aliyun-wanx',\n QCLOUD_HUNYUAN = 'qcloud-hunyuan',\n MOONSHOT_KIMI = 'moonshot-kimi',\n DEEPSEEK = 'deepseek',\n GROQ = 'groq',\n}\n","import fetchSSE from 'node-fetch';\nimport { v4 as uuidv4 } from 'uuid';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { ChatBaseAPI } from '../base';\nimport { openai } from './types';\n\nexport class OpenAICompletionsAPI extends ChatBaseAPI {\n protected provider: string = 'openai';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://api.openai.com/v1' }, opts);\n super(options);\n }\n\n public models(): string[] {\n return [\n 'gpt-3.5-turbo',\n 'gpt-3.5-turbo-0125',\n 'gpt-3.5-turbo-16k',\n 'gpt-3.5-turbo-instruct',\n 'gpt-4',\n 'gpt-4-0125-preview',\n 'gpt-4-turbo-preview',\n 'gpt-4-32k',\n ];\n }\n\n async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n\n return new Promise(async (resolove, reject) => {\n const url = `${this.baseURL}/chat/completions`;\n const params: openai.Request = await this.convertParams(options);\n // console.log(`[fetch]params`, JSON.stringify(params, null, 2));\n const res = await fetchSSE(url, {\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${this.apiKey}` },\n body: JSON.stringify(params),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.error?.message || 'request error', res.status));\n }\n\n // not stream\n if (params.stream === false) {\n const result = await res.json();\n const choices = this.convertChoices(result.choices);\n const usage = result?.usage;\n resolove({ id: uuidv4(), model: opts.model, choices, usage });\n } else {\n // streaming\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n const choicesList: types.chat.Choice[] = [];\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n if (event.type === 'event') {\n if (event.data !== '[DONE]') {\n try {\n const result = JSON.parse(event.data);\n const choices = this.convertChoices(result.choices);\n onProgress?.(choices);\n choicesList.push(...choices);\n } catch (e) {\n // ignore\n }\n }\n }\n });\n body.on('readable', async () => {\n let chunk: string | Buffer;\n while ((chunk = body.read())) {\n parser.feed(chunk.toString());\n }\n });\n\n body.on('end', async () => {\n const choices: types.chat.Choice[] = this.combineChoices(choicesList);\n const usage = this.caclulateUsage(opts.messages, choices);\n resolove({ id: uuidv4(), model: opts.model, choices, usage });\n });\n }\n });\n }\n\n /**\n * 转换为 Gemini 要求的请求参数\n * https://platform.openai.com/docs/api-reference/chat/create\n * @returns\n */\n private async convertParams(opts: types.chat.SendOptions): Promise {\n const params: openai.Request = {\n model: opts.model || 'gpt-3.5-turbo-0125',\n messages: await this.corvertContents(opts),\n temperature: opts?.temperature || 0.9,\n top_p: opts?.top_p || 1,\n // frequency_penalty: 0,\n // presence_penalty: 0,\n max_tokens: opts?.max_tokens || 1000,\n n: opts.n || 1,\n stop: opts?.stop_sequences || undefined,\n stream: true,\n };\n // tools\n if (opts.tools && opts.tools.length > 0) {\n Object.assign(params, { tools: opts.tools, stream: false });\n }\n return params;\n }\n\n private async corvertContents(opts: types.chat.SendOptions): Promise {\n return Promise.all(\n opts.messages.map(async (item) => {\n const parts: openai.Part[] = [];\n const tool_calls: openai.ToolCallPart[] = [];\n await Promise.all(\n item.parts.map(async (part: types.chat.Part) => {\n // text\n if (part.type === 'text') {\n parts.push({ type: 'text', text: part.text });\n }\n // file: docs\n if (part.type === 'file' && part?.extract) {\n parts.push({ type: 'text', text: part.extract });\n }\n // file, only support image, now\n if (part.type === 'file' && part.mimetype?.startsWith('image')) {\n // TODO: fetch 下载图片并转化buffer为base64\n // parts.push({ type: 'image_url', image_url: (part as types.chat.FilePart).url });\n parts.push({ type: 'image_url', image_url: { url: (part as types.chat.FilePart).url } });\n }\n // tools\n if (part.type === 'function_call' && part.id) {\n const { name, args } = part.function_call;\n tool_calls.push({ id: part.id, type: 'function', function: { name, arguments: args } });\n }\n }),\n );\n if (item.role === 'system') {\n return { role: 'system', content: this.filterTextPartsToString(parts) } as openai.Message;\n }\n if (item.role === 'assistant') {\n return {\n role: 'assistant',\n content: parts,\n tool_calls: tool_calls.length > 0 ? tool_calls : undefined,\n } as openai.Message;\n }\n return { role: 'user', content: parts } as openai.Message;\n }),\n );\n }\n\n private filterTextPartsToString(parts: openai.Part[]): string {\n return parts\n .filter((p) => p.type === 'text')\n .map((p) => (p as openai.TextPart).text)\n .join('');\n }\n\n protected convertChoices(candidates: openai.Choice[]): types.chat.Choice[] {\n const choices: types.chat.Choice[] = [];\n try {\n candidates.map(({ index, delta, message, finish_reason }: openai.Choice) => {\n const parts: types.chat.Part[] = [];\n let { content, tool_calls } = message || delta;\n if (delta) {\n content = delta.content;\n tool_calls = delta.tool_calls;\n }\n if (content) {\n parts.push({ type: 'text', text: content });\n }\n if (tool_calls) {\n tool_calls.map((call: any) => {\n const { name, arguments: args } = call.function;\n parts.push({ type: 'function_call', function_call: { name, args }, id: call.id });\n });\n }\n\n choices.push({ index, role: 'assistant', parts, finish_reason });\n });\n } catch (err) {\n console.warn(err);\n }\n return choices;\n }\n}\n","/**\n * Chat\n */\nexport namespace chat {\n export class ChatError extends Error {\n name: 'ChatError';\n code: number;\n constructor(message: string, code: number) {\n super(message);\n this.code = code;\n }\n }\n\n export type ChatOptions = {\n agent?: string;\n baseURL?: string;\n apiKey: string;\n apiSecret?: string;\n timeout?: number;\n };\n\n /**\n * Request\n */\n export type SendOptions = {\n model: string;\n messages: Message[];\n tools?: Tools[];\n temperature?: number;\n top_p?: number;\n top_k?: number;\n n?: number;\n max_tokens?: number;\n stop_sequences?: string[];\n stream?: boolean;\n onProgress?: (event: any) => void;\n };\n\n /* Message */\n export type Message = { role: string; parts: Part[] };\n\n export type Part = TextPart | FilePart | ToolPart;\n export type TextPart = { type: 'text'; text: string };\n export type FilePart = { type: 'file'; mimetype: string; url: string; id: string; extract?: string };\n export type ToolPart = FunctionCallTool | FunctionTool;\n\n /* Tools */\n export type Tools = FunctionTool;\n export type FunctionCallTool = {\n type: 'function_call';\n function_call: { name: string; args: any };\n id?: string | undefined;\n };\n export type FunctionTool = { type: 'function'; function: Function };\n\n export type Function = {\n name: string;\n description: string;\n parameters: { type: string; properties: any; required: string[] };\n };\n\n /**\n * Response\n */\n export type ChatResponse = {\n id: string;\n model: string;\n choices: Choice[];\n usage: Usage;\n };\n\n export type Choice = {\n index: number;\n role: string;\n parts: Part[];\n finish_reason: 'stop' | 'function_call' | string | null;\n };\n\n export type Usage = { prompt_tokens: number; completion_tokens: number; total_tokens: number };\n}\n","import { get_encoding } from 'tiktoken';\nimport fetch from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport * as types from '@/types';\n\nexport class ChatBaseAPI {\n protected provider: string = '';\n\n protected agent?: string = '';\n protected baseURL: string = '';\n protected apiKey: string = '';\n protected apiSecret?: string = '';\n protected timeout?: number = 10000;\n\n constructor(opts: types.chat.ChatOptions) {\n opts.agent && (this.agent = opts.agent);\n opts.baseURL && (this.baseURL = opts.baseURL);\n opts.apiKey && (this.apiKey = opts.apiKey);\n opts.apiSecret && (this.apiSecret = opts.apiSecret);\n opts.timeout && (this.timeout = opts.timeout);\n }\n\n public models(): string[] {\n throw new Error('Not implemented');\n }\n\n public async sendMessage(opts: types.chat.SendOptions | types.image.SendOptions): Promise {\n throw new Error('Not implemented');\n }\n\n public async getTaskResult(task_id: string): Promise {\n throw new Error('Not implemented');\n }\n\n protected async fetchFile(url: string) {\n const response = await fetch(url, {\n headers: {\n 'user-agent':\n 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',\n },\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n });\n const buffer = await response.buffer();\n const base64 = buffer.toString('base64');\n const mimeType = response.headers.get('content-type') as string;\n return { mimeType, data: base64 };\n }\n\n protected combineChoices(choices: types.chat.Choice[]): types.chat.Choice[] {\n return choices.reduce((acc: types.chat.Choice[], item: types.chat.Choice) => {\n const existingItem = acc.find((i: types.chat.Choice) => i.index === item.index);\n if (existingItem) {\n item.parts.forEach((part: types.chat.Part) => {\n if (part.type === 'text') {\n const existingPart = existingItem.parts.find((p: types.chat.Part) => p.type === 'text');\n if (existingPart) {\n (existingPart as types.chat.TextPart).text += (part as types.chat.TextPart).text;\n } else {\n existingItem.parts.push(part);\n }\n } else if (part.type === 'function_call') {\n const existingPart = existingItem.parts.find((p: types.chat.Part) => p.type === 'function_call');\n if (existingPart) {\n (existingPart as types.chat.FunctionCallTool).function_call.name +=\n (part as types.chat.FunctionCallTool).function_call.name || '';\n (existingPart as types.chat.FunctionCallTool).function_call.args +=\n (part as types.chat.FunctionCallTool).function_call.args || '';\n } else {\n existingItem.parts.push(part);\n }\n } else {\n const existingPart = existingItem.parts.find(\n (p: types.chat.Part) => JSON.stringify(p) === JSON.stringify(part),\n );\n if (!existingPart) {\n existingItem.parts.push(part);\n }\n }\n });\n\n // finish_reason\n existingItem.finish_reason = item.finish_reason;\n } else {\n acc.push(item);\n }\n return acc;\n }, []);\n }\n\n protected caclulateUsage(messages: types.chat.Message[], choices: types.chat.Choice[]): types.chat.Usage {\n const parts: types.chat.Part[] = messages.flatMap((item) => item.parts);\n const prompt_tokens = parts\n .filter((p) => p.type === 'text' || (p.type === 'file' && p.extract))\n .reduce((acc: number, item) => {\n return acc + this.getTokenCount((item as types.chat.TextPart)?.text || (item as types.chat.FilePart)?.extract);\n }, 0);\n const completion_tokens = choices.reduce((acc: number, item: types.chat.Choice) => {\n return acc + this.getTokenCount(item.parts.map((part) => (part as types.chat.TextPart).text).join(''));\n }, 0);\n return { prompt_tokens, completion_tokens, total_tokens: prompt_tokens + completion_tokens };\n }\n\n protected getTokenCount(text: string) {\n return get_encoding('cl100k_base').encode(text).length;\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { ChatBaseAPI } from '../base';\n\nexport class OpenAIAssistantsAPI extends ChatBaseAPI {\n protected provider: string = 'openai';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://api.openai.com/v1' }, opts);\n super(options);\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { v4 as uuidv4 } from 'uuid';\nimport { GoogleAuth } from 'google-auth-library';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { GoogleGeminiAPI } from './gemini';\nimport { gemini } from './types';\n\nexport class GoogleVertexAPI extends GoogleGeminiAPI {\n protected provider: string = 'google';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign(\n {\n baseURL: 'https://us-central1-aiplatform.googleapis.com/v1/projects/bodhi-415003/locations/us-central1',\n },\n opts,\n );\n super(options);\n }\n\n public models(): string[] {\n return ['gemini-1.0-pro', 'gemini-1.5-pro-preview-0409'];\n }\n\n /**\n * 根据服务账号获取 access token\n */\n private async getToken(): Promise {\n const auth: GoogleAuth = new GoogleAuth({\n credentials: { client_email: this.apiKey, private_key: this.apiSecret },\n scopes: 'https://www.googleapis.com/auth/cloud-platform',\n });\n return (await auth.getAccessToken()) as string;\n }\n\n /**\n * 发送消息\n * @param opts \n * Reference: https://cloud.google.com/vertex-ai/docs/reference/rest/v1/GenerateContentResponse\n * Reference: https://cloud.google.com/vertex-ai/docs/generative-ai/model-reference/gemini?hl=zh-cn\n * Multi-modal: https://cloud.google.com/vertex-ai/docs/generative-ai/multimodal/send-multimodal-prompts?hl=zh-cn#gemini-send-multimodal-samples-drest\n * Tools: https://cloud.google.com/vertex-ai/docs/generative-ai/multimodal/function-calling?hl=zh-cn\n * @returns\n */\n public async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n\n return new Promise(async (resolove, reject) => {\n const token = await this.getToken();\n const model = this.detechModel(opts);\n const url = `${this.baseURL}/publishers/google/models/${model}:streamGenerateContent?alt=sse`;\n const params: gemini.Request = await this.convertParams(options);\n // console.log(`[fetch]params`, model, url, opts.messages);\n\n const res = await fetchSSE(url, {\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },\n body: JSON.stringify(params),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.error?.message || 'request error', res.status));\n }\n\n // only get content from node-fetch\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n // streaming\n const choicesList: types.chat.Choice[] = [];\n const usage: types.chat.Usage = { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n if (event.type === 'event') {\n const res = JSON.parse(event.data);\n const choices = this.convertChoices(res.candidates);\n if (res.usageMetadata) {\n Object.assign(usage, {\n prompt_tokens: res.usageMetadata.promptTokenCount,\n completion_tokens: res.usageMetadata.candidatesTokenCount,\n total_tokens: res.usageMetadata.totalTokenCount,\n });\n }\n onProgress?.(choices);\n choicesList.push(...choices);\n }\n });\n body.on('readable', async () => {\n let chunk: string | Buffer;\n while ((chunk = body.read())) {\n parser.feed(chunk.toString());\n }\n });\n\n // finished\n body.on('end', () => {\n const choices: types.chat.Choice[] = this.combineChoices(choicesList);\n // TODO: Google AI Gemini not found usageMetadata, but vertex founded.\n resolove({ id: uuidv4(), model: opts.model, choices, usage });\n });\n });\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { v4 as uuidv4 } from 'uuid';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { gemini } from './types';\nimport { ChatBaseAPI } from '../base';\n\nexport class GoogleGeminiAPI extends ChatBaseAPI {\n protected provider: string = 'google';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://generativelanguage.googleapis.com/v1beta' }, opts);\n super(options);\n }\n\n public models(): string[] {\n return ['gemini-pro', 'gemini-pro-vision', 'gemini-1.5-pro-latest'];\n }\n\n /**\n *\n * https://ai.google.dev/docs/gemini_api_overview?hl=zh-cn#curl_3\n * @param opts\n * @returns\n */\n public async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n return new Promise(async (resolove, reject) => {\n const params: gemini.Request = await this.convertParams(options);\n const model = this.detechModel(opts);\n const url = `${this.baseURL}/models/${model}:streamGenerateContent?alt=sse`;\n // console.log(`[fetch]params`, url, JSON.stringify(params, null, 2));\n\n const res = await fetchSSE(url, {\n headers: { 'Content-Type': 'application/json', 'x-goog-api-key': this.apiKey },\n body: JSON.stringify(params),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n // console.log(`[fetch]result`, res);\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.error?.message || 'request error', res.status));\n }\n\n // only get content from node-fetch\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n // streaming\n const choicesList: types.chat.Choice[] = [];\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n if (event.type === 'event') {\n const res = JSON.parse(event.data);\n // console.log(`->`, JSON.stringify(res));\n const choices = this.convertChoices(res.candidates);\n onProgress?.(choices);\n\n choicesList.push(...choices);\n }\n });\n body.on('readable', async () => {\n let chunk: string | Buffer;\n while ((chunk = body.read())) {\n parser.feed(chunk.toString());\n }\n });\n\n body.on('end', () => {\n const choices: types.chat.Choice[] = this.combineChoices(choicesList);\n // TODO: Google AI Gemini not found usageMetadata, but vertex founded.\n const usage = { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };\n resolove({ id: uuidv4(), model: opts.model, choices, usage });\n });\n });\n }\n\n protected detechModel(opts: types.chat.SendOptions): string {\n const hasMedia = opts.messages.some((item) =>\n item.parts.some(\n (part) =>\n part.type === 'file' &&\n (part.mimetype.startsWith('image') || part.mimetype.startsWith('video') || part.mimetype.startsWith('audio')),\n ),\n );\n return hasMedia && opts.model === 'gemini-1.0-pro' ? 'gemini-1.0-pro-vision' : opts.model;\n }\n\n /**\n * 转换为 Gemini 要求的请求参数\n * https://cloud.google.com/vertex-ai/docs/reference/rest/v1/GenerateContentResponse\n * @returns\n */\n protected async convertParams(opts: types.chat.SendOptions): Promise {\n return {\n contents: await this.corvertContents(opts),\n // systemInstruction: await this.corvertSystemContent(opts),\n tools: this.corvertTools(opts),\n safety_settings: [\n // { category: 'BLOCK_NONE', threshold: 'HARM_CATEGORY_UNSPECIFIED' },\n ],\n generationConfig: {\n temperature: opts.temperature || 0.9, // gemini-pro:0.9, gemini-pro-vision:0.4\n topP: opts.top_p || 1, // gemini-pro:none, gemini-pro-vision:32\n // topK: Math.round((opts.top_k || 0.025) * 40) || 32,\n candidateCount: opts.n || 1,\n maxOutputTokens: opts.max_tokens || 2048, // gemini-pro:2048, gemini-pro-vision:8192\n stopSequences: opts.stop_sequences || undefined,\n },\n };\n }\n\n protected async corvertContents(opts: types.chat.SendOptions): Promise {\n // filter system role\n const rows = await Promise.all(\n opts.messages\n .filter((item) => ['user', 'assistant'].includes(item.role))\n .map(async (item) => {\n const parts: gemini.Part[] = [];\n await Promise.all(\n item.parts.map(async (part: types.chat.Part) => {\n // text\n if (part.type === 'text') {\n parts.push({ text: part.text });\n }\n // file\n if (part.type === 'file') {\n if (part?.extract) {\n parts.push({ text: part.extract });\n } else {\n const { mimetype: mimeType, url } = part as types.chat.FilePart;\n if (url.startsWith('gs://')) {\n parts.push({ fileData: { mimeType, fileUri: url } });\n } else {\n try {\n parts.push({ inlineData: await this.fetchFile(url) });\n } catch (err) {}\n }\n }\n }\n // tools\n if (part.type === 'function_call') {\n const { name, args } = part.function_call;\n parts.push({ functionCall: { name, args } });\n }\n }),\n );\n item.role = item.role === 'assistant' ? 'model' : item.role;\n return { role: item.role, parts } as gemini.Content;\n }),\n );\n\n // Compatible with system role\n // insert system text part to rows's first user parts\n const system = opts.messages.filter((item) => item.role === 'system');\n if (system.length > 0) {\n const textParts = system[0].parts.filter((part) => 'text' in part) as gemini.TextPart[];\n rows[0].parts.unshift(...textParts.map((part) => ({ text: `[instructions]\\n${part.text}\\n\\n[user prompt]\\n` })));\n }\n\n return rows;\n }\n\n protected corvertTools(opts: types.chat.SendOptions): gemini.Tools[] {\n const tools: gemini.Tools[] = [];\n if (opts.tools) {\n opts.tools.map((item) => {\n if (item.type === 'function') {\n tools.push({ functionDeclarations: [item.function] });\n }\n });\n }\n return tools;\n }\n\n protected convertChoices(candidates: gemini.Candidate[]): types.chat.Choice[] {\n const choices: types.chat.Choice[] = [];\n try {\n candidates.map(({ index, content, finishReason }: gemini.Candidate) => {\n const parts: types.chat.Part[] = [];\n content.parts.map((part: any) => {\n if ('text' in part) {\n parts.push({ type: 'text', text: part.text });\n }\n if ('functionCall' in part) {\n parts.push({ type: 'function_call', function_call: part.functionCall });\n }\n });\n choices.push({ index, role: 'assistant', parts, finish_reason: 'stop' });\n });\n } catch (err) {\n console.warn(err);\n }\n return choices;\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { GoogleAuth } from 'google-auth-library';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { claude } from '../anthropic/types';\nimport { ChatBaseAPI } from '../base';\n\nexport class GoogleClaudeAPI extends ChatBaseAPI {\n protected provider: string = 'google';\n\n constructor(opts: types.chat.ChatOptions) {\n // available models: claude-instant-1p2(100K tokens), claude-2p0(200K tokens)\n // available regions: us-central1(60QPM), asia-southeast1(60QPM)\n const options = Object.assign(\n { baseURL: 'https://us-central1-aiplatform.googleapis.com/v1/projects/bodhi-415003/locations/us-central1' },\n opts,\n );\n super(options);\n }\n\n /**\n * 根据服务账号获取 access token\n */\n private async getToken(): Promise {\n const auth: GoogleAuth = new GoogleAuth({\n credentials: { client_email: this.apiKey, private_key: this.apiSecret },\n scopes: 'https://www.googleapis.com/auth/cloud-platform',\n });\n return (await auth.getAccessToken()) as string;\n }\n\n public models(): string[] {\n return ['claude-3-sonnet@20240229', 'claude-3-haiku@20240307'];\n }\n\n /**\n * Send message\n * https://docs.anthropic.com/claude/reference/messages_post\n * @param opts\n * @returns\n */\n public async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n return new Promise(async (resolove, reject) => {\n const token = await this.getToken();\n const url = `${this.baseURL}/publishers/anthropic/models/${opts.model}:streamRawPredict?alt=sse`;\n const params: claude.Request = await this.convertParams(options);\n // console.log(`->url`, url, JSON.stringify(params));\n const res = await fetchSSE(url, {\n headers: { 'content-type': 'application/json', Authorization: `Bearer ${token}` },\n body: JSON.stringify(params),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.error?.message || 'request error', res.status));\n }\n\n // only get content from node-fetch\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n let response: types.chat.ChatResponse;\n const choicesList: types.chat.Choice[] = [];\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n if (event.type === 'event') {\n const res: claude.Response = JSON.parse(event.data);\n response = this.convertResult(response, res);\n const choices = this.convertChoices(res);\n if (choices.length > 0) {\n onProgress?.(choices);\n choicesList.push(...choices);\n }\n }\n });\n body.on('readable', async () => {\n let chunk: string | Buffer;\n while ((chunk = body.read())) {\n parser.feed(chunk.toString());\n }\n });\n\n body.on('end', () => {\n response.choices = this.combineChoices(choicesList);\n resolove(response);\n });\n });\n }\n\n /**\n * https://docs.anthropic.com/claude/reference/messages-streaming\n * @returns\n */\n private async convertParams(opts: types.chat.SendOptions): Promise {\n return {\n messages: await this.corvertContents(opts),\n system: this.corvertSystem(opts),\n temperature: opts.temperature || 0.8,\n top_p: opts.top_p || 1,\n // top_k: opts.top_k || 1,\n max_tokens: opts.max_tokens || 1024,\n stop_sequences: opts.stop_sequences || [],\n stream: true,\n anthropic_version: 'vertex-2023-10-16',\n };\n }\n\n protected corvertSystem(opts: types.chat.SendOptions): string {\n return opts.messages\n .filter((item) => item.role === 'system')\n .map((item) =>\n item.parts\n .filter((p: types.chat.Part) => p.type === 'text')\n .map((p) => (p as types.chat.TextPart).text)\n .join(''),\n )\n .join('\\n');\n }\n\n protected async corvertContents(opts: types.chat.SendOptions): Promise {\n return Promise.all(\n opts.messages\n .filter((item) => item.role !== 'system')\n .map(async (item) => {\n const parts: claude.Part[] = [];\n await Promise.all(\n item.parts.map(async (part: types.chat.Part) => {\n // text\n if (part.type === 'text') {\n parts.push({ type: 'text', text: part.text });\n }\n // file, only support image, now\n if (part.type === 'file' && part?.extract) {\n parts.push({ type: 'text', text: part.extract });\n }\n if (part.type === 'file' && part.mimetype?.startsWith('image')) {\n try {\n const { mimeType: media_type, data } = await this.fetchFile((part as types.chat.FilePart).url);\n parts.push({ type: 'image', source: { type: 'base64', media_type, data } });\n } catch (err) {\n // console.warn(``);\n }\n }\n }),\n );\n return { role: item.role, content: parts } as claude.Content;\n }),\n );\n }\n\n private convertResult(response, res: claude.Response): types.chat.ChatResponse {\n try {\n if (res.type === 'message_start') {\n const { message: m } = res;\n const { input_tokens: prompt_tokens, output_tokens: completion_tokens } = m.usage;\n response = {\n id: m.id,\n model: m.model,\n choices: [],\n usage: { prompt_tokens, completion_tokens, total_tokens: prompt_tokens + completion_tokens },\n };\n }\n\n if (res.type === 'message_delta') {\n const { output_tokens } = res.usage;\n response.usage.completion_tokens = output_tokens;\n response.usage.total_tokens = response.usage.prompt_tokens + output_tokens;\n }\n } catch (err) {\n console.warn(err);\n }\n return response;\n }\n\n private convertChoices(res: claude.Response): types.chat.Choice[] {\n const choices: types.chat.Choice[] = [];\n try {\n if (res.type === 'content_block_start') {\n const { index, content_block: c } = res;\n choices.push({ index, role: 'assistant', parts: [{ type: 'text', text: c.text }], finish_reason: null });\n }\n\n if (res.type === 'content_block_delta') {\n const { index, delta: d } = res;\n choices.push({ index, role: 'assistant', parts: [{ type: 'text', text: d.text }], finish_reason: null });\n }\n\n if (res.type === 'content_block_stop') {\n const { index } = res;\n choices.push({ index, role: 'assistant', parts: [], finish_reason: 'stop' });\n }\n } catch (err) {\n console.warn(err);\n }\n return choices;\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { claude } from './types';\nimport { ChatBaseAPI } from '../base';\n\nexport class AnthropicClaudeAPI extends ChatBaseAPI {\n protected provider: string = 'anthropic';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://api.anthropic.com' }, opts);\n super(options);\n }\n\n public models(): string[] {\n return [\n 'claude-3-opus-20240229',\n 'claude-3-sonnet-20240229',\n 'claude-3-haiku-20240307',\n 'claude-2.1',\n 'claude-2.0',\n 'claude-instant-1.2',\n ];\n }\n\n /**\n * Send message\n * https://docs.anthropic.com/claude/reference/messages_post\n * @param opts\n * @returns\n */\n public async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n return new Promise(async (resolove, reject) => {\n const url = `${this.baseURL}/v1/messages`;\n const params: claude.Request = await this.convertParams(options);\n const res = await fetchSSE(url, {\n headers: {\n 'content-type': 'application/json',\n 'anthropic-version': '2023-06-01',\n 'x-api-key': this.apiKey,\n },\n body: JSON.stringify(params),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.error?.message || 'request error', res.status));\n }\n\n // only get content from node-fetch\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n let response: types.chat.ChatResponse;\n const choicesList: types.chat.Choice[] = [];\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n if (event.type === 'event') {\n const res: claude.Response = JSON.parse(event.data);\n response = this.convertResult(response, res);\n const choices = this.convertChoices(res);\n if (choices.length > 0) {\n onProgress?.(choices);\n choicesList.push(...choices);\n }\n }\n });\n body.on('readable', async () => {\n let chunk: string | Buffer;\n while ((chunk = body.read())) {\n parser.feed(chunk.toString());\n }\n });\n\n body.on('end', () => {\n response.choices = this.combineChoices(choicesList);\n resolove(response);\n });\n });\n }\n\n /**\n * https://docs.anthropic.com/claude/reference/messages-streaming\n * @returns\n */\n private async convertParams(opts: types.chat.SendOptions): Promise {\n return {\n model: opts.model || 'claude-3-haiku-20240307',\n messages: await this.corvertContents(opts),\n system: this.corvertSystem(opts),\n temperature: opts.temperature || 0.8,\n top_p: opts.top_p || 1,\n // top_k: opts.top_k || 1,\n max_tokens: opts.max_tokens || 1024,\n // metadata:\n stop_sequences: opts.stop_sequences || [],\n stream: true,\n };\n }\n\n protected corvertSystem(opts: types.chat.SendOptions): string {\n return opts.messages\n .filter((item) => item.role === 'system')\n .map((item) =>\n item.parts\n .filter((p: types.chat.Part) => p.type === 'text')\n .map((p) => (p as types.chat.TextPart).text)\n .join(''),\n )\n .join('\\n');\n }\n\n protected async corvertContents(opts: types.chat.SendOptions): Promise {\n return Promise.all(\n opts.messages\n .filter((item) => item.role !== 'system')\n .map(async (item) => {\n const parts: claude.Part[] = [];\n await Promise.all(\n item.parts.map(async (part: types.chat.Part) => {\n // text\n if (part.type === 'text') {\n parts.push({ type: 'text', text: part.text });\n }\n // file, only support image, now\n if (part.type === 'file' && part?.extract) {\n parts.push({ type: 'text', text: part.extract });\n }\n if (part.type === 'file' && part.mimetype?.startsWith('image')) {\n try {\n const { mimeType: media_type, data } = await this.fetchFile((part as types.chat.FilePart).url);\n parts.push({ type: 'image', source: { type: 'base64', media_type, data } });\n } catch (err) {\n // console.warn(``);\n }\n }\n }),\n );\n return { role: item.role, content: parts } as claude.Content;\n }),\n );\n }\n\n private convertResult(response, res: claude.Response): types.chat.ChatResponse {\n try {\n if (res.type === 'message_start') {\n const { message: m } = res;\n const { input_tokens: prompt_tokens, output_tokens: completion_tokens } = m.usage;\n response = {\n id: m.id,\n model: m.model,\n choices: [],\n usage: { prompt_tokens, completion_tokens, total_tokens: prompt_tokens + completion_tokens },\n };\n }\n\n if (res.type === 'message_delta') {\n const { output_tokens } = res.usage;\n response.usage.completion_tokens = output_tokens;\n response.usage.total_tokens = response.usage.prompt_tokens + output_tokens;\n }\n } catch (err) {\n console.warn(err);\n }\n return response;\n }\n\n private convertChoices(res: claude.Response): types.chat.Choice[] {\n const choices: types.chat.Choice[] = [];\n try {\n if (res.type === 'content_block_start') {\n const { index, content_block: c } = res;\n choices.push({ index, role: 'assistant', parts: [{ type: 'text', text: c.text }], finish_reason: null });\n }\n\n if (res.type === 'content_block_delta') {\n const { index, delta: d } = res;\n choices.push({ index, role: 'assistant', parts: [{ type: 'text', text: d.text }], finish_reason: null });\n }\n\n if (res.type === 'content_block_stop') {\n const { index } = res;\n choices.push({ index, role: 'assistant', parts: [], finish_reason: 'stop' });\n }\n } catch (err) {\n console.warn(err);\n }\n return choices;\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { ChatBaseAPI } from '../base';\nimport { requestWithAuth, toUtf8 } from './auth';\n\nexport class AnthropicBedrockAPI extends ChatBaseAPI {\n protected provider: string = 'anthropic';\n\n constructor(opts: types.chat.ChatOptions) {\n super(Object.assign({ baseURL: `https://bedrock-runtime.ap-northeast-1.amazonaws.com` }, opts));\n }\n\n public models(): string[] {\n return ['anthropic.claude-v2:1', 'anthropic.claude-v2', 'anthropic.claude-v1', 'anthropic.claude-instant-v1'];\n }\n\n /**\n * Send message\n * https://docs.anthropic.com/claude/reference/messages_post\n * @param opts\n * @returns\n */\n public async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n\n return new Promise(async (resolove, reject) => {\n const url = new URL(`${this.baseURL}/model/${opts.model}/invoke-with-response-stream`);\n // 预请求并签名\n const req = await requestWithAuth(\n { region: 'ap-northeast-1', service: 'bedrock', accessKeyId: this.apiKey, secretAccessKey: this.apiSecret },\n {\n method: 'POST',\n protocol: url.protocol,\n path: url.pathname,\n headers: {\n host: url.hostname,\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n 'User-Agent': 'AnthropicBedrock/JS 0.6.1',\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': '0.6.1',\n 'X-Stainless-OS': 'MacOS',\n 'X-Stainless-Arch': 'arm64',\n 'X-Stainless-Runtime': 'node',\n 'X-Stainless-Runtime-Version': 'v19.4.0',\n },\n body: JSON.stringify(this.convertParams(options), null, 2),\n },\n );\n // 请求\n const res = await fetchSSE(url, {\n headers: req.headers,\n body: req.body,\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: req.method,\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.message || 'request error', res.status));\n }\n\n // only get content from node-fetch\n let response: any;\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n // if (event.type === 'event') {\n // response = JSON.parse(event.data);\n // onProgress?.(response);\n // }\n console.log(`[bedrock]`, event);\n });\n\n body.on('readable', async () => {\n // 解析SSE 并进行utf8解码\n // let chunk: string | Buffer;\n // while ((chunk = body.read())) {\n // console.log(`[bedrock]`, chunk.toString());\n // // parser.feed(chunk.toString());\n // }\n\n let event;\n while (null !== (event = body.read())) {\n if (Buffer.isBuffer(event)) {\n console.log(`[bedrock]`, event.toString('utf8'));\n }\n }\n });\n\n body.on('end', () => {\n resolove(response);\n });\n });\n }\n\n /**\n * https://docs.anthropic.com/claude/reference/messages-streaming\n * @returns\n */\n private convertParams(opts: types.chat.SendOptions) {\n return {\n prompt: '\\n\\nHuman: Hey Claude! How can I recursively list all files in a directory in Rust?\\n\\nAssistant:',\n temperature: 1,\n // top_k: 250,\n // top_p: 0.999,\n max_tokens_to_sample: 500,\n anthropic_version: 'bedrock-2023-05-31',\n };\n }\n\n // 将 Gemini 的结果转换为你的数据格式\n private convertResult(result: any) {\n return {\n // 根据你的数据格式,从 Gemini 的结果中提取数据\n history: result.contents,\n // 其他数据...\n };\n }\n}\n","import { SignatureV4 } from '@smithy/signature-v4';\nimport { HttpRequest } from '@aws-sdk/protocol-http';\nimport { Sha256 } from '@aws-crypto/sha256-js';\n\nexport const toUtf8 = (input: Uint8Array): string => new TextDecoder('utf-8').decode(input);\n\nexport async function requestWithAuth(options: any, request: any): Promise {\n const { accessKeyId, secretAccessKey, region, service } = options;\n const credentials = { accessKeyId, secretAccessKey };\n // sign request\n const signed = await new SignatureV4({ region, service, sha256: Sha256, credentials }).sign(new HttpRequest(request));\n return signed as HttpRequest;\n}\n","import fetchSSE from 'node-fetch';\nimport { v4 as uuidv4 } from 'uuid';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { ChatBaseAPI } from '../base';\nimport { aliyun } from './types';\n\nexport class AliyunQwenAPI extends ChatBaseAPI {\n protected provider: string = 'google';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://dashscope.aliyuncs.com/api/v1' }, opts);\n super(options);\n }\n\n public models(): string[] {\n return ['qwen-turbo', 'qwen-plus', 'qwen-max'];\n }\n\n /**\n *\n * https://ai.google.dev/docs/gemini_api_overview?hl=zh-cn#curl_3\n * @param opts\n * @returns\n */\n public async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n return new Promise(async (resolove, reject) => {\n // 如果消息存在图片, 则自动切换到 multimodal\n const isMulti =\n opts.model !== 'qwen-turbo' &&\n opts.messages.some((item) => item.parts.some((part) => ['image'].includes(part.type)));\n const model = isMulti ? opts.model.replace('-', '-vl-') : opts.model;\n const url = `${this.baseURL}/services/aigc/${isMulti ? 'multimodal' : 'text'}-generation/generation`;\n const params: aliyun.Request = await this.convertParams(model, options);\n // console.log(`[fetch]params`, JSON.stringify(params, null, 2));\n\n const res = await fetchSSE(url, {\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`,\n 'X-DashScope-SSE': 'enable',\n },\n body: JSON.stringify(params),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.message || 'request error', res.status));\n }\n\n // only get content from node-fetch\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n // streaming\n const choicesList: types.chat.Choice[] = [];\n const usage: types.chat.Usage = { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n if (event.type === 'event') {\n const res = JSON.parse(event.data);\n // console.log(`->`, JSON.stringify(res));\n // success\n if (res?.output) {\n const choices = this.convertChoices(res.output.choices);\n onProgress?.(choices);\n\n if (res.usage) {\n const u = res.usage;\n Object.assign(usage, {\n prompt_tokens: u.input_tokens,\n completion_tokens: u.output_tokens,\n total_tokens: u.total_tokens ? u.total_tokens : u.input_tokens + u.output_tokens,\n });\n }\n choicesList.push(...choices);\n }\n\n // error\n if (res?.code) {\n reject(new types.chat.ChatError(res?.message, 500));\n }\n }\n });\n body.on('readable', async () => {\n let chunk: string | Buffer;\n while ((chunk = body.read())) {\n parser.feed(chunk.toString());\n }\n });\n\n body.on('end', () => {\n const choices: types.chat.Choice[] = this.combineChoices(choicesList);\n resolove({ id: uuidv4(), model: opts.model, choices, usage });\n });\n });\n }\n\n /**\n * Aliyun Qwen API\n * https://help.aliyun.com/zh/dashscope/developer-reference/api-details\n * @returns\n */\n private async convertParams(model, opts: types.chat.SendOptions): Promise {\n const params = {\n model: model || 'qwen-turbo',\n input: {\n messages: await this.corvertContents(opts),\n },\n parameters: {\n temperature: (opts.temperature || 0.85) * 2 - 0.1,\n top_p: opts.top_p || 0.8,\n // top_k: Math.round((opts.top_k || 0.025) * 100) || undefined,\n max_tokens: opts.max_tokens || 1500,\n incremental_output: true,\n enable_search: true,\n },\n };\n // fix different model\n if (model.indexOf('vl') === -1) {\n Object.assign(params.parameters, {\n temperature: opts.temperature || 1,\n max_tokens: opts.max_tokens || 1500,\n enable_search: true,\n stop: opts.stop_sequences || undefined,\n result_format: 'message',\n });\n }\n return params;\n }\n\n private async corvertContents(opts: types.chat.SendOptions): Promise {\n return Promise.all(\n opts.messages.map(async (item) => {\n const parts: aliyun.Part[] = [];\n await Promise.all(\n item.parts.map(async (part: types.chat.Part) => {\n // text\n if (part.type === 'text') {\n parts.push({ text: part.text });\n }\n // file: docs\n if (part.type === 'file' && part?.extract) {\n parts.push({ text: part.extract });\n }\n\n // file, only support image, now\n if (part.type === 'file' && part.mimetype?.startsWith('image')) {\n parts.push({ image: (part as types.chat.FilePart).url });\n }\n }),\n );\n // fix different model\n let content: string | aliyun.Part[] = parts;\n if (!['qwen-vl-plus'].includes(opts.model)) {\n content = parts\n .map((item: any) => {\n return 'text' in item ? item.text : '';\n })\n .join('\\n');\n }\n return { role: item.role, content: parts } as aliyun.Content;\n }),\n );\n }\n\n protected convertChoices(candidates: aliyun.Choice[]): types.chat.Choice[] {\n const choices: types.chat.Choice[] = [];\n try {\n candidates.map(({ message, finish_reason }: aliyun.Choice) => {\n const parts: types.chat.Part[] = [];\n // for text\n if (typeof message.content === 'string') {\n parts.push({ type: 'text', text: message.content });\n }\n // for multimodal\n if (typeof message.content === 'object' && message.content instanceof Array) {\n message.content.map((part: any) => {\n if ('text' in part) {\n parts.push({ type: 'text', text: part.text });\n }\n });\n }\n choices.push({ index: 0, role: 'assistant', parts, finish_reason: 'stop' });\n });\n } catch (err) {\n console.warn(err);\n }\n return choices;\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { ChatBaseAPI } from '../base';\n\nexport class AliyunWanxAPI extends ChatBaseAPI {\n protected provider: string = 'google';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://dashscope.aliyuncs.com/api/v1' }, opts);\n super(options);\n }\n\n public models(): string[] {\n return ['wanx-v1'];\n }\n\n /**\n * https://help.aliyun.com/zh/dashscope/developer-reference/api-details-9\n * @param opts\n * @returns\n */\n public async sendMessage(opts: types.image.SendOptions) {\n return new Promise(async (resolove, reject) => {\n const url = `${this.baseURL}/services/aigc/text2image/image-synthesis`;\n const res = await fetchSSE(url, {\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`,\n 'X-DashScope-Async': 'enable',\n },\n body: JSON.stringify(this.convertParams(opts)),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.message || 'request error', res.status));\n }\n\n try {\n const { output } = await res.json();\n if (output.task_status === 'FAILED') {\n reject(new types.chat.ChatError(output.message, res.status));\n }\n resolove(output);\n } catch (err) {\n reject(new types.chat.ChatError('request error', res.status));\n }\n });\n }\n\n public async getTaskResult(task_id: string) {\n const url = `${this.baseURL}/tasks/${task_id}`;\n return new Promise(async (resolove, reject) => {\n const res = await fetchSSE(url, {\n headers: { Authorization: `Bearer ${this.apiKey}` },\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n });\n\n try {\n const { output } = await res.json();\n if (output.task_status === 'FAILED') {\n reject(new types.chat.ChatError(output.message, res.status));\n }\n\n resolove(output);\n } catch (err) {\n reject(new types.chat.ChatError('request error', res.status));\n }\n });\n }\n\n /**\n * https://help.aliyun.com/zh/dashscope/developer-reference/api-details-9\n * @returns\n */\n private convertParams(opts: types.image.SendOptions) {\n return {\n model: opts.model || 'wanx-v1',\n input: {\n prompt: opts.prompt,\n },\n parameters: {\n style: '',\n size: '1024*1024',\n n: 4,\n seed: 42,\n },\n };\n }\n\n // 将 Gemini 的结果转换为你的数据格式\n private convertResult(result: any) {\n return {\n // 根据你的数据格式,从 Gemini 的结果中提取数据\n history: result.contents,\n // 其他数据...\n };\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { v4 as uuidv4 } from 'uuid';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { ChatBaseAPI } from '../base';\nimport { kimi } from './types';\n\nexport class MoonshotKimiAPI extends ChatBaseAPI {\n protected provider: string = 'moonshot';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://api.moonshot.cn/v1' }, opts);\n super(options);\n }\n\n public models(): string[] {\n return ['moonshot-v1-8k', 'moonshot-v1-32k', 'moonshot-v1-128k'];\n }\n\n async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n\n return new Promise(async (resolove, reject) => {\n const url = `${this.baseURL}/chat/completions`;\n const params: kimi.Request = await this.convertParams(options);\n // console.log(`[fetch]params`, JSON.stringify(params, null, 2));\n\n const res = await fetchSSE(url, {\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${this.apiKey}` },\n body: JSON.stringify(params),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.error?.message || 'request error', res.status));\n return;\n }\n\n // not stream\n let usage = { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };\n if (params.stream === false) {\n const result = await res.json();\n const choices = this.convertChoices(result.choices);\n resolove({ id: uuidv4(), model: opts.model, choices, usage: result.usage });\n } else {\n // streaming\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n const choicesList: types.chat.Choice[] = [];\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n if (event.type === 'event') {\n if (event.data !== '[DONE]') {\n try {\n const result = JSON.parse(event.data);\n const choices = this.convertChoices(result.choices);\n usage = this.convertChoicesUsage(result.choices, usage);\n onProgress?.(choices);\n choicesList.push(...choices);\n } catch (e) {\n // ignore\n }\n }\n }\n });\n body.on('readable', async () => {\n let chunk: string | Buffer;\n while ((chunk = body.read())) {\n parser.feed(chunk.toString());\n }\n });\n\n // console.log(`->`, choicesList);\n body.on('end', async () => {\n const choices: types.chat.Choice[] = this.combineChoices(choicesList);\n resolove({ id: uuidv4(), model: opts.model, choices, usage });\n });\n }\n });\n }\n\n /**\n * 转换为 Gemini 要求的请求参数\n * https://platform.openai.com/docs/api-reference/chat/create\n * @returns\n */\n private async convertParams(opts: types.chat.SendOptions): Promise {\n const params: kimi.Request = {\n model: opts.model || 'moonshot-v1-8k',\n messages: await this.corvertContents(opts),\n temperature: opts?.temperature || 0.9,\n top_p: opts?.top_p || 1.0,\n // frequency_penalty: 0,\n // presence_penalty: 0,\n max_tokens: opts?.max_tokens || 1000,\n n: opts.n || 1,\n stop: opts?.stop_sequences || undefined,\n stream: opts?.stream != undefined ? opts.stream : true,\n };\n // tools\n if (opts.tools && opts.tools.length > 0) {\n Object.assign(params, { tools: opts.tools, stream: false });\n }\n return params;\n }\n\n private async corvertContents(opts: types.chat.SendOptions): Promise {\n return Promise.all(\n opts.messages.map(async (item) => {\n const parts: string[] = [];\n await Promise.all(\n item.parts.map(async (part: types.chat.Part) => {\n // text\n if (part.type === 'text') {\n parts.push(part.text);\n }\n // file, only support image, now\n if (part.type === 'file' && part?.extract) {\n parts.push(part.extract);\n }\n }),\n );\n\n return { role: item.role, content: parts.join('\\n') } as kimi.Message;\n }),\n );\n }\n\n protected convertChoices(candidates: kimi.Choice[]): types.chat.Choice[] {\n const choices: types.chat.Choice[] = [];\n try {\n candidates.map(({ index, delta, message, finish_reason }: kimi.Choice) => {\n const parts: types.chat.Part[] = [];\n let { content } = message || delta;\n if (delta) {\n content = delta.content;\n }\n if (content) {\n parts.push({ type: 'text', text: content });\n }\n\n choices.push({ index, role: 'assistant', parts, finish_reason });\n });\n } catch (err) {\n console.warn(err);\n }\n return choices;\n }\n\n protected convertChoicesUsage(candidates: kimi.Choice[], initial: types.chat.Usage): types.chat.Usage {\n candidates.map(({ usage }: kimi.Choice) => {\n if (usage) {\n initial.prompt_tokens += usage.prompt_tokens;\n initial.completion_tokens += usage.completion_tokens;\n initial.total_tokens += usage.total_tokens;\n }\n });\n return initial;\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { v4 as uuidv4 } from 'uuid';\nimport * as tencentcloud from 'tencentcloud-sdk-nodejs';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { ChatBaseAPI } from '../base';\nimport { hunyuan } from './types';\n\nexport class QcloudHunyuanAPI extends ChatBaseAPI {\n protected provider: string = 'tencent';\n private client: any;\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://hunyuan.tencentcloudapi.com' }, opts);\n super(options);\n\n // init tencentcloud client\n this.client = new tencentcloud.hunyuan.v20230901.Client({\n credential: { secretId: this.apiKey, secretKey: this.apiSecret },\n profile: {\n signMethod: 'TC3-HMAC-SHA256',\n httpProfile: { reqMethod: 'POST', reqTimeout: 30, endpoint: 'hunyuan.tencentcloudapi.com' },\n },\n });\n }\n\n public models(): string[] {\n return ['hunyuan-lite', 'hunyuan-standard', 'hunyuan-pro'];\n }\n\n /**\n * tencent hunyuan\n * https://cloud.tencent.com/document/api/1729/101836\n * @param opts\n * @returns\n */\n public async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n return new Promise(async (resolove, reject) => {\n if (!this.models().includes(opts.model)) {\n reject(new Error(`model ${opts.model} is not supported`));\n }\n\n const params = await this.convertParams(options);\n const response = await this.client.ChatCompletions(params);\n\n // streaming\n let id = uuidv4();\n const choicesList: types.chat.Choice[] = [];\n const usage: types.chat.Usage = { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };\n for await (let message of response) {\n const res = JSON.parse(message.data);\n id = res.Id;\n const choices = this.convertChoices(res.Choices);\n if (res.Usage) {\n Object.assign(usage, {\n prompt_tokens: res.Usage.PromptTokens,\n completion_tokens: res.Usage.CompletionTokens,\n total_tokens: res.Usage.TotalTokens,\n });\n }\n onProgress?.(choices);\n choicesList.push(...choices);\n }\n\n // finished\n const choices: types.chat.Choice[] = this.combineChoices(choicesList);\n resolove({ id, model: opts.model, choices, usage });\n });\n }\n\n /**\n * 转换请求参数\n * @returns\n */\n private async convertParams(opts: types.chat.SendOptions) {\n return {\n Model: opts.model,\n TopP: opts.top_p || 1.0,\n Temperature: opts.temperature || 1.0,\n Messages: await this.corvertContents(opts),\n Stream: true,\n };\n }\n\n private async corvertContents(opts: types.chat.SendOptions): Promise {\n return Promise.all(\n opts.messages.map(async (item) => {\n const parts: string[] = [];\n await Promise.all(\n item.parts.map(async (part: types.chat.Part) => {\n // text\n if (part.type === 'text') {\n parts.push(part.text);\n }\n // file, only support image, now\n if (part.type === 'file' && part?.extract) {\n parts.push(part.extract);\n }\n }),\n );\n return { Role: item.role, Content: parts.join('/n') } as hunyuan.Content;\n }),\n );\n }\n\n protected convertChoices(candidates: hunyuan.Choice[]): types.chat.Choice[] {\n const choices: types.chat.Choice[] = [];\n try {\n candidates.map(({ Delta, FinishReason }: hunyuan.Choice, index) => {\n const parts: types.chat.Part[] = [];\n parts.push({ type: 'text', text: Delta.Content });\n choices.push({ index, role: 'assistant', parts, finish_reason: 'stop' });\n });\n } catch (err) {\n console.warn(err);\n }\n return choices;\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { v4 as uuidv4 } from 'uuid';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { ChatBaseAPI } from '../base';\nimport { deepseek } from './types';\n\nexport class DeepSeekAPI extends ChatBaseAPI {\n protected provider: string = 'moonshot';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://api.deepseek.com' }, opts);\n super(options);\n }\n\n public models(): string[] {\n return ['deepseek-chat'];\n }\n\n async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n\n return new Promise(async (resolove, reject) => {\n const url = `${this.baseURL}/chat/completions`;\n const params: deepseek.Request = await this.convertParams(options);\n // console.log(`[fetch]params`, JSON.stringify(params, null, 2));\n\n const res = await fetchSSE(url, {\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${this.apiKey}` },\n body: JSON.stringify(params),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.error?.message || 'request error', res.status));\n }\n\n // not stream\n if (params.stream === false) {\n const result = await res.json();\n const choices = this.convertChoices(result.choices);\n const usage = result?.usage;\n resolove({ id: uuidv4(), model: opts.model, choices, usage });\n } else {\n // streaming\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n let result;\n const choicesList: types.chat.Choice[] = [];\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n if (event.type === 'event') {\n if (event.data !== '[DONE]') {\n try {\n result = JSON.parse(event.data);\n const choices = this.convertChoices(result.choices);\n onProgress?.(choices);\n choicesList.push(...choices);\n } catch (e) {\n // ignore\n }\n }\n }\n });\n body.on('readable', async () => {\n let chunk: string | Buffer;\n while ((chunk = body.read())) {\n parser.feed(chunk.toString());\n }\n });\n\n body.on('end', async () => {\n const choices: types.chat.Choice[] = this.combineChoices(choicesList);\n resolove({ id: uuidv4(), model: opts.model, choices, usage: result.usage });\n });\n }\n });\n }\n\n /**\n * https://platform.deepseek.com/api-docs/zh-cn/api/create-chat-completion/index.html\n * @returns\n */\n private async convertParams(opts: types.chat.SendOptions): Promise {\n const params: deepseek.Request = {\n model: opts.model || 'moonshot-v1-8k',\n messages: await this.corvertContents(opts),\n temperature: opts?.temperature || 0.9,\n top_p: opts?.top_p || 1.0,\n // frequency_penalty: 0,\n // presence_penalty: 0,\n max_tokens: opts?.max_tokens || 1000,\n // n: opts.n || 1,\n stop: opts?.stop_sequences || undefined,\n stream: true,\n };\n // tools\n if (opts.tools && opts.tools.length > 0) {\n Object.assign(params, { tools: opts.tools, stream: false });\n }\n return params;\n }\n\n private async corvertContents(opts: types.chat.SendOptions): Promise {\n return Promise.all(\n opts.messages.map(async (item) => {\n const parts: string[] = [];\n await Promise.all(\n item.parts.map(async (part: types.chat.Part) => {\n // text\n if (part.type === 'text') {\n parts.push(part.text);\n }\n // file, only support image, now\n if (part.type === 'file' && part?.extract) {\n parts.push(part.extract);\n }\n }),\n );\n\n return { role: item.role, content: parts.join('\\n') } as deepseek.Message;\n }),\n );\n }\n\n protected convertChoices(candidates: deepseek.Choice[]): types.chat.Choice[] {\n const choices: types.chat.Choice[] = [];\n try {\n candidates.map(({ index, delta, message, finish_reason }: deepseek.Choice) => {\n const parts: types.chat.Part[] = [];\n let { content } = message || delta;\n if (delta) {\n content = delta.content;\n }\n if (content) {\n parts.push({ type: 'text', text: content });\n }\n\n choices.push({ index, role: 'assistant', parts, finish_reason });\n });\n } catch (err) {\n console.warn(err);\n }\n return choices;\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { v4 as uuidv4 } from 'uuid';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { ChatBaseAPI } from '../base';\nimport { groq } from './types';\n\nexport class GroqCompletionsAPI extends ChatBaseAPI {\n protected provider: string = 'groq';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://api.groq.com/openai/v1' }, opts);\n super(options);\n }\n\n public models(): string[] {\n return ['llama3-8b-8192', 'llama3-70b-8192', 'mixtral-8x7b-32768', 'gemma-7b-it'];\n }\n\n async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n\n return new Promise(async (resolove, reject) => {\n const url = `${this.baseURL}/chat/completions`;\n const params: groq.Request = await this.convertParams(options);\n // console.log(`[fetch]params`, JSON.stringify(params, null, 2));\n const res = await fetchSSE(url, {\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${this.apiKey}` },\n body: JSON.stringify(params),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.error?.message || 'request error', res.status));\n }\n\n // not stream\n if (params.stream === false) {\n const result = await res.json();\n const choices = this.convertChoices(result.choices);\n const usage = result?.usage;\n resolove({ id: uuidv4(), model: opts.model, choices, usage });\n } else {\n // streaming\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n let result;\n const choicesList: types.chat.Choice[] = [];\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n if (event.type === 'event') {\n if (event.data !== '[DONE]') {\n try {\n result = JSON.parse(event.data);\n const choices = this.convertChoices(result.choices);\n onProgress?.(choices);\n choicesList.push(...choices);\n } catch (e) {\n // ignore\n }\n }\n }\n });\n body.on('readable', async () => {\n let chunk: string | Buffer;\n while ((chunk = body.read())) {\n parser.feed(chunk.toString());\n }\n });\n\n body.on('end', async () => {\n const choices: types.chat.Choice[] = this.combineChoices(choicesList);\n const { prompt_tokens, completion_tokens, total_tokens } = result?.x_groq?.usage;\n const usage = { prompt_tokens, completion_tokens, total_tokens };\n resolove({ id: uuidv4(), model: opts.model, choices, usage });\n });\n }\n });\n }\n\n /**\n * 转换为 Gemini 要求的请求参数\n * https://platform.groq.com/docs/api-reference/chat/create\n * @returns\n */\n private async convertParams(opts: types.chat.SendOptions): Promise {\n const params: groq.Request = {\n model: opts.model || 'gpt-3.5-turbo-0125',\n messages: await this.corvertContents(opts),\n temperature: opts?.temperature || 0.9,\n top_p: opts?.top_p || 1,\n // frequency_penalty: 0,\n // presence_penalty: 0,\n max_tokens: opts?.max_tokens || 1000,\n n: opts.n || 1,\n stop: opts?.stop_sequences || undefined,\n stream: true,\n };\n // tools\n if (opts.tools && opts.tools.length > 0) {\n Object.assign(params, { tools: opts.tools, stream: false });\n }\n return params;\n }\n\n private async corvertContents(opts: types.chat.SendOptions): Promise {\n return Promise.all(\n opts.messages.map(async (item) => {\n const parts: groq.Part[] = [];\n const tool_calls: groq.ToolCallPart[] = [];\n await Promise.all(\n item.parts.map(async (part: types.chat.Part) => {\n // text\n if (part.type === 'text') {\n parts.push({ type: 'text', text: part.text });\n }\n // file: docs\n if (part.type === 'file' && part?.extract) {\n parts.push({ type: 'text', text: part.extract });\n }\n\n // file, only support image, now\n if (part.type === 'file' && part.mimetype?.startsWith('image')) {\n parts.push({ type: 'image_url', image_url: { url: (part as types.chat.FilePart).url } });\n }\n // tools\n if (part.type === 'function_call' && part.id) {\n const { name, args } = part.function_call;\n tool_calls.push({ id: part.id, type: 'function', function: { name, arguments: args } });\n }\n }),\n );\n if (item.role === 'system') {\n return { role: 'system', content: this.filterTextPartsToString(parts) } as groq.Message;\n }\n if (item.role === 'assistant') {\n return {\n role: 'assistant',\n content: parts,\n tool_calls: tool_calls.length > 0 ? tool_calls : undefined,\n } as groq.Message;\n }\n return { role: 'user', content: parts } as groq.Message;\n }),\n );\n }\n\n private filterTextPartsToString(parts: groq.Part[]): string {\n return parts\n .filter((p) => p.type === 'text')\n .map((p) => (p as groq.TextPart).text)\n .join('');\n }\n\n protected convertChoices(candidates: groq.Choice[]): types.chat.Choice[] {\n const choices: types.chat.Choice[] = [];\n try {\n candidates.map(({ index, delta, message, finish_reason }: groq.Choice) => {\n const parts: types.chat.Part[] = [];\n let { content, tool_calls } = message || delta;\n if (delta) {\n content = delta.content;\n tool_calls = delta.tool_calls;\n }\n if (content) {\n parts.push({ type: 'text', text: content });\n }\n if (tool_calls) {\n tool_calls.map((call: any) => {\n const { name, arguments: args } = call.function;\n parts.push({ type: 'function_call', function_call: { name, args }, id: call.id });\n });\n }\n\n choices.push({ index, role: 'assistant', parts, finish_reason });\n });\n } catch (err) {\n console.warn(err);\n }\n return choices;\n }\n}\n","import { OpenAICompletionsAPI, OpenAIAssistantsAPI, GoogleClaudeAPI } from '@/provider';\nimport { MoonshotKimiAPI, QcloudHunyuanAPI, DeepSeekAPI } from '@/provider';\nimport { GoogleVertexAPI, GoogleGeminiAPI } from '@/provider';\nimport { AnthropicClaudeAPI, AnthropicBedrockAPI } from '@/provider';\nimport { AliyunQwenAPI, AliyunWanxAPI } from '@/provider';\nimport { ChatBaseAPI } from '@/provider/base';\nimport { GroqCompletionsAPI } from '@/provider/groq';\nimport * as types from '@/types';\n\nexport class ChatAPI {\n private provider: ChatBaseAPI | null = null;\n\n constructor(provider: string, opts: types.chat.ChatOptions) {\n switch (provider) {\n case types.Provider.GOOGLE_VERTEX:\n this.provider = new GoogleVertexAPI(opts);\n break;\n case types.Provider.GOOGLE_GEMINI:\n this.provider = new GoogleGeminiAPI(opts);\n break;\n case types.Provider.GOOGLE_CLAUDE:\n this.provider = new GoogleClaudeAPI(opts);\n break;\n case types.Provider.OPENAI_COMPLETIONS:\n this.provider = new OpenAICompletionsAPI(opts);\n break;\n case types.Provider.OPENAI_ASSISTANTS:\n this.provider = new OpenAIAssistantsAPI(opts);\n break;\n case types.Provider.ALIYUN_QWEN:\n this.provider = new AliyunQwenAPI(opts);\n break;\n case types.Provider.ALIYUN_WANX:\n this.provider = new AliyunWanxAPI(opts);\n break;\n case types.Provider.ANTHROPIC_CLAUDE:\n this.provider = new AnthropicClaudeAPI(opts);\n break;\n case types.Provider.ANTHROPIC_BEDROCK:\n this.provider = new AnthropicBedrockAPI(opts);\n break;\n case types.Provider.QCLOUD_HUNYUAN:\n this.provider = new QcloudHunyuanAPI(opts);\n break;\n case types.Provider.MOONSHOT_KIMI:\n this.provider = new MoonshotKimiAPI(opts);\n break;\n case types.Provider.DEEPSEEK:\n this.provider = new DeepSeekAPI(opts);\n break;\n case types.Provider.GROQ:\n this.provider = new GroqCompletionsAPI(opts);\n break;\n default:\n throw new Error(`Unsupported supplier: ${provider}`);\n }\n }\n\n public async sendMessage(opts: types.chat.SendOptions | types.image.SendOptions) {\n if (!this.provider) {\n throw new Error('Provider is not initialized');\n }\n return await this.provider.sendMessage(opts);\n }\n}\n","import { AliyunWanxAPI } from '@/provider';\nimport { ChatBaseAPI } from '@/provider/base';\n\nimport * as types from '@/types';\n\nexport class ImageAPI {\n private provider: ChatBaseAPI | null = null;\n\n constructor(provider: string, opts: types.chat.ChatOptions) {\n switch (provider) {\n case types.Provider.ALIYUN_WANX:\n this.provider = new AliyunWanxAPI(opts);\n break;\n default:\n throw new Error(`Unsupported supplier: ${provider}`);\n }\n }\n\n public async sendMessage(opts: types.image.SendOptions) {\n if (!this.provider) {\n throw new Error('Provider is not initialized');\n }\n return await this.provider.sendMessage(opts);\n }\n\n public async getTaskResult(task_id: string) {\n if (!this.provider) {\n throw new Error('Provider is not initialized');\n }\n return await this.provider.getTaskResult(task_id);\n }\n}\n"],"mappings":";AAAO,IAAK,WAAL,kBAAKA,cAAL;AACL,EAAAA,UAAA,mBAAgB;AAChB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,iBAAiB,IAAI;AACzC;AAAA,MACF;AACE,aAAK,WAAW,IAAI,gBAAgB,IAAI;AACxC;AAAA,MACF;AACE,aAAK,WAAW,IAAI,YAAY,IAAI;AACpC;AAAA,MACF;AACE,aAAK,WAAW,IAAI,mBAAmB,IAAI;AAC3C;AAAA,MACF;AACE,cAAM,IAAI,MAAM,yBAAyB,QAAQ,EAAE;AAAA,IACvD;AAAA,EACF;AAAA,EAEA,MAAa,YAAY,MAAwD;AAC/E,QAAI,CAAC,KAAK,UAAU;AAClB,YAAM,IAAI,MAAM,6BAA6B;AAAA,IAC/C;AACA,WAAO,MAAM,KAAK,SAAS,YAAY,IAAI;AAAA,EAC7C;AACF;;;AC3DO,IAAM,WAAN,MAAe;AAAA,EAGpB,YAAY,UAAkB,MAA8B;AAF5D,SAAQ,WAA+B;AAGrC,YAAQ,UAAU;AAAA,MAChB;AACE,aAAK,WAAW,IAAI,cAAc,IAAI;AACtC;AAAA,MACF;AACE,cAAM,IAAI,MAAM,yBAAyB,QAAQ,EAAE;AAAA,IACvD;AAAA,EACF;AAAA,EAEA,MAAa,YAAY,MAA+B;AACtD,QAAI,CAAC,KAAK,UAAU;AAClB,YAAM,IAAI,MAAM,6BAA6B;AAAA,IAC/C;AACA,WAAO,MAAM,KAAK,SAAS,YAAY,IAAI;AAAA,EAC7C;AAAA,EAEA,MAAa,cAAc,SAAiB;AAC1C,QAAI,CAAC,KAAK,UAAU;AAClB,YAAM,IAAI,MAAM,6BAA6B;AAAA,IAC/C;AACA,WAAO,MAAM,KAAK,SAAS,cAAc,OAAO;AAAA,EAClD;AACF;","names":["Provider","HttpsProxyAgent","chat","HttpsProxyAgent","fetchSSE","uuidv4","HttpsProxyAgent","createParser","fetchSSE","uuidv4","HttpsProxyAgent","createParser","fetchSSE","HttpsProxyAgent","createParser","res","uuidv4","fetchSSE","HttpsProxyAgent","createParser","res","uuidv4","fetchSSE","GoogleAuth","HttpsProxyAgent","createParser","GoogleAuth","fetchSSE","HttpsProxyAgent","createParser","res","fetchSSE","HttpsProxyAgent","createParser","fetchSSE","HttpsProxyAgent","createParser","res","fetchSSE","HttpsProxyAgent","createParser","fetchSSE","HttpsProxyAgent","createParser","fetchSSE","uuidv4","HttpsProxyAgent","createParser","fetchSSE","HttpsProxyAgent","createParser","res","uuidv4","item","fetchSSE","HttpsProxyAgent","fetchSSE","HttpsProxyAgent","fetchSSE","uuidv4","HttpsProxyAgent","createParser","fetchSSE","HttpsProxyAgent","uuidv4","createParser","uuidv4","uuidv4","choices","fetchSSE","uuidv4","HttpsProxyAgent","createParser","fetchSSE","HttpsProxyAgent","uuidv4","createParser","fetchSSE","uuidv4","HttpsProxyAgent","createParser","fetchSSE","HttpsProxyAgent","uuidv4","createParser"]} \ No newline at end of file +{"version":3,"sources":["../src/types/provider.ts","../src/provider/openai/completions.ts","../src/types/chat.ts","../src/provider/base.ts","../src/provider/openai/assistants.ts","../src/provider/google/vertex.ts","../src/provider/google/gemini.ts","../src/provider/google/claude.ts","../src/provider/anthropic/claude.ts","../src/provider/anthropic/bedrock.ts","../src/provider/anthropic/auth.ts","../src/provider/aliyun/qwen.ts","../src/provider/aliyun/wanx.ts","../src/provider/moonshot/kimi.ts","../src/provider/qcloud/hunyuan.ts","../src/provider/deepseek/deepseek.ts","../src/provider/groq/completions.ts","../src/api/chat.ts","../src/api/image.ts"],"sourcesContent":["export enum Provider {\n GOOGLE_GEMINI = 'google-gemini',\n GOOGLE_VERTEX = 'google-vertex',\n GOOGLE_CLAUDE = 'google-claude',\n OPENAI_COMPLETIONS = 'openai-completion',\n OPENAI_ASSISTANTS = 'openai-assistant',\n ANTHROPIC_CLAUDE = 'anthropic-claude',\n ANTHROPIC_BEDROCK = 'anthropic-bedrock',\n ALIYUN_QWEN = 'aliyun-qwen',\n ALIYUN_WANX = 'aliyun-wanx',\n QCLOUD_HUNYUAN = 'qcloud-hunyuan',\n MOONSHOT_KIMI = 'moonshot-kimi',\n DEEPSEEK = 'deepseek',\n GROQ = 'groq',\n}\n","import fetchSSE from 'node-fetch';\nimport { v4 as uuidv4 } from 'uuid';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { ChatBaseAPI } from '../base';\nimport { openai } from './types';\n\nexport class OpenAICompletionsAPI extends ChatBaseAPI {\n protected provider: string = 'openai';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://api.openai.com/v1' }, opts);\n super(options);\n }\n\n public models(): string[] {\n return [\n 'gpt-3.5-turbo',\n 'gpt-3.5-turbo-0125',\n 'gpt-3.5-turbo-16k',\n 'gpt-3.5-turbo-instruct',\n 'gpt-4',\n 'gpt-4-0125-preview',\n 'gpt-4-turbo-preview',\n 'gpt-4-32k',\n ];\n }\n\n async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n\n return new Promise(async (resolove, reject) => {\n const url = `${this.baseURL}/chat/completions`;\n const params: openai.Request = await this.convertParams(options);\n // console.log(`[fetch]params`, JSON.stringify(params, null, 2));\n const res = await fetchSSE(url, {\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${this.apiKey}` },\n body: JSON.stringify(params),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.error?.message || 'request error', res.status));\n }\n\n // not stream\n if (params.stream === false) {\n const result = await res.json();\n const choices = this.convertChoices(result.choices);\n const usage = result?.usage;\n resolove({ id: uuidv4(), model: opts.model, choices, usage });\n } else {\n // streaming\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n const choicesList: types.chat.Choice[] = [];\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n if (event.type === 'event') {\n if (event.data !== '[DONE]') {\n try {\n const result = JSON.parse(event.data);\n const choices = this.convertChoices(result.choices);\n onProgress?.(choices);\n choicesList.push(...choices);\n } catch (e) {\n // ignore\n }\n }\n }\n });\n body.on('readable', async () => {\n let chunk: string | Buffer;\n while ((chunk = body.read())) {\n parser.feed(chunk.toString());\n }\n });\n\n body.on('end', async () => {\n const choices: types.chat.Choice[] = this.combineChoices(choicesList);\n const usage = this.caclulateUsage(opts.messages, choices);\n resolove({ id: uuidv4(), model: opts.model, choices, usage });\n });\n }\n });\n }\n\n /**\n * 转换为 Gemini 要求的请求参数\n * https://platform.openai.com/docs/api-reference/chat/create\n * @returns\n */\n private async convertParams(opts: types.chat.SendOptions): Promise {\n const params: openai.Request = {\n model: opts.model || 'gpt-3.5-turbo-0125',\n messages: await this.corvertContents(opts),\n temperature: opts?.temperature || 0.9,\n top_p: opts?.top_p || 1,\n // frequency_penalty: 0,\n // presence_penalty: 0,\n max_tokens: opts?.max_tokens || 1000,\n n: opts.n || 1,\n stop: opts?.stop_sequences || undefined,\n stream: true,\n };\n // tools\n if (opts.tools && opts.tools.length > 0) {\n Object.assign(params, { tools: opts.tools, stream: false });\n }\n return params;\n }\n\n private async corvertContents(opts: types.chat.SendOptions): Promise {\n return Promise.all(\n opts.messages.map(async (item) => {\n const parts: openai.Part[] = [];\n const tool_calls: openai.ToolCallPart[] = [];\n await Promise.all(\n item.parts.map(async (part: types.chat.Part) => {\n // text\n if (part.type === 'text') {\n parts.push({ type: 'text', text: part.text });\n }\n // file: docs\n if (part.type === 'file' && part?.extract) {\n parts.push({ type: 'text', text: part.extract });\n }\n // file, only support image, now\n if (part.type === 'file' && part.mimetype?.startsWith('image')) {\n // TODO: fetch 下载图片并转化buffer为base64\n // parts.push({ type: 'image_url', image_url: (part as types.chat.FilePart).url });\n parts.push({ type: 'image_url', image_url: { url: (part as types.chat.FilePart).url } });\n }\n // tools\n if (part.type === 'function_call' && part.id) {\n const { name, args } = part.function_call;\n tool_calls.push({ id: part.id, type: 'function', function: { name, arguments: args } });\n }\n }),\n );\n if (item.role === 'system') {\n return { role: 'system', content: this.filterTextPartsToString(parts) } as openai.Message;\n }\n if (item.role === 'assistant') {\n return {\n role: 'assistant',\n content: parts,\n tool_calls: tool_calls.length > 0 ? tool_calls : undefined,\n } as openai.Message;\n }\n return { role: 'user', content: parts } as openai.Message;\n }),\n );\n }\n\n private filterTextPartsToString(parts: openai.Part[]): string {\n return parts\n .filter((p) => p.type === 'text')\n .map((p) => (p as openai.TextPart).text)\n .join('');\n }\n\n protected convertChoices(candidates: openai.Choice[]): types.chat.Choice[] {\n const choices: types.chat.Choice[] = [];\n try {\n candidates.map(({ index, delta, message, finish_reason }: openai.Choice) => {\n const parts: types.chat.Part[] = [];\n let { content, tool_calls } = message || delta;\n if (delta) {\n content = delta.content;\n tool_calls = delta.tool_calls;\n }\n if (content) {\n parts.push({ type: 'text', text: content });\n }\n if (tool_calls) {\n tool_calls.map((call: any) => {\n const { name, arguments: args } = call.function;\n parts.push({ type: 'function_call', function_call: { name, args }, id: call.id });\n });\n }\n\n choices.push({ index, role: 'assistant', parts, finish_reason });\n });\n } catch (err) {\n console.warn(err);\n }\n return choices;\n }\n}\n","/**\n * Chat\n */\nexport namespace chat {\n export class ChatError extends Error {\n name: 'ChatError';\n code: number;\n constructor(message: string, code: number) {\n super(message);\n this.code = code;\n }\n }\n\n export type ChatOptions = {\n agent?: string;\n baseURL?: string;\n apiKey: string;\n apiSecret?: string;\n timeout?: number;\n };\n\n /**\n * Request\n */\n export type SendOptions = {\n model: string;\n messages: Message[];\n tools?: Tools[];\n temperature?: number;\n top_p?: number;\n top_k?: number;\n n?: number;\n max_tokens?: number;\n stop_sequences?: string[];\n stream?: boolean;\n onProgress?: (event: any) => void;\n };\n\n /* Message */\n export type Message = { role: string; parts: Part[] };\n\n export type Part = TextPart | FilePart | ToolPart;\n export type TextPart = { type: 'text'; text: string };\n export type FilePart = { type: 'file'; mimetype: string; url: string; id: string; extract?: string };\n export type ToolPart = FunctionCallTool | FunctionTool;\n\n /* Tools */\n export type Tools = FunctionTool;\n export type FunctionCallTool = {\n type: 'function_call';\n function_call: { name: string; args: any };\n id?: string | undefined;\n };\n export type FunctionTool = { type: 'function'; function: Function };\n\n export type Function = {\n name: string;\n description: string;\n parameters: { type: string; properties: any; required: string[] };\n };\n\n /**\n * Response\n */\n export type ChatResponse = {\n id: string;\n model: string;\n choices: Choice[];\n usage: Usage;\n };\n\n export type Choice = {\n index: number;\n role: string;\n parts: Part[];\n finish_reason: 'stop' | 'function_call' | string | null;\n };\n\n export type Usage = { prompt_tokens: number; completion_tokens: number; total_tokens: number };\n}\n","import { get_encoding } from 'tiktoken';\nimport fetch from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport * as types from '@/types';\n\nexport class ChatBaseAPI {\n protected provider: string = '';\n\n protected agent?: string = '';\n protected baseURL: string = '';\n protected apiKey: string = '';\n protected apiSecret?: string = '';\n protected timeout?: number = 10000;\n\n constructor(opts: types.chat.ChatOptions) {\n opts.agent && (this.agent = opts.agent);\n opts.baseURL && (this.baseURL = opts.baseURL);\n opts.apiKey && (this.apiKey = opts.apiKey);\n opts.apiSecret && (this.apiSecret = opts.apiSecret);\n opts.timeout && (this.timeout = opts.timeout);\n }\n\n public models(): string[] {\n throw new Error('Not implemented');\n }\n\n public async sendMessage(opts: types.chat.SendOptions | types.image.SendOptions): Promise {\n throw new Error('Not implemented');\n }\n\n public async getTaskResult(task_id: string): Promise {\n throw new Error('Not implemented');\n }\n\n protected async fetchFile(url: string) {\n const response = await fetch(url, {\n headers: {\n 'user-agent':\n 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',\n },\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n });\n const buffer = await response.buffer();\n const base64 = buffer.toString('base64');\n const mimeType = response.headers.get('content-type') as string;\n return { mimeType, data: base64 };\n }\n\n protected combineChoices(choices: types.chat.Choice[]): types.chat.Choice[] {\n return choices.reduce((acc: types.chat.Choice[], item: types.chat.Choice) => {\n const existingItem = acc.find((i: types.chat.Choice) => i.index === item.index);\n if (existingItem) {\n item.parts.forEach((part: types.chat.Part) => {\n if (part.type === 'text') {\n const existingPart = existingItem.parts.find((p: types.chat.Part) => p.type === 'text');\n if (existingPart) {\n (existingPart as types.chat.TextPart).text += (part as types.chat.TextPart).text;\n } else {\n existingItem.parts.push(part);\n }\n } else if (part.type === 'function_call') {\n const existingPart = existingItem.parts.find((p: types.chat.Part) => p.type === 'function_call');\n if (existingPart) {\n (existingPart as types.chat.FunctionCallTool).function_call.name +=\n (part as types.chat.FunctionCallTool).function_call.name || '';\n (existingPart as types.chat.FunctionCallTool).function_call.args +=\n (part as types.chat.FunctionCallTool).function_call.args || '';\n } else {\n existingItem.parts.push(part);\n }\n } else {\n const existingPart = existingItem.parts.find(\n (p: types.chat.Part) => JSON.stringify(p) === JSON.stringify(part),\n );\n if (!existingPart) {\n existingItem.parts.push(part);\n }\n }\n });\n\n // finish_reason\n existingItem.finish_reason = item.finish_reason;\n } else {\n acc.push(item);\n }\n return acc;\n }, []);\n }\n\n protected caclulateUsage(messages: types.chat.Message[], choices: types.chat.Choice[]): types.chat.Usage {\n const parts: types.chat.Part[] = messages.flatMap((item) => item.parts);\n const prompt_tokens = parts\n .filter((p) => p.type === 'text' || (p.type === 'file' && p.extract))\n .reduce((acc: number, item) => {\n return acc + this.getTokenCount((item as types.chat.TextPart)?.text || (item as types.chat.FilePart)?.extract);\n }, 0);\n const completion_tokens = choices.reduce((acc: number, item: types.chat.Choice) => {\n return acc + this.getTokenCount(item.parts.map((part) => (part as types.chat.TextPart).text).join(''));\n }, 0);\n return { prompt_tokens, completion_tokens, total_tokens: prompt_tokens + completion_tokens };\n }\n\n protected getTokenCount(text: string) {\n return get_encoding('cl100k_base').encode(text).length;\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { ChatBaseAPI } from '../base';\n\nexport class OpenAIAssistantsAPI extends ChatBaseAPI {\n protected provider: string = 'openai';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://api.openai.com/v1' }, opts);\n super(options);\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { v4 as uuidv4 } from 'uuid';\nimport { GoogleAuth } from 'google-auth-library';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { GoogleGeminiAPI } from './gemini';\nimport { gemini } from './types';\n\nexport class GoogleVertexAPI extends GoogleGeminiAPI {\n protected provider: string = 'google';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign(\n {\n baseURL: 'https://us-central1-aiplatform.googleapis.com/v1/projects/bodhi-415003/locations/us-central1',\n },\n opts,\n );\n super(options);\n }\n\n public models(): string[] {\n return ['gemini-1.0-pro', 'gemini-1.5-pro-preview-0409'];\n }\n\n /**\n * 根据服务账号获取 access token\n */\n private async getToken(): Promise {\n const auth: GoogleAuth = new GoogleAuth({\n credentials: { client_email: this.apiKey, private_key: this.apiSecret },\n scopes: 'https://www.googleapis.com/auth/cloud-platform',\n });\n return (await auth.getAccessToken()) as string;\n }\n\n /**\n * 发送消息\n * @param opts \n * Reference: https://cloud.google.com/vertex-ai/docs/reference/rest/v1/GenerateContentResponse\n * Reference: https://cloud.google.com/vertex-ai/docs/generative-ai/model-reference/gemini?hl=zh-cn\n * Multi-modal: https://cloud.google.com/vertex-ai/docs/generative-ai/multimodal/send-multimodal-prompts?hl=zh-cn#gemini-send-multimodal-samples-drest\n * Tools: https://cloud.google.com/vertex-ai/docs/generative-ai/multimodal/function-calling?hl=zh-cn\n * @returns\n */\n public async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n\n return new Promise(async (resolove, reject) => {\n const token = await this.getToken();\n const model = this.detechModel(opts);\n const url = `${this.baseURL}/publishers/google/models/${model}:streamGenerateContent?alt=sse`;\n const params: gemini.Request = await this.convertParams(options);\n // console.log(`[fetch]params`, model, url, opts.messages);\n\n const res = await fetchSSE(url, {\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },\n body: JSON.stringify(params),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.error?.message || 'request error', res.status));\n }\n\n // only get content from node-fetch\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n // streaming\n const choicesList: types.chat.Choice[] = [];\n const usage: types.chat.Usage = { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n if (event.type === 'event') {\n const res = JSON.parse(event.data);\n if (!res.candidates) {\n console.log(`[vertex]debug`, res);\n }\n const choices = this.convertChoices(res.candidates || []);\n if (res.usageMetadata) {\n Object.assign(usage, {\n prompt_tokens: res.usageMetadata.promptTokenCount,\n completion_tokens: res.usageMetadata.candidatesTokenCount,\n total_tokens: res.usageMetadata.totalTokenCount,\n });\n }\n onProgress?.(choices);\n choicesList.push(...choices);\n }\n });\n body.on('readable', async () => {\n let chunk: string | Buffer;\n while ((chunk = body.read())) {\n parser.feed(chunk.toString());\n }\n });\n\n // finished\n body.on('end', () => {\n const choices: types.chat.Choice[] = this.combineChoices(choicesList);\n // TODO: Google AI Gemini not found usageMetadata, but vertex founded.\n resolove({ id: uuidv4(), model: opts.model, choices, usage });\n });\n });\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { v4 as uuidv4 } from 'uuid';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { gemini } from './types';\nimport { ChatBaseAPI } from '../base';\n\nexport class GoogleGeminiAPI extends ChatBaseAPI {\n protected provider: string = 'google';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://generativelanguage.googleapis.com/v1beta' }, opts);\n super(options);\n }\n\n public models(): string[] {\n return ['gemini-pro', 'gemini-pro-vision', 'gemini-1.5-pro-latest'];\n }\n\n /**\n *\n * https://ai.google.dev/docs/gemini_api_overview?hl=zh-cn#curl_3\n * @param opts\n * @returns\n */\n public async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n return new Promise(async (resolove, reject) => {\n const params: gemini.Request = await this.convertParams(options);\n const model = this.detechModel(opts);\n const url = `${this.baseURL}/models/${model}:streamGenerateContent?alt=sse`;\n // console.log(`[fetch]params`, url, JSON.stringify(params, null, 2));\n\n const res = await fetchSSE(url, {\n headers: { 'Content-Type': 'application/json', 'x-goog-api-key': this.apiKey },\n body: JSON.stringify(params),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n // console.log(`[fetch]result`, res);\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.error?.message || 'request error', res.status));\n }\n\n // only get content from node-fetch\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n // streaming\n const choicesList: types.chat.Choice[] = [];\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n if (event.type === 'event') {\n const res = JSON.parse(event.data);\n // console.log(`->`, JSON.stringify(res));\n const choices = this.convertChoices(res.candidates);\n onProgress?.(choices);\n\n choicesList.push(...choices);\n }\n });\n body.on('readable', async () => {\n let chunk: string | Buffer;\n while ((chunk = body.read())) {\n parser.feed(chunk.toString());\n }\n });\n\n body.on('end', () => {\n const choices: types.chat.Choice[] = this.combineChoices(choicesList);\n // TODO: Google AI Gemini not found usageMetadata, but vertex founded.\n const usage = { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };\n resolove({ id: uuidv4(), model: opts.model, choices, usage });\n });\n });\n }\n\n protected detechModel(opts: types.chat.SendOptions): string {\n const hasMedia = opts.messages.some((item) =>\n item.parts.some(\n (part) =>\n part.type === 'file' &&\n (part.mimetype.startsWith('image') || part.mimetype.startsWith('video') || part.mimetype.startsWith('audio')),\n ),\n );\n return hasMedia && opts.model === 'gemini-1.0-pro' ? 'gemini-1.0-pro-vision' : opts.model;\n }\n\n /**\n * 转换为 Gemini 要求的请求参数\n * https://cloud.google.com/vertex-ai/docs/reference/rest/v1/GenerateContentResponse\n * @returns\n */\n protected async convertParams(opts: types.chat.SendOptions): Promise {\n return {\n contents: await this.corvertContents(opts),\n // systemInstruction: await this.corvertSystemContent(opts),\n tools: this.corvertTools(opts),\n safety_settings: [\n // { category: 'BLOCK_NONE', threshold: 'HARM_CATEGORY_UNSPECIFIED' },\n ],\n generationConfig: {\n temperature: opts.temperature || 0.9, // gemini-pro:0.9, gemini-pro-vision:0.4\n topP: opts.top_p || 1, // gemini-pro:none, gemini-pro-vision:32\n // topK: Math.round((opts.top_k || 0.025) * 40) || 32,\n candidateCount: opts.n || 1,\n maxOutputTokens: opts.max_tokens || 2048, // gemini-pro:2048, gemini-pro-vision:8192\n stopSequences: opts.stop_sequences || undefined,\n },\n };\n }\n\n protected async corvertContents(opts: types.chat.SendOptions): Promise {\n // filter system role\n const rows = await Promise.all(\n opts.messages\n .filter((item) => ['user', 'assistant'].includes(item.role))\n .map(async (item) => {\n const parts: gemini.Part[] = [];\n await Promise.all(\n item.parts.map(async (part: types.chat.Part) => {\n // text\n if (part.type === 'text') {\n parts.push({ text: part.text });\n }\n // file\n if (part.type === 'file') {\n if (part?.extract) {\n parts.push({ text: part.extract });\n } else {\n const { mimetype: mimeType, url } = part as types.chat.FilePart;\n if (url.startsWith('gs://')) {\n parts.push({ fileData: { mimeType, fileUri: url } });\n } else {\n try {\n parts.push({ inlineData: await this.fetchFile(url) });\n } catch (err) {}\n }\n }\n }\n // tools\n if (part.type === 'function_call') {\n const { name, args } = part.function_call;\n parts.push({ functionCall: { name, args } });\n }\n }),\n );\n item.role = item.role === 'assistant' ? 'model' : item.role;\n return { role: item.role, parts } as gemini.Content;\n }),\n );\n\n // Compatible with system role\n // insert system text part to rows's first user parts\n const system = opts.messages.filter((item) => item.role === 'system');\n if (system.length > 0) {\n const textParts = system[0].parts.filter((part) => 'text' in part) as gemini.TextPart[];\n rows[0].parts.unshift(...textParts.map((part) => ({ text: `[instructions]\\n${part.text}\\n\\n[user prompt]\\n` })));\n }\n\n return rows;\n }\n\n protected corvertTools(opts: types.chat.SendOptions): gemini.Tools[] {\n const tools: gemini.Tools[] = [];\n if (opts.tools) {\n opts.tools.map((item) => {\n if (item.type === 'function') {\n tools.push({ functionDeclarations: [item.function] });\n }\n });\n }\n return tools;\n }\n\n protected convertChoices(candidates: gemini.Candidate[]): types.chat.Choice[] {\n const choices: types.chat.Choice[] = [];\n\n try {\n candidates.map(({ index, content, finishReason }: gemini.Candidate) => {\n const parts: types.chat.Part[] = [];\n content.parts.map((part: any) => {\n if ('text' in part) {\n parts.push({ type: 'text', text: part.text });\n }\n if ('functionCall' in part) {\n parts.push({ type: 'function_call', function_call: part.functionCall });\n }\n });\n choices.push({ index, role: 'assistant', parts, finish_reason: 'stop' });\n });\n } catch (err) {\n console.log(`->candidates1`, JSON.stringify(candidates, null, 2));\n console.warn(err);\n console.log(`->candidates2`);\n }\n return choices;\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { GoogleAuth } from 'google-auth-library';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { claude } from '../anthropic/types';\nimport { ChatBaseAPI } from '../base';\n\nexport class GoogleClaudeAPI extends ChatBaseAPI {\n protected provider: string = 'google';\n\n constructor(opts: types.chat.ChatOptions) {\n // available models: claude-instant-1p2(100K tokens), claude-2p0(200K tokens)\n // available regions: us-central1(60QPM), asia-southeast1(60QPM)\n const options = Object.assign(\n { baseURL: 'https://us-central1-aiplatform.googleapis.com/v1/projects/bodhi-415003/locations/us-central1' },\n opts,\n );\n super(options);\n }\n\n /**\n * 根据服务账号获取 access token\n */\n private async getToken(): Promise {\n const auth: GoogleAuth = new GoogleAuth({\n credentials: { client_email: this.apiKey, private_key: this.apiSecret },\n scopes: 'https://www.googleapis.com/auth/cloud-platform',\n });\n return (await auth.getAccessToken()) as string;\n }\n\n public models(): string[] {\n return ['claude-3-sonnet@20240229', 'claude-3-haiku@20240307', 'gemini-1.5-flash-preview-0514'];\n }\n\n /**\n * Send message\n * https://docs.anthropic.com/claude/reference/messages_post\n * @param opts\n * @returns\n */\n public async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n return new Promise(async (resolove, reject) => {\n const token = await this.getToken();\n const url = `${this.baseURL}/publishers/anthropic/models/${opts.model}:streamRawPredict?alt=sse`;\n const params: claude.Request = await this.convertParams(options);\n // console.log(`->url`, url, JSON.stringify(params));\n const res = await fetchSSE(url, {\n headers: { 'content-type': 'application/json', Authorization: `Bearer ${token}` },\n body: JSON.stringify(params),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.error?.message || 'request error', res.status));\n }\n\n // only get content from node-fetch\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n let response: types.chat.ChatResponse;\n const choicesList: types.chat.Choice[] = [];\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n if (event.type === 'event') {\n const res: claude.Response = JSON.parse(event.data);\n response = this.convertResult(response, res);\n const choices = this.convertChoices(res);\n if (choices.length > 0) {\n onProgress?.(choices);\n choicesList.push(...choices);\n }\n }\n });\n body.on('readable', async () => {\n let chunk: string | Buffer;\n while ((chunk = body.read())) {\n parser.feed(chunk.toString());\n }\n });\n\n body.on('end', () => {\n response.choices = this.combineChoices(choicesList);\n resolove(response);\n });\n });\n }\n\n /**\n * https://docs.anthropic.com/claude/reference/messages-streaming\n * @returns\n */\n private async convertParams(opts: types.chat.SendOptions): Promise {\n return {\n messages: await this.corvertContents(opts),\n system: this.corvertSystem(opts),\n temperature: opts.temperature || 0.8,\n top_p: opts.top_p || 1,\n // top_k: opts.top_k || 1,\n max_tokens: opts.max_tokens || 1024,\n stop_sequences: opts.stop_sequences || [],\n stream: true,\n anthropic_version: 'vertex-2023-10-16',\n };\n }\n\n protected corvertSystem(opts: types.chat.SendOptions): string {\n return opts.messages\n .filter((item) => item.role === 'system')\n .map((item) =>\n item.parts\n .filter((p: types.chat.Part) => p.type === 'text')\n .map((p) => (p as types.chat.TextPart).text)\n .join(''),\n )\n .join('\\n');\n }\n\n protected async corvertContents(opts: types.chat.SendOptions): Promise {\n return Promise.all(\n opts.messages\n .filter((item) => item.role !== 'system')\n .map(async (item) => {\n const parts: claude.Part[] = [];\n await Promise.all(\n item.parts.map(async (part: types.chat.Part) => {\n // text\n if (part.type === 'text') {\n parts.push({ type: 'text', text: part.text });\n }\n // file, only support image, now\n if (part.type === 'file' && part?.extract) {\n parts.push({ type: 'text', text: part.extract });\n }\n if (part.type === 'file' && part.mimetype?.startsWith('image')) {\n try {\n const { mimeType: media_type, data } = await this.fetchFile((part as types.chat.FilePart).url);\n parts.push({ type: 'image', source: { type: 'base64', media_type, data } });\n } catch (err) {\n // console.warn(``);\n }\n }\n }),\n );\n return { role: item.role, content: parts } as claude.Content;\n }),\n );\n }\n\n private convertResult(response, res: claude.Response): types.chat.ChatResponse {\n try {\n if (res.type === 'message_start') {\n const { message: m } = res;\n const { input_tokens: prompt_tokens, output_tokens: completion_tokens } = m.usage;\n response = {\n id: m.id,\n model: m.model,\n choices: [],\n usage: { prompt_tokens, completion_tokens, total_tokens: prompt_tokens + completion_tokens },\n };\n }\n\n if (res.type === 'message_delta') {\n const { output_tokens } = res.usage;\n response.usage.completion_tokens = output_tokens;\n response.usage.total_tokens = response.usage.prompt_tokens + output_tokens;\n }\n } catch (err) {\n console.warn(err);\n }\n return response;\n }\n\n private convertChoices(res: claude.Response): types.chat.Choice[] {\n const choices: types.chat.Choice[] = [];\n try {\n if (res.type === 'content_block_start') {\n const { index, content_block: c } = res;\n choices.push({ index, role: 'assistant', parts: [{ type: 'text', text: c.text }], finish_reason: null });\n }\n\n if (res.type === 'content_block_delta') {\n const { index, delta: d } = res;\n choices.push({ index, role: 'assistant', parts: [{ type: 'text', text: d.text }], finish_reason: null });\n }\n\n if (res.type === 'content_block_stop') {\n const { index } = res;\n choices.push({ index, role: 'assistant', parts: [], finish_reason: 'stop' });\n }\n } catch (err) {\n console.warn(err);\n }\n return choices;\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { claude } from './types';\nimport { ChatBaseAPI } from '../base';\n\nexport class AnthropicClaudeAPI extends ChatBaseAPI {\n protected provider: string = 'anthropic';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://api.anthropic.com' }, opts);\n super(options);\n }\n\n public models(): string[] {\n return [\n 'claude-3-opus-20240229',\n 'claude-3-sonnet-20240229',\n 'claude-3-haiku-20240307',\n 'claude-2.1',\n 'claude-2.0',\n 'claude-instant-1.2',\n ];\n }\n\n /**\n * Send message\n * https://docs.anthropic.com/claude/reference/messages_post\n * @param opts\n * @returns\n */\n public async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n return new Promise(async (resolove, reject) => {\n const url = `${this.baseURL}/v1/messages`;\n const params: claude.Request = await this.convertParams(options);\n const res = await fetchSSE(url, {\n headers: {\n 'content-type': 'application/json',\n 'anthropic-version': '2023-06-01',\n 'x-api-key': this.apiKey,\n },\n body: JSON.stringify(params),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.error?.message || 'request error', res.status));\n }\n\n // only get content from node-fetch\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n let response: types.chat.ChatResponse;\n const choicesList: types.chat.Choice[] = [];\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n if (event.type === 'event') {\n const res: claude.Response = JSON.parse(event.data);\n response = this.convertResult(response, res);\n const choices = this.convertChoices(res);\n if (choices.length > 0) {\n onProgress?.(choices);\n choicesList.push(...choices);\n }\n }\n });\n body.on('readable', async () => {\n let chunk: string | Buffer;\n while ((chunk = body.read())) {\n parser.feed(chunk.toString());\n }\n });\n\n body.on('end', () => {\n response.choices = this.combineChoices(choicesList);\n resolove(response);\n });\n });\n }\n\n /**\n * https://docs.anthropic.com/claude/reference/messages-streaming\n * @returns\n */\n private async convertParams(opts: types.chat.SendOptions): Promise {\n return {\n model: opts.model || 'claude-3-haiku-20240307',\n messages: await this.corvertContents(opts),\n system: this.corvertSystem(opts),\n temperature: opts.temperature || 0.8,\n top_p: opts.top_p || 1,\n // top_k: opts.top_k || 1,\n max_tokens: opts.max_tokens || 1024,\n // metadata:\n stop_sequences: opts.stop_sequences || [],\n stream: true,\n };\n }\n\n protected corvertSystem(opts: types.chat.SendOptions): string {\n return opts.messages\n .filter((item) => item.role === 'system')\n .map((item) =>\n item.parts\n .filter((p: types.chat.Part) => p.type === 'text')\n .map((p) => (p as types.chat.TextPart).text)\n .join(''),\n )\n .join('\\n');\n }\n\n protected async corvertContents(opts: types.chat.SendOptions): Promise {\n return Promise.all(\n opts.messages\n .filter((item) => item.role !== 'system')\n .map(async (item) => {\n const parts: claude.Part[] = [];\n await Promise.all(\n item.parts.map(async (part: types.chat.Part) => {\n // text\n if (part.type === 'text') {\n parts.push({ type: 'text', text: part.text });\n }\n // file, only support image, now\n if (part.type === 'file' && part?.extract) {\n parts.push({ type: 'text', text: part.extract });\n }\n if (part.type === 'file' && part.mimetype?.startsWith('image')) {\n try {\n const { mimeType: media_type, data } = await this.fetchFile((part as types.chat.FilePart).url);\n parts.push({ type: 'image', source: { type: 'base64', media_type, data } });\n } catch (err) {\n // console.warn(``);\n }\n }\n }),\n );\n return { role: item.role, content: parts } as claude.Content;\n }),\n );\n }\n\n private convertResult(response, res: claude.Response): types.chat.ChatResponse {\n try {\n if (res.type === 'message_start') {\n const { message: m } = res;\n const { input_tokens: prompt_tokens, output_tokens: completion_tokens } = m.usage;\n response = {\n id: m.id,\n model: m.model,\n choices: [],\n usage: { prompt_tokens, completion_tokens, total_tokens: prompt_tokens + completion_tokens },\n };\n }\n\n if (res.type === 'message_delta') {\n const { output_tokens } = res.usage;\n response.usage.completion_tokens = output_tokens;\n response.usage.total_tokens = response.usage.prompt_tokens + output_tokens;\n }\n } catch (err) {\n console.warn(err);\n }\n return response;\n }\n\n private convertChoices(res: claude.Response): types.chat.Choice[] {\n const choices: types.chat.Choice[] = [];\n try {\n if (res.type === 'content_block_start') {\n const { index, content_block: c } = res;\n choices.push({ index, role: 'assistant', parts: [{ type: 'text', text: c.text }], finish_reason: null });\n }\n\n if (res.type === 'content_block_delta') {\n const { index, delta: d } = res;\n choices.push({ index, role: 'assistant', parts: [{ type: 'text', text: d.text }], finish_reason: null });\n }\n\n if (res.type === 'content_block_stop') {\n const { index } = res;\n choices.push({ index, role: 'assistant', parts: [], finish_reason: 'stop' });\n }\n } catch (err) {\n console.warn(err);\n }\n return choices;\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { ChatBaseAPI } from '../base';\nimport { requestWithAuth, toUtf8 } from './auth';\n\nexport class AnthropicBedrockAPI extends ChatBaseAPI {\n protected provider: string = 'anthropic';\n\n constructor(opts: types.chat.ChatOptions) {\n super(Object.assign({ baseURL: `https://bedrock-runtime.ap-northeast-1.amazonaws.com` }, opts));\n }\n\n public models(): string[] {\n return ['anthropic.claude-v2:1', 'anthropic.claude-v2', 'anthropic.claude-v1', 'anthropic.claude-instant-v1'];\n }\n\n /**\n * Send message\n * https://docs.anthropic.com/claude/reference/messages_post\n * @param opts\n * @returns\n */\n public async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n\n return new Promise(async (resolove, reject) => {\n const url = new URL(`${this.baseURL}/model/${opts.model}/invoke-with-response-stream`);\n // 预请求并签名\n const req = await requestWithAuth(\n { region: 'ap-northeast-1', service: 'bedrock', accessKeyId: this.apiKey, secretAccessKey: this.apiSecret },\n {\n method: 'POST',\n protocol: url.protocol,\n path: url.pathname,\n headers: {\n host: url.hostname,\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n 'User-Agent': 'AnthropicBedrock/JS 0.6.1',\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': '0.6.1',\n 'X-Stainless-OS': 'MacOS',\n 'X-Stainless-Arch': 'arm64',\n 'X-Stainless-Runtime': 'node',\n 'X-Stainless-Runtime-Version': 'v19.4.0',\n },\n body: JSON.stringify(this.convertParams(options), null, 2),\n },\n );\n // 请求\n const res = await fetchSSE(url, {\n headers: req.headers,\n body: req.body,\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: req.method,\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.message || 'request error', res.status));\n }\n\n // only get content from node-fetch\n let response: any;\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n // if (event.type === 'event') {\n // response = JSON.parse(event.data);\n // onProgress?.(response);\n // }\n console.log(`[bedrock]`, event);\n });\n\n body.on('readable', async () => {\n // 解析SSE 并进行utf8解码\n // let chunk: string | Buffer;\n // while ((chunk = body.read())) {\n // console.log(`[bedrock]`, chunk.toString());\n // // parser.feed(chunk.toString());\n // }\n\n let event;\n while (null !== (event = body.read())) {\n if (Buffer.isBuffer(event)) {\n console.log(`[bedrock]`, event.toString('utf8'));\n }\n }\n });\n\n body.on('end', () => {\n resolove(response);\n });\n });\n }\n\n /**\n * https://docs.anthropic.com/claude/reference/messages-streaming\n * @returns\n */\n private convertParams(opts: types.chat.SendOptions) {\n return {\n prompt: '\\n\\nHuman: Hey Claude! How can I recursively list all files in a directory in Rust?\\n\\nAssistant:',\n temperature: 1,\n // top_k: 250,\n // top_p: 0.999,\n max_tokens_to_sample: 500,\n anthropic_version: 'bedrock-2023-05-31',\n };\n }\n\n // 将 Gemini 的结果转换为你的数据格式\n private convertResult(result: any) {\n return {\n // 根据你的数据格式,从 Gemini 的结果中提取数据\n history: result.contents,\n // 其他数据...\n };\n }\n}\n","import { SignatureV4 } from '@smithy/signature-v4';\nimport { HttpRequest } from '@aws-sdk/protocol-http';\nimport { Sha256 } from '@aws-crypto/sha256-js';\n\nexport const toUtf8 = (input: Uint8Array): string => new TextDecoder('utf-8').decode(input);\n\nexport async function requestWithAuth(options: any, request: any): Promise {\n const { accessKeyId, secretAccessKey, region, service } = options;\n const credentials = { accessKeyId, secretAccessKey };\n // sign request\n const signed = await new SignatureV4({ region, service, sha256: Sha256, credentials }).sign(new HttpRequest(request));\n return signed as HttpRequest;\n}\n","import fetchSSE from 'node-fetch';\nimport { v4 as uuidv4 } from 'uuid';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { ChatBaseAPI } from '../base';\nimport { aliyun } from './types';\n\nexport class AliyunQwenAPI extends ChatBaseAPI {\n protected provider: string = 'google';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://dashscope.aliyuncs.com/api/v1' }, opts);\n super(options);\n }\n\n public models(): string[] {\n return ['qwen-turbo', 'qwen-plus', 'qwen-max'];\n }\n\n /**\n *\n * https://ai.google.dev/docs/gemini_api_overview?hl=zh-cn#curl_3\n * @param opts\n * @returns\n */\n public async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n return new Promise(async (resolove, reject) => {\n // 如果消息存在图片, 则自动切换到 multimodal\n const isMulti =\n opts.model !== 'qwen-turbo' &&\n opts.messages.some((item) => item.parts.some((part) => ['image'].includes(part.type)));\n const model = isMulti ? opts.model.replace('-', '-vl-') : opts.model;\n const url = `${this.baseURL}/services/aigc/${isMulti ? 'multimodal' : 'text'}-generation/generation`;\n const params: aliyun.Request = await this.convertParams(model, options);\n // console.log(`[fetch]params`, JSON.stringify(params, null, 2));\n\n const res = await fetchSSE(url, {\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`,\n 'X-DashScope-SSE': 'enable',\n },\n body: JSON.stringify(params),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.message || 'request error', res.status));\n }\n\n // only get content from node-fetch\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n // streaming\n const choicesList: types.chat.Choice[] = [];\n const usage: types.chat.Usage = { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n if (event.type === 'event') {\n const res = JSON.parse(event.data);\n // console.log(`->`, JSON.stringify(res));\n // success\n if (res?.output) {\n const choices = this.convertChoices(res.output.choices);\n onProgress?.(choices);\n\n if (res.usage) {\n const u = res.usage;\n Object.assign(usage, {\n prompt_tokens: u.input_tokens,\n completion_tokens: u.output_tokens,\n total_tokens: u.total_tokens ? u.total_tokens : u.input_tokens + u.output_tokens,\n });\n }\n choicesList.push(...choices);\n }\n\n // error\n if (res?.code) {\n reject(new types.chat.ChatError(res?.message, 500));\n }\n }\n });\n body.on('readable', async () => {\n let chunk: string | Buffer;\n while ((chunk = body.read())) {\n parser.feed(chunk.toString());\n }\n });\n\n body.on('end', () => {\n const choices: types.chat.Choice[] = this.combineChoices(choicesList);\n resolove({ id: uuidv4(), model: opts.model, choices, usage });\n });\n });\n }\n\n /**\n * Aliyun Qwen API\n * https://help.aliyun.com/zh/dashscope/developer-reference/api-details\n * @returns\n */\n private async convertParams(model, opts: types.chat.SendOptions): Promise {\n const params = {\n model: model || 'qwen-turbo',\n input: {\n messages: await this.corvertContents(opts),\n },\n parameters: {\n temperature: (opts.temperature || 0.85) * 2 - 0.1,\n top_p: opts.top_p || 0.8,\n // top_k: Math.round((opts.top_k || 0.025) * 100) || undefined,\n max_tokens: opts.max_tokens || 1500,\n incremental_output: true,\n enable_search: true,\n },\n };\n // fix different model\n if (model.indexOf('vl') === -1) {\n Object.assign(params.parameters, {\n temperature: opts.temperature || 1,\n max_tokens: opts.max_tokens || 1500,\n enable_search: true,\n stop: opts.stop_sequences || undefined,\n result_format: 'message',\n });\n }\n return params;\n }\n\n private async corvertContents(opts: types.chat.SendOptions): Promise {\n return Promise.all(\n opts.messages.map(async (item) => {\n const parts: aliyun.Part[] = [];\n await Promise.all(\n item.parts.map(async (part: types.chat.Part) => {\n // text\n if (part.type === 'text') {\n parts.push({ text: part.text });\n }\n // file: docs\n if (part.type === 'file' && part?.extract) {\n parts.push({ text: part.extract });\n }\n\n // file, only support image, now\n if (part.type === 'file' && part.mimetype?.startsWith('image')) {\n parts.push({ image: (part as types.chat.FilePart).url });\n }\n }),\n );\n // fix different model\n let content: string | aliyun.Part[] = parts;\n if (!['qwen-vl-plus'].includes(opts.model)) {\n content = parts\n .map((item: any) => {\n return 'text' in item ? item.text : '';\n })\n .join('\\n');\n }\n return { role: item.role, content: parts } as aliyun.Content;\n }),\n );\n }\n\n protected convertChoices(candidates: aliyun.Choice[]): types.chat.Choice[] {\n const choices: types.chat.Choice[] = [];\n try {\n candidates.map(({ message, finish_reason }: aliyun.Choice) => {\n const parts: types.chat.Part[] = [];\n // for text\n if (typeof message.content === 'string') {\n parts.push({ type: 'text', text: message.content });\n }\n // for multimodal\n if (typeof message.content === 'object' && message.content instanceof Array) {\n message.content.map((part: any) => {\n if ('text' in part) {\n parts.push({ type: 'text', text: part.text });\n }\n });\n }\n choices.push({ index: 0, role: 'assistant', parts, finish_reason: 'stop' });\n });\n } catch (err) {\n console.warn(err);\n }\n return choices;\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { ChatBaseAPI } from '../base';\n\nexport class AliyunWanxAPI extends ChatBaseAPI {\n protected provider: string = 'google';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://dashscope.aliyuncs.com/api/v1' }, opts);\n super(options);\n }\n\n public models(): string[] {\n return ['wanx-v1'];\n }\n\n /**\n * https://help.aliyun.com/zh/dashscope/developer-reference/api-details-9\n * @param opts\n * @returns\n */\n public async sendMessage(opts: types.image.SendOptions) {\n return new Promise(async (resolove, reject) => {\n const url = `${this.baseURL}/services/aigc/text2image/image-synthesis`;\n const res = await fetchSSE(url, {\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`,\n 'X-DashScope-Async': 'enable',\n },\n body: JSON.stringify(this.convertParams(opts)),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.message || 'request error', res.status));\n }\n\n try {\n const { output } = await res.json();\n if (output.task_status === 'FAILED') {\n reject(new types.chat.ChatError(output.message, res.status));\n }\n resolove(output);\n } catch (err) {\n reject(new types.chat.ChatError('request error', res.status));\n }\n });\n }\n\n public async getTaskResult(task_id: string) {\n const url = `${this.baseURL}/tasks/${task_id}`;\n return new Promise(async (resolove, reject) => {\n const res = await fetchSSE(url, {\n headers: { Authorization: `Bearer ${this.apiKey}` },\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n });\n\n try {\n const { output } = await res.json();\n if (output.task_status === 'FAILED') {\n reject(new types.chat.ChatError(output.message, res.status));\n }\n\n resolove(output);\n } catch (err) {\n reject(new types.chat.ChatError('request error', res.status));\n }\n });\n }\n\n /**\n * https://help.aliyun.com/zh/dashscope/developer-reference/api-details-9\n * @returns\n */\n private convertParams(opts: types.image.SendOptions) {\n return {\n model: opts.model || 'wanx-v1',\n input: {\n prompt: opts.prompt,\n },\n parameters: {\n style: '',\n size: '1024*1024',\n n: 4,\n seed: 42,\n },\n };\n }\n\n // 将 Gemini 的结果转换为你的数据格式\n private convertResult(result: any) {\n return {\n // 根据你的数据格式,从 Gemini 的结果中提取数据\n history: result.contents,\n // 其他数据...\n };\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { v4 as uuidv4 } from 'uuid';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { ChatBaseAPI } from '../base';\nimport { kimi } from './types';\n\nexport class MoonshotKimiAPI extends ChatBaseAPI {\n protected provider: string = 'moonshot';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://api.moonshot.cn/v1' }, opts);\n super(options);\n }\n\n public models(): string[] {\n return ['moonshot-v1-8k', 'moonshot-v1-32k', 'moonshot-v1-128k'];\n }\n\n async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n\n return new Promise(async (resolove, reject) => {\n const url = `${this.baseURL}/chat/completions`;\n const params: kimi.Request = await this.convertParams(options);\n // console.log(`[fetch]params`, JSON.stringify(params, null, 2));\n\n const res = await fetchSSE(url, {\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${this.apiKey}` },\n body: JSON.stringify(params),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.error?.message || 'request error', res.status));\n return;\n }\n\n // not stream\n let usage = { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };\n if (params.stream === false) {\n const result = await res.json();\n const choices = this.convertChoices(result.choices);\n resolove({ id: uuidv4(), model: opts.model, choices, usage: result.usage });\n } else {\n // streaming\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n const choicesList: types.chat.Choice[] = [];\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n if (event.type === 'event') {\n if (event.data !== '[DONE]') {\n try {\n const result = JSON.parse(event.data);\n const choices = this.convertChoices(result.choices);\n usage = this.convertChoicesUsage(result.choices, usage);\n onProgress?.(choices);\n choicesList.push(...choices);\n } catch (e) {\n // ignore\n }\n }\n }\n });\n body.on('readable', async () => {\n let chunk: string | Buffer;\n while ((chunk = body.read())) {\n parser.feed(chunk.toString());\n }\n });\n\n // console.log(`->`, choicesList);\n body.on('end', async () => {\n const choices: types.chat.Choice[] = this.combineChoices(choicesList);\n resolove({ id: uuidv4(), model: opts.model, choices, usage });\n });\n }\n });\n }\n\n /**\n * 转换为 Gemini 要求的请求参数\n * https://platform.openai.com/docs/api-reference/chat/create\n * @returns\n */\n private async convertParams(opts: types.chat.SendOptions): Promise {\n const params: kimi.Request = {\n model: opts.model || 'moonshot-v1-8k',\n messages: await this.corvertContents(opts),\n temperature: opts?.temperature || 0.9,\n top_p: opts?.top_p || 1.0,\n // frequency_penalty: 0,\n // presence_penalty: 0,\n max_tokens: opts?.max_tokens || 1000,\n n: opts.n || 1,\n stop: opts?.stop_sequences || undefined,\n stream: opts?.stream != undefined ? opts.stream : true,\n };\n // tools\n if (opts.tools && opts.tools.length > 0) {\n Object.assign(params, { tools: opts.tools, stream: false });\n }\n return params;\n }\n\n private async corvertContents(opts: types.chat.SendOptions): Promise {\n return Promise.all(\n opts.messages.map(async (item) => {\n const parts: string[] = [];\n await Promise.all(\n item.parts.map(async (part: types.chat.Part) => {\n // text\n if (part.type === 'text') {\n parts.push(part.text);\n }\n // file, only support image, now\n if (part.type === 'file' && part?.extract) {\n parts.push(part.extract);\n }\n }),\n );\n\n return { role: item.role, content: parts.join('\\n') } as kimi.Message;\n }),\n );\n }\n\n protected convertChoices(candidates: kimi.Choice[]): types.chat.Choice[] {\n const choices: types.chat.Choice[] = [];\n try {\n candidates.map(({ index, delta, message, finish_reason }: kimi.Choice) => {\n const parts: types.chat.Part[] = [];\n let { content } = message || delta;\n if (delta) {\n content = delta.content;\n }\n if (content) {\n parts.push({ type: 'text', text: content });\n }\n\n choices.push({ index, role: 'assistant', parts, finish_reason });\n });\n } catch (err) {\n console.warn(err);\n }\n return choices;\n }\n\n protected convertChoicesUsage(candidates: kimi.Choice[], initial: types.chat.Usage): types.chat.Usage {\n candidates.map(({ usage }: kimi.Choice) => {\n if (usage) {\n initial.prompt_tokens += usage.prompt_tokens;\n initial.completion_tokens += usage.completion_tokens;\n initial.total_tokens += usage.total_tokens;\n }\n });\n return initial;\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { v4 as uuidv4 } from 'uuid';\nimport * as tencentcloud from 'tencentcloud-sdk-nodejs';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { ChatBaseAPI } from '../base';\nimport { hunyuan } from './types';\n\nexport class QcloudHunyuanAPI extends ChatBaseAPI {\n protected provider: string = 'tencent';\n private client: any;\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://hunyuan.tencentcloudapi.com' }, opts);\n super(options);\n\n // init tencentcloud client\n this.client = new tencentcloud.hunyuan.v20230901.Client({\n credential: { secretId: this.apiKey, secretKey: this.apiSecret },\n profile: {\n signMethod: 'TC3-HMAC-SHA256',\n httpProfile: { reqMethod: 'POST', reqTimeout: 30, endpoint: 'hunyuan.tencentcloudapi.com' },\n },\n });\n }\n\n public models(): string[] {\n return ['hunyuan-lite', 'hunyuan-standard', 'hunyuan-pro'];\n }\n\n /**\n * tencent hunyuan\n * https://cloud.tencent.com/document/api/1729/101836\n * @param opts\n * @returns\n */\n public async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n return new Promise(async (resolove, reject) => {\n if (!this.models().includes(opts.model)) {\n reject(new Error(`model ${opts.model} is not supported`));\n }\n\n const params = await this.convertParams(options);\n const response = await this.client.ChatCompletions(params);\n\n // streaming\n let id = uuidv4();\n const choicesList: types.chat.Choice[] = [];\n const usage: types.chat.Usage = { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };\n for await (let message of response) {\n const res = JSON.parse(message.data);\n id = res.Id;\n const choices = this.convertChoices(res.Choices);\n if (res.Usage) {\n Object.assign(usage, {\n prompt_tokens: res.Usage.PromptTokens,\n completion_tokens: res.Usage.CompletionTokens,\n total_tokens: res.Usage.TotalTokens,\n });\n }\n onProgress?.(choices);\n choicesList.push(...choices);\n }\n\n // finished\n const choices: types.chat.Choice[] = this.combineChoices(choicesList);\n resolove({ id, model: opts.model, choices, usage });\n });\n }\n\n /**\n * 转换请求参数\n * @returns\n */\n private async convertParams(opts: types.chat.SendOptions) {\n return {\n Model: opts.model,\n TopP: opts.top_p || 1.0,\n Temperature: opts.temperature || 1.0,\n Messages: await this.corvertContents(opts),\n Stream: true,\n };\n }\n\n private async corvertContents(opts: types.chat.SendOptions): Promise {\n return Promise.all(\n opts.messages.map(async (item) => {\n const parts: string[] = [];\n await Promise.all(\n item.parts.map(async (part: types.chat.Part) => {\n // text\n if (part.type === 'text') {\n parts.push(part.text);\n }\n // file, only support image, now\n if (part.type === 'file' && part?.extract) {\n parts.push(part.extract);\n }\n }),\n );\n return { Role: item.role, Content: parts.join('/n') } as hunyuan.Content;\n }),\n );\n }\n\n protected convertChoices(candidates: hunyuan.Choice[]): types.chat.Choice[] {\n const choices: types.chat.Choice[] = [];\n try {\n candidates.map(({ Delta, FinishReason }: hunyuan.Choice, index) => {\n const parts: types.chat.Part[] = [];\n parts.push({ type: 'text', text: Delta.Content });\n choices.push({ index, role: 'assistant', parts, finish_reason: 'stop' });\n });\n } catch (err) {\n console.warn(err);\n }\n return choices;\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { v4 as uuidv4 } from 'uuid';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { ChatBaseAPI } from '../base';\nimport { deepseek } from './types';\n\nexport class DeepSeekAPI extends ChatBaseAPI {\n protected provider: string = 'moonshot';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://api.deepseek.com' }, opts);\n super(options);\n }\n\n public models(): string[] {\n return ['deepseek-chat'];\n }\n\n async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n\n return new Promise(async (resolove, reject) => {\n const url = `${this.baseURL}/chat/completions`;\n const params: deepseek.Request = await this.convertParams(options);\n // console.log(`[fetch]params`, JSON.stringify(params, null, 2));\n\n const res = await fetchSSE(url, {\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${this.apiKey}` },\n body: JSON.stringify(params),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.error?.message || 'request error', res.status));\n }\n\n // not stream\n if (params.stream === false) {\n const result = await res.json();\n const choices = this.convertChoices(result.choices);\n const usage = result?.usage;\n resolove({ id: uuidv4(), model: opts.model, choices, usage });\n } else {\n // streaming\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n let result;\n const choicesList: types.chat.Choice[] = [];\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n if (event.type === 'event') {\n if (event.data !== '[DONE]') {\n try {\n result = JSON.parse(event.data);\n const choices = this.convertChoices(result.choices);\n onProgress?.(choices);\n choicesList.push(...choices);\n } catch (e) {\n // ignore\n }\n }\n }\n });\n body.on('readable', async () => {\n let chunk: string | Buffer;\n while ((chunk = body.read())) {\n parser.feed(chunk.toString());\n }\n });\n\n body.on('end', async () => {\n const choices: types.chat.Choice[] = this.combineChoices(choicesList);\n resolove({ id: uuidv4(), model: opts.model, choices, usage: result.usage });\n });\n }\n });\n }\n\n /**\n * https://platform.deepseek.com/api-docs/zh-cn/api/create-chat-completion/index.html\n * @returns\n */\n private async convertParams(opts: types.chat.SendOptions): Promise {\n const params: deepseek.Request = {\n model: opts.model || 'moonshot-v1-8k',\n messages: await this.corvertContents(opts),\n temperature: opts?.temperature || 0.9,\n top_p: opts?.top_p || 1.0,\n // frequency_penalty: 0,\n // presence_penalty: 0,\n max_tokens: opts?.max_tokens || 1000,\n // n: opts.n || 1,\n stop: opts?.stop_sequences || undefined,\n stream: true,\n };\n // tools\n if (opts.tools && opts.tools.length > 0) {\n Object.assign(params, { tools: opts.tools, stream: false });\n }\n return params;\n }\n\n private async corvertContents(opts: types.chat.SendOptions): Promise {\n return Promise.all(\n opts.messages.map(async (item) => {\n const parts: string[] = [];\n await Promise.all(\n item.parts.map(async (part: types.chat.Part) => {\n // text\n if (part.type === 'text') {\n parts.push(part.text);\n }\n // file, only support image, now\n if (part.type === 'file' && part?.extract) {\n parts.push(part.extract);\n }\n }),\n );\n\n return { role: item.role, content: parts.join('\\n') } as deepseek.Message;\n }),\n );\n }\n\n protected convertChoices(candidates: deepseek.Choice[]): types.chat.Choice[] {\n const choices: types.chat.Choice[] = [];\n try {\n candidates.map(({ index, delta, message, finish_reason }: deepseek.Choice) => {\n const parts: types.chat.Part[] = [];\n let { content } = message || delta;\n if (delta) {\n content = delta.content;\n }\n if (content) {\n parts.push({ type: 'text', text: content });\n }\n\n choices.push({ index, role: 'assistant', parts, finish_reason });\n });\n } catch (err) {\n console.warn(err);\n }\n return choices;\n }\n}\n","import fetchSSE from 'node-fetch';\nimport { v4 as uuidv4 } from 'uuid';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { createParser, type ParseEvent, type ReconnectInterval } from 'eventsource-parser';\n\nimport * as types from '@/types';\nimport { ChatBaseAPI } from '../base';\nimport { groq } from './types';\n\nexport class GroqCompletionsAPI extends ChatBaseAPI {\n protected provider: string = 'groq';\n\n constructor(opts: types.chat.ChatOptions) {\n const options = Object.assign({ baseURL: 'https://api.groq.com/openai/v1' }, opts);\n super(options);\n }\n\n public models(): string[] {\n return ['llama3-8b-8192', 'llama3-70b-8192', 'mixtral-8x7b-32768', 'gemma-7b-it'];\n }\n\n async sendMessage(opts: types.chat.SendOptions) {\n const { onProgress = () => {}, ...options } = opts;\n\n return new Promise(async (resolove, reject) => {\n const url = `${this.baseURL}/chat/completions`;\n const params: groq.Request = await this.convertParams(options);\n // console.log(`[fetch]params`, JSON.stringify(params, null, 2));\n const res = await fetchSSE(url, {\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${this.apiKey}` },\n body: JSON.stringify(params),\n agent: this.agent ? new HttpsProxyAgent(this.agent) : undefined,\n method: 'POST',\n });\n\n if (!res.ok) {\n const reason = await res.json();\n reject(new types.chat.ChatError(reason.error?.message || 'request error', res.status));\n }\n\n // not stream\n if (params.stream === false) {\n const result = await res.json();\n const choices = this.convertChoices(result.choices);\n const usage = result?.usage;\n resolove({ id: uuidv4(), model: opts.model, choices, usage });\n } else {\n // streaming\n const body: NodeJS.ReadableStream = res.body;\n body.on('error', (err) => reject(new types.chat.ChatError(err.message, 500)));\n\n let result;\n const choicesList: types.chat.Choice[] = [];\n const parser = createParser((event: ParseEvent | ReconnectInterval) => {\n if (event.type === 'event') {\n if (event.data !== '[DONE]') {\n try {\n result = JSON.parse(event.data);\n const choices = this.convertChoices(result.choices);\n onProgress?.(choices);\n choicesList.push(...choices);\n } catch (e) {\n // ignore\n }\n }\n }\n });\n body.on('readable', async () => {\n let chunk: string | Buffer;\n while ((chunk = body.read())) {\n parser.feed(chunk.toString());\n }\n });\n\n body.on('end', async () => {\n const choices: types.chat.Choice[] = this.combineChoices(choicesList);\n const { prompt_tokens, completion_tokens, total_tokens } = result?.x_groq?.usage;\n const usage = { prompt_tokens, completion_tokens, total_tokens };\n resolove({ id: uuidv4(), model: opts.model, choices, usage });\n });\n }\n });\n }\n\n /**\n * 转换为 Gemini 要求的请求参数\n * https://platform.groq.com/docs/api-reference/chat/create\n * @returns\n */\n private async convertParams(opts: types.chat.SendOptions): Promise {\n const params: groq.Request = {\n model: opts.model || 'gpt-3.5-turbo-0125',\n messages: await this.corvertContents(opts),\n temperature: opts?.temperature || 0.9,\n top_p: opts?.top_p || 1,\n // frequency_penalty: 0,\n // presence_penalty: 0,\n max_tokens: opts?.max_tokens || 1000,\n n: opts.n || 1,\n stop: opts?.stop_sequences || undefined,\n stream: true,\n };\n // tools\n if (opts.tools && opts.tools.length > 0) {\n Object.assign(params, { tools: opts.tools, stream: false });\n }\n return params;\n }\n\n private async corvertContents(opts: types.chat.SendOptions): Promise {\n return Promise.all(\n opts.messages.map(async (item) => {\n const parts: groq.Part[] = [];\n const tool_calls: groq.ToolCallPart[] = [];\n await Promise.all(\n item.parts.map(async (part: types.chat.Part) => {\n // text\n if (part.type === 'text') {\n parts.push({ type: 'text', text: part.text });\n }\n // file: docs\n if (part.type === 'file' && part?.extract) {\n parts.push({ type: 'text', text: part.extract });\n }\n\n // file, only support image, now\n if (part.type === 'file' && part.mimetype?.startsWith('image')) {\n parts.push({ type: 'image_url', image_url: { url: (part as types.chat.FilePart).url } });\n }\n // tools\n if (part.type === 'function_call' && part.id) {\n const { name, args } = part.function_call;\n tool_calls.push({ id: part.id, type: 'function', function: { name, arguments: args } });\n }\n }),\n );\n if (item.role === 'system') {\n return { role: 'system', content: this.filterTextPartsToString(parts) } as groq.Message;\n }\n if (item.role === 'assistant') {\n return {\n role: 'assistant',\n content: parts,\n tool_calls: tool_calls.length > 0 ? tool_calls : undefined,\n } as groq.Message;\n }\n return { role: 'user', content: parts } as groq.Message;\n }),\n );\n }\n\n private filterTextPartsToString(parts: groq.Part[]): string {\n return parts\n .filter((p) => p.type === 'text')\n .map((p) => (p as groq.TextPart).text)\n .join('');\n }\n\n protected convertChoices(candidates: groq.Choice[]): types.chat.Choice[] {\n const choices: types.chat.Choice[] = [];\n try {\n candidates.map(({ index, delta, message, finish_reason }: groq.Choice) => {\n const parts: types.chat.Part[] = [];\n let { content, tool_calls } = message || delta;\n if (delta) {\n content = delta.content;\n tool_calls = delta.tool_calls;\n }\n if (content) {\n parts.push({ type: 'text', text: content });\n }\n if (tool_calls) {\n tool_calls.map((call: any) => {\n const { name, arguments: args } = call.function;\n parts.push({ type: 'function_call', function_call: { name, args }, id: call.id });\n });\n }\n\n choices.push({ index, role: 'assistant', parts, finish_reason });\n });\n } catch (err) {\n console.warn(err);\n }\n return choices;\n }\n}\n","import { OpenAICompletionsAPI, OpenAIAssistantsAPI, GoogleClaudeAPI } from '@/provider';\nimport { MoonshotKimiAPI, QcloudHunyuanAPI, DeepSeekAPI } from '@/provider';\nimport { GoogleVertexAPI, GoogleGeminiAPI } from '@/provider';\nimport { AnthropicClaudeAPI, AnthropicBedrockAPI } from '@/provider';\nimport { AliyunQwenAPI, AliyunWanxAPI } from '@/provider';\nimport { ChatBaseAPI } from '@/provider/base';\nimport { GroqCompletionsAPI } from '@/provider/groq';\nimport * as types from '@/types';\n\nexport class ChatAPI {\n private provider: ChatBaseAPI | null = null;\n\n constructor(provider: string, opts: types.chat.ChatOptions) {\n switch (provider) {\n case types.Provider.GOOGLE_VERTEX:\n this.provider = new GoogleVertexAPI(opts);\n break;\n case types.Provider.GOOGLE_GEMINI:\n this.provider = new GoogleGeminiAPI(opts);\n break;\n case types.Provider.GOOGLE_CLAUDE:\n this.provider = new GoogleClaudeAPI(opts);\n break;\n case types.Provider.OPENAI_COMPLETIONS:\n this.provider = new OpenAICompletionsAPI(opts);\n break;\n case types.Provider.OPENAI_ASSISTANTS:\n this.provider = new OpenAIAssistantsAPI(opts);\n break;\n case types.Provider.ALIYUN_QWEN:\n this.provider = new AliyunQwenAPI(opts);\n break;\n case types.Provider.ALIYUN_WANX:\n this.provider = new AliyunWanxAPI(opts);\n break;\n case types.Provider.ANTHROPIC_CLAUDE:\n this.provider = new AnthropicClaudeAPI(opts);\n break;\n case types.Provider.ANTHROPIC_BEDROCK:\n this.provider = new AnthropicBedrockAPI(opts);\n break;\n case types.Provider.QCLOUD_HUNYUAN:\n this.provider = new QcloudHunyuanAPI(opts);\n break;\n case types.Provider.MOONSHOT_KIMI:\n this.provider = new MoonshotKimiAPI(opts);\n break;\n case types.Provider.DEEPSEEK:\n this.provider = new DeepSeekAPI(opts);\n break;\n case types.Provider.GROQ:\n this.provider = new GroqCompletionsAPI(opts);\n break;\n default:\n throw new Error(`Unsupported supplier: ${provider}`);\n }\n }\n\n public async sendMessage(opts: types.chat.SendOptions | types.image.SendOptions) {\n if (!this.provider) {\n throw new Error('Provider is not initialized');\n }\n return await this.provider.sendMessage(opts);\n }\n}\n","import { AliyunWanxAPI } from '@/provider';\nimport { ChatBaseAPI } from '@/provider/base';\n\nimport * as types from '@/types';\n\nexport class ImageAPI {\n private provider: ChatBaseAPI | null = null;\n\n constructor(provider: string, opts: types.chat.ChatOptions) {\n switch (provider) {\n case types.Provider.ALIYUN_WANX:\n this.provider = new AliyunWanxAPI(opts);\n break;\n default:\n throw new Error(`Unsupported supplier: ${provider}`);\n }\n }\n\n public async sendMessage(opts: types.image.SendOptions) {\n if (!this.provider) {\n throw new Error('Provider is not initialized');\n }\n return await this.provider.sendMessage(opts);\n }\n\n public async getTaskResult(task_id: string) {\n if (!this.provider) {\n throw new Error('Provider is not initialized');\n }\n return await this.provider.getTaskResult(task_id);\n }\n}\n"],"mappings":";AAAO,IAAK,WAAL,kBAAKA,cAAL;AACL,EAAAA,UAAA,mBAAgB;AAChB,EAAAA,UAAA,mBAAgB;AAChB,EAAAA,UAAA,mBAAgB;AAChB,EAAAA,UAAA,wBAAqB;AACrB,EAAAA,UAAA,uBAAoB;AACpB,EAAAA,UAAA,sBAAmB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,oBAAoB,IAAI;AAC5C;AAAA,MACF;AACE,aAAK,WAAW,IAAI,iBAAiB,IAAI;AACzC;AAAA,MACF;AACE,aAAK,WAAW,IAAI,gBAAgB,IAAI;AACxC;AAAA,MACF;AACE,aAAK,WAAW,IAAI,YAAY,IAAI;AACpC;AAAA,MACF;AACE,aAAK,WAAW,IAAI,mBAAmB,IAAI;AAC3C;AAAA,MACF;AACE,cAAM,IAAI,MAAM,yBAAyB,QAAQ,EAAE;AAAA,IACvD;AAAA,EACF;AAAA,EAEA,MAAa,YAAY,MAAwD;AAC/E,QAAI,CAAC,KAAK,UAAU;AAClB,YAAM,IAAI,MAAM,6BAA6B;AAAA,IAC/C;AACA,WAAO,MAAM,KAAK,SAAS,YAAY,IAAI;AAAA,EAC7C;AACF;;;AC3DO,IAAM,WAAN,MAAe;AAAA,EAGpB,YAAY,UAAkB,MAA8B;AAF5D,SAAQ,WAA+B;AAGrC,YAAQ,UAAU;AAAA,MAChB;AACE,aAAK,WAAW,IAAI,cAAc,IAAI;AACtC;AAAA,MACF;AACE,cAAM,IAAI,MAAM,yBAAyB,QAAQ,EAAE;AAAA,IACvD;AAAA,EACF;AAAA,EAEA,MAAa,YAAY,MAA+B;AACtD,QAAI,CAAC,KAAK,UAAU;AAClB,YAAM,IAAI,MAAM,6BAA6B;AAAA,IAC/C;AACA,WAAO,MAAM,KAAK,SAAS,YAAY,IAAI;AAAA,EAC7C;AAAA,EAEA,MAAa,cAAc,SAAiB;AAC1C,QAAI,CAAC,KAAK,UAAU;AAClB,YAAM,IAAI,MAAM,6BAA6B;AAAA,IAC/C;AACA,WAAO,MAAM,KAAK,SAAS,cAAc,OAAO;AAAA,EAClD;AACF;","names":["Provider","HttpsProxyAgent","chat","HttpsProxyAgent","fetchSSE","uuidv4","HttpsProxyAgent","createParser","fetchSSE","uuidv4","HttpsProxyAgent","createParser","fetchSSE","HttpsProxyAgent","createParser","res","uuidv4","fetchSSE","HttpsProxyAgent","createParser","res","uuidv4","fetchSSE","GoogleAuth","HttpsProxyAgent","createParser","GoogleAuth","fetchSSE","HttpsProxyAgent","createParser","res","fetchSSE","HttpsProxyAgent","createParser","fetchSSE","HttpsProxyAgent","createParser","res","fetchSSE","HttpsProxyAgent","createParser","fetchSSE","HttpsProxyAgent","createParser","fetchSSE","uuidv4","HttpsProxyAgent","createParser","fetchSSE","HttpsProxyAgent","createParser","res","uuidv4","item","fetchSSE","HttpsProxyAgent","fetchSSE","HttpsProxyAgent","fetchSSE","uuidv4","HttpsProxyAgent","createParser","fetchSSE","HttpsProxyAgent","uuidv4","createParser","uuidv4","uuidv4","choices","fetchSSE","uuidv4","HttpsProxyAgent","createParser","fetchSSE","HttpsProxyAgent","uuidv4","createParser","fetchSSE","uuidv4","HttpsProxyAgent","createParser","fetchSSE","HttpsProxyAgent","uuidv4","createParser"]} \ No newline at end of file diff --git a/packages/bodhi-adapter/package.json b/packages/bodhi-adapter/package.json index af96644..a9d79c0 100644 --- a/packages/bodhi-adapter/package.json +++ b/packages/bodhi-adapter/package.json @@ -1,6 +1,6 @@ { "name": "@isnolan/bodhi-adapter", - "version": "0.7.1", + "version": "0.7.5", "description": "llms adapter api for bodhi", "main": "index.js", "scripts": { diff --git a/packages/bodhi-adapter/src/provider/google/gemini.ts b/packages/bodhi-adapter/src/provider/google/gemini.ts index 0372921..a422e92 100644 --- a/packages/bodhi-adapter/src/provider/google/gemini.ts +++ b/packages/bodhi-adapter/src/provider/google/gemini.ts @@ -178,6 +178,7 @@ export class GoogleGeminiAPI extends ChatBaseAPI { protected convertChoices(candidates: gemini.Candidate[]): types.chat.Choice[] { const choices: types.chat.Choice[] = []; + try { candidates.map(({ index, content, finishReason }: gemini.Candidate) => { const parts: types.chat.Part[] = []; @@ -192,7 +193,9 @@ export class GoogleGeminiAPI extends ChatBaseAPI { choices.push({ index, role: 'assistant', parts, finish_reason: 'stop' }); }); } catch (err) { + console.log(`->candidates1`, JSON.stringify(candidates, null, 2)); console.warn(err); + console.log(`->candidates2`); } return choices; } diff --git a/packages/bodhi-adapter/src/provider/google/vertex.ts b/packages/bodhi-adapter/src/provider/google/vertex.ts index 975e81b..d2896a3 100644 --- a/packages/bodhi-adapter/src/provider/google/vertex.ts +++ b/packages/bodhi-adapter/src/provider/google/vertex.ts @@ -77,7 +77,11 @@ export class GoogleVertexAPI extends GoogleGeminiAPI { const parser = createParser((event: ParseEvent | ReconnectInterval) => { if (event.type === 'event') { const res = JSON.parse(event.data); - const choices = this.convertChoices(res.candidates); + // TODO: res 可能为空 + if (!res.candidates) { + console.log(`[vertex]debug`, res); + } + const choices = this.convertChoices(res.candidates || []); if (res.usageMetadata) { Object.assign(usage, { prompt_tokens: res.usageMetadata.promptTokenCount, diff --git a/packages/bodhi-adapter/test/aliyun-qwen.test.ts b/packages/bodhi-adapter/test/aliyun-qwen.test.ts index 0c39548..53969db 100644 --- a/packages/bodhi-adapter/test/aliyun-qwen.test.ts +++ b/packages/bodhi-adapter/test/aliyun-qwen.test.ts @@ -19,7 +19,7 @@ describe('chat', () => { it('text: streaming', async () => { const res = await api.sendMessage({ - model: 'qwen1.5-110b-chat', // qwen-turbo + model: 'qwen-turbo', // qwen-turbo messages: [ // { role: 'system', content: 'You are a helpful assistant.' }, // { role: 'user', content: '你好,哪个公园距离我最近?' }, @@ -70,4 +70,19 @@ describe('chat', () => { console.log(`[qwen]muliti`, JSON.stringify(res)); expect(res).toBeInstanceOf(Object); }, 30000); + + it('text: max', async () => { + const res = await api.sendMessage({ + model: 'qwen-max', // qwen-turbo + messages: [{ role: 'user', parts: [{ type: 'text', text: '今天最新AI科技新闻是什么?' }] }], + top_k: 1.0, + // top_p + onProgress: (choices) => { + console.log(`[qwen]streaming`, JSON.stringify(choices)); + expect(choices).toBeInstanceOf(Object); + }, + }); + console.log(`[qwen]`, JSON.stringify(res)); + expect(res).toBeInstanceOf(Object); + }, 30000); });