api.ts 8.9 KB

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