api.ts 9.4 KB

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