Electron Forge【实战】阿里百炼大模型 —— AI 聊天
获取 apiKey
登录并开通阿里云百炼
https://bailian.console.aliyun.com/#/home
新人有半年免费的使用福利,在模型详情中,可以查看剩余的免费额度
https://bailian.console.aliyun.com/?tab=model#/model-market/detail/qwen-turbo
在下方链接中创建 apiKey
https://bailian.console.aliyun.com/?tab=model#/api-key
安装 OpenAI SDK
npm install openai
src/providers/OpenAIProvider.ts
import OpenAI from 'openai'interface ChatMessageProps {role: string;content: string;
}interface UniversalChunkProps {is_end: boolean;result: string;
}export class OpenAIProvider {private client: OpenAI;constructor(apiKey: string, baseURL: string) {this.client = new OpenAI({apiKey,baseURL})}async chat(messages: ChatMessageProps[], model: string) {const stream = await this.client.chat.completions.create({model,messages,stream: true})const self = thisreturn {async *[Symbol.asyncIterator]() {for await (const chunk of stream) {yield self.transformResponse(chunk)}}}}protected transformResponse(chunk: OpenAI.Chat.Completions.ChatCompletionChunk): UniversalChunkProps {const choice = chunk.choices[0]return {is_end: choice.finish_reason === 'stop',result: choice.delta.content || ''}}
}
src/providers/createProvider.ts
import { QianfanProvider } from "./QianfanProvider";
import { OpenAIProvider } from './OpenAIProvider'export function createProvider(providerName: string) {const providerConfigs = {aliyun: {apiKey: "换成第一步获取的apiKey",baseUrl: "https://dashscope.aliyuncs.com/compatible-mode/v1",}};// 为了解决类型错误,先进行类型断言,确保可以通过 providerName 访问 providerConfigsconst providerConfig = (providerConfigs as { [key: string]: any })[providerName];switch (providerName) {case "qianfan":if (!providerConfig.accessKey || !providerConfig.secretKey) {throw new Error("缺少千帆API配置:请在设置中配置 accessKey 和 secretKey");}return new QianfanProvider(providerConfig.accessKey,providerConfig.secretKey);case 'aliyun':if (!providerConfig.apiKey || !providerConfig.baseUrl) {throw new Error('缺少阿里云百炼API配置:请在设置中配置 apiKey 和 baseUrl')}return new OpenAIProvider(providerConfig.apiKey, providerConfig.baseUrl)default:throw new Error(`不支持的AI服务提供商: ${providerName}`);}
}
其他通用代码见
https://blog.csdn.net/weixin_41192489/article/details/147492144
效果预览