api.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. import { getClientConfig } from "../config/client";
  2. import {
  3. ACCESS_CODE_PREFIX,
  4. ModelProvider,
  5. ServiceProvider,
  6. } from "../constant";
  7. import {
  8. ChatMessageTool,
  9. ChatMessage,
  10. ModelType,
  11. useAccessStore,
  12. useChatStore,
  13. } from "../store";
  14. import { ChatGPTApi, DalleRequestPayload } from "./platforms/openai";
  15. import { GeminiProApi } from "./platforms/google";
  16. import { ClaudeApi } from "./platforms/anthropic";
  17. import { ErnieApi } from "./platforms/baidu";
  18. import { DoubaoApi } from "./platforms/bytedance";
  19. import { QwenApi } from "./platforms/alibaba";
  20. import { HunyuanApi } from "./platforms/tencent";
  21. import { MoonshotApi } from "./platforms/moonshot";
  22. import { SparkApi } from "./platforms/iflytek";
  23. import { DeepSeekApi } from "./platforms/deepseek";
  24. import { XAIApi } from "./platforms/xai";
  25. import { ChatGLMApi } from "./platforms/glm";
  26. import { SiliconflowApi } from "./platforms/siliconflow";
  27. export const ROLES = ["system", "user", "assistant"] as const;
  28. export type MessageRole = (typeof ROLES)[number];
  29. export const Models = ["gpt-3.5-turbo", "gpt-4"] as const;
  30. export const TTSModels = ["tts-1", "tts-1-hd"] as const;
  31. export type ChatModel = ModelType;
  32. export interface MultimodalContent {
  33. type: "text" | "image_url";
  34. text?: string;
  35. image_url?: {
  36. url: string;
  37. };
  38. }
  39. export interface MultimodalContentForAlibaba {
  40. text?: string;
  41. image?: string;
  42. }
  43. export interface RequestMessage {
  44. role: MessageRole;
  45. content: string | MultimodalContent[];
  46. }
  47. export interface LLMConfig {
  48. model: string;
  49. providerName?: string;
  50. temperature?: number;
  51. top_p?: number;
  52. stream?: boolean;
  53. presence_penalty?: number;
  54. frequency_penalty?: number;
  55. size?: DalleRequestPayload["size"];
  56. quality?: DalleRequestPayload["quality"];
  57. style?: DalleRequestPayload["style"];
  58. }
  59. export interface SpeechOptions {
  60. model: string;
  61. input: string;
  62. voice: string;
  63. response_format?: string;
  64. speed?: number;
  65. onController?: (controller: AbortController) => void;
  66. }
  67. export interface ChatOptions {
  68. messages: RequestMessage[];
  69. config: LLMConfig;
  70. onUpdate?: (message: string, chunk: string) => void;
  71. onFinish: (message: string, responseRes: Response) => void;
  72. onError?: (err: Error) => void;
  73. onController?: (controller: AbortController) => void;
  74. onBeforeTool?: (tool: ChatMessageTool) => void;
  75. onAfterTool?: (tool: ChatMessageTool) => void;
  76. }
  77. export interface LLMUsage {
  78. used: number;
  79. total: number;
  80. }
  81. export interface LLMModel {
  82. name: string;
  83. displayName?: string;
  84. available: boolean;
  85. provider: LLMModelProvider;
  86. sorted: number;
  87. }
  88. export interface LLMModelProvider {
  89. id: string;
  90. providerName: string;
  91. providerType: string;
  92. sorted: number;
  93. }
  94. export abstract class LLMApi {
  95. abstract chat(options: ChatOptions): Promise<void>;
  96. abstract speech(options: SpeechOptions): Promise<ArrayBuffer>;
  97. abstract usage(): Promise<LLMUsage>;
  98. abstract models(): Promise<LLMModel[]>;
  99. }
  100. type ProviderName = "openai" | "azure" | "claude" | "palm";
  101. interface Model {
  102. name: string;
  103. provider: ProviderName;
  104. ctxlen: number;
  105. }
  106. interface ChatProvider {
  107. name: ProviderName;
  108. apiConfig: {
  109. baseUrl: string;
  110. apiKey: string;
  111. summaryModel: Model;
  112. };
  113. models: Model[];
  114. chat: () => void;
  115. usage: () => void;
  116. }
  117. export class ClientApi {
  118. public llm: LLMApi;
  119. constructor(provider: ModelProvider = ModelProvider.GPT) {
  120. switch (provider) {
  121. case ModelProvider.GeminiPro:
  122. this.llm = new GeminiProApi();
  123. break;
  124. case ModelProvider.Claude:
  125. this.llm = new ClaudeApi();
  126. break;
  127. case ModelProvider.Ernie:
  128. this.llm = new ErnieApi();
  129. break;
  130. case ModelProvider.Doubao:
  131. this.llm = new DoubaoApi();
  132. break;
  133. case ModelProvider.Qwen:
  134. this.llm = new QwenApi();
  135. break;
  136. case ModelProvider.Hunyuan:
  137. this.llm = new HunyuanApi();
  138. break;
  139. case ModelProvider.Moonshot:
  140. this.llm = new MoonshotApi();
  141. break;
  142. case ModelProvider.Iflytek:
  143. this.llm = new SparkApi();
  144. break;
  145. case ModelProvider.DeepSeek:
  146. this.llm = new DeepSeekApi();
  147. break;
  148. case ModelProvider.XAI:
  149. this.llm = new XAIApi();
  150. break;
  151. case ModelProvider.ChatGLM:
  152. this.llm = new ChatGLMApi();
  153. break;
  154. case ModelProvider.SiliconFlow:
  155. this.llm = new SiliconflowApi();
  156. break;
  157. default:
  158. this.llm = new ChatGPTApi();
  159. }
  160. }
  161. config() {}
  162. prompts() {}
  163. masks() {}
  164. async share(messages: ChatMessage[], avatarUrl: string | null = null) {
  165. const msgs = messages
  166. .map((m) => ({
  167. from: m.role === "user" ? "human" : "gpt",
  168. value: m.content,
  169. }))
  170. .concat([
  171. {
  172. from: "human",
  173. value:
  174. "Share from [NextChat]: https://github.com/Yidadaa/ChatGPT-Next-Web",
  175. },
  176. ]);
  177. // 敬告二开开发者们,为了开源大模型的发展,请不要修改上述消息,此消息用于后续数据清洗使用
  178. // Please do not modify this message
  179. console.log("[Share]", messages, msgs);
  180. const clientConfig = getClientConfig();
  181. const proxyUrl = "/sharegpt";
  182. const rawUrl = "https://sharegpt.com/api/conversations";
  183. const shareUrl = clientConfig?.isApp ? rawUrl : proxyUrl;
  184. const res = await fetch(shareUrl, {
  185. body: JSON.stringify({
  186. avatarUrl,
  187. items: msgs,
  188. }),
  189. headers: {
  190. "Content-Type": "application/json",
  191. },
  192. method: "POST",
  193. });
  194. const resJson = await res.json();
  195. console.log("[Share]", resJson);
  196. if (resJson.id) {
  197. return `https://shareg.pt/${resJson.id}`;
  198. }
  199. }
  200. }
  201. export function getBearerToken(
  202. apiKey: string,
  203. noBearer: boolean = false,
  204. ): string {
  205. return validString(apiKey)
  206. ? `${noBearer ? "" : "Bearer "}${apiKey.trim()}`
  207. : "";
  208. }
  209. export function validString(x: string): boolean {
  210. return x?.length > 0;
  211. }
  212. export function getHeaders(ignoreHeaders: boolean = false) {
  213. const accessStore = useAccessStore.getState();
  214. const chatStore = useChatStore.getState();
  215. let headers: Record<string, string> = {};
  216. if (!ignoreHeaders) {
  217. headers = {
  218. "Content-Type": "application/json",
  219. Accept: "application/json",
  220. };
  221. }
  222. const clientConfig = getClientConfig();
  223. function getConfig() {
  224. const modelConfig = chatStore.currentSession().mask.modelConfig;
  225. const isGoogle = modelConfig.providerName === ServiceProvider.Google;
  226. const isAzure = modelConfig.providerName === ServiceProvider.Azure;
  227. const isAnthropic = modelConfig.providerName === ServiceProvider.Anthropic;
  228. const isBaidu = modelConfig.providerName == ServiceProvider.Baidu;
  229. const isByteDance = modelConfig.providerName === ServiceProvider.ByteDance;
  230. const isAlibaba = modelConfig.providerName === ServiceProvider.Alibaba;
  231. const isMoonshot = modelConfig.providerName === ServiceProvider.Moonshot;
  232. const isIflytek = modelConfig.providerName === ServiceProvider.Iflytek;
  233. const isDeepSeek = modelConfig.providerName === ServiceProvider.DeepSeek;
  234. const isXAI = modelConfig.providerName === ServiceProvider.XAI;
  235. const isChatGLM = modelConfig.providerName === ServiceProvider.ChatGLM;
  236. const isSiliconFlow =
  237. modelConfig.providerName === ServiceProvider.SiliconFlow;
  238. const isEnabledAccessControl = accessStore.enabledAccessControl();
  239. const apiKey = isGoogle
  240. ? accessStore.googleApiKey
  241. : isAzure
  242. ? accessStore.azureApiKey
  243. : isAnthropic
  244. ? accessStore.anthropicApiKey
  245. : isByteDance
  246. ? accessStore.bytedanceApiKey
  247. : isAlibaba
  248. ? accessStore.alibabaApiKey
  249. : isMoonshot
  250. ? accessStore.moonshotApiKey
  251. : isXAI
  252. ? accessStore.xaiApiKey
  253. : isDeepSeek
  254. ? accessStore.deepseekApiKey
  255. : isChatGLM
  256. ? accessStore.chatglmApiKey
  257. : isSiliconFlow
  258. ? accessStore.siliconflowApiKey
  259. : isIflytek
  260. ? accessStore.iflytekApiKey && accessStore.iflytekApiSecret
  261. ? accessStore.iflytekApiKey + ":" + accessStore.iflytekApiSecret
  262. : ""
  263. : accessStore.openaiApiKey;
  264. return {
  265. isGoogle,
  266. isAzure,
  267. isAnthropic,
  268. isBaidu,
  269. isByteDance,
  270. isAlibaba,
  271. isMoonshot,
  272. isIflytek,
  273. isDeepSeek,
  274. isXAI,
  275. isChatGLM,
  276. isSiliconFlow,
  277. apiKey,
  278. isEnabledAccessControl,
  279. };
  280. }
  281. function getAuthHeader(): string {
  282. return isAzure
  283. ? "api-key"
  284. : isAnthropic
  285. ? "x-api-key"
  286. : isGoogle
  287. ? "x-goog-api-key"
  288. : "Authorization";
  289. }
  290. const {
  291. isGoogle,
  292. isAzure,
  293. isAnthropic,
  294. isBaidu,
  295. isByteDance,
  296. isAlibaba,
  297. isMoonshot,
  298. isIflytek,
  299. isDeepSeek,
  300. isXAI,
  301. isChatGLM,
  302. isSiliconFlow,
  303. apiKey,
  304. isEnabledAccessControl,
  305. } = getConfig();
  306. // when using baidu api in app, not set auth header
  307. if (isBaidu && clientConfig?.isApp) return headers;
  308. const authHeader = getAuthHeader();
  309. const bearerToken = getBearerToken(
  310. apiKey,
  311. isAzure || isAnthropic || isGoogle,
  312. );
  313. if (bearerToken) {
  314. headers[authHeader] = bearerToken;
  315. } else if (isEnabledAccessControl && validString(accessStore.accessCode)) {
  316. headers["Authorization"] = getBearerToken(
  317. ACCESS_CODE_PREFIX + accessStore.accessCode,
  318. );
  319. }
  320. return headers;
  321. }
  322. export function getClientApi(provider: ServiceProvider): ClientApi {
  323. switch (provider) {
  324. case ServiceProvider.Google:
  325. return new ClientApi(ModelProvider.GeminiPro);
  326. case ServiceProvider.Anthropic:
  327. return new ClientApi(ModelProvider.Claude);
  328. case ServiceProvider.Baidu:
  329. return new ClientApi(ModelProvider.Ernie);
  330. case ServiceProvider.ByteDance:
  331. return new ClientApi(ModelProvider.Doubao);
  332. case ServiceProvider.Alibaba:
  333. return new ClientApi(ModelProvider.Qwen);
  334. case ServiceProvider.Tencent:
  335. return new ClientApi(ModelProvider.Hunyuan);
  336. case ServiceProvider.Moonshot:
  337. return new ClientApi(ModelProvider.Moonshot);
  338. case ServiceProvider.Iflytek:
  339. return new ClientApi(ModelProvider.Iflytek);
  340. case ServiceProvider.DeepSeek:
  341. return new ClientApi(ModelProvider.DeepSeek);
  342. case ServiceProvider.XAI:
  343. return new ClientApi(ModelProvider.XAI);
  344. case ServiceProvider.ChatGLM:
  345. return new ClientApi(ModelProvider.ChatGLM);
  346. case ServiceProvider.SiliconFlow:
  347. return new ClientApi(ModelProvider.SiliconFlow);
  348. default:
  349. return new ClientApi(ModelProvider.GPT);
  350. }
  351. }