api.ts 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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() {
  196. const accessStore = useAccessStore.getState();
  197. const chatStore = useChatStore.getState();
  198. const headers: Record<string, string> = {
  199. "Content-Type": "application/json",
  200. Accept: "application/json",
  201. };
  202. const clientConfig = getClientConfig();
  203. function getConfig() {
  204. const modelConfig = chatStore.currentSession().mask.modelConfig;
  205. const isGoogle = modelConfig.providerName == ServiceProvider.Google;
  206. const isAzure = modelConfig.providerName === ServiceProvider.Azure;
  207. const isAnthropic = modelConfig.providerName === ServiceProvider.Anthropic;
  208. const isBaidu = modelConfig.providerName == ServiceProvider.Baidu;
  209. const isByteDance = modelConfig.providerName === ServiceProvider.ByteDance;
  210. const isAlibaba = modelConfig.providerName === ServiceProvider.Alibaba;
  211. const isMoonshot = modelConfig.providerName === ServiceProvider.Moonshot;
  212. const isIflytek = modelConfig.providerName === ServiceProvider.Iflytek;
  213. const isEnabledAccessControl = accessStore.enabledAccessControl();
  214. const apiKey = isGoogle
  215. ? accessStore.googleApiKey
  216. : isAzure
  217. ? accessStore.azureApiKey
  218. : isAnthropic
  219. ? accessStore.anthropicApiKey
  220. : isByteDance
  221. ? accessStore.bytedanceApiKey
  222. : isAlibaba
  223. ? accessStore.alibabaApiKey
  224. : isMoonshot
  225. ? accessStore.moonshotApiKey
  226. : isIflytek
  227. ? accessStore.iflytekApiKey && accessStore.iflytekApiSecret
  228. ? accessStore.iflytekApiKey + ":" + accessStore.iflytekApiSecret
  229. : ""
  230. : accessStore.openaiApiKey;
  231. return {
  232. isGoogle,
  233. isAzure,
  234. isAnthropic,
  235. isBaidu,
  236. isByteDance,
  237. isAlibaba,
  238. isMoonshot,
  239. isIflytek,
  240. apiKey,
  241. isEnabledAccessControl,
  242. };
  243. }
  244. function getAuthHeader(): string {
  245. return isAzure ? "api-key" : isAnthropic ? "x-api-key" : "Authorization";
  246. }
  247. const {
  248. isGoogle,
  249. isAzure,
  250. isAnthropic,
  251. isBaidu,
  252. apiKey,
  253. isEnabledAccessControl,
  254. } = getConfig();
  255. // when using google api in app, not set auth header
  256. if (isGoogle && clientConfig?.isApp) return headers;
  257. // when using baidu api in app, not set auth header
  258. if (isBaidu && clientConfig?.isApp) return headers;
  259. const authHeader = getAuthHeader();
  260. const bearerToken = getBearerToken(apiKey, isAzure || isAnthropic);
  261. if (bearerToken) {
  262. headers[authHeader] = bearerToken;
  263. } else if (isEnabledAccessControl && validString(accessStore.accessCode)) {
  264. headers["Authorization"] = getBearerToken(
  265. ACCESS_CODE_PREFIX + accessStore.accessCode,
  266. );
  267. }
  268. return headers;
  269. }
  270. export function getClientApi(provider: ServiceProvider): ClientApi {
  271. switch (provider) {
  272. case ServiceProvider.Google:
  273. return new ClientApi(ModelProvider.GeminiPro);
  274. case ServiceProvider.Anthropic:
  275. return new ClientApi(ModelProvider.Claude);
  276. case ServiceProvider.Baidu:
  277. return new ClientApi(ModelProvider.Ernie);
  278. case ServiceProvider.ByteDance:
  279. return new ClientApi(ModelProvider.Doubao);
  280. case ServiceProvider.Alibaba:
  281. return new ClientApi(ModelProvider.Qwen);
  282. case ServiceProvider.Tencent:
  283. return new ClientApi(ModelProvider.Hunyuan);
  284. case ServiceProvider.Moonshot:
  285. return new ClientApi(ModelProvider.Moonshot);
  286. case ServiceProvider.Iflytek:
  287. return new ClientApi(ModelProvider.Iflytek);
  288. default:
  289. return new ClientApi(ModelProvider.GPT);
  290. }
  291. }