api.ts 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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. export const ROLES = ["system", "user", "assistant"] as const;
  24. export type MessageRole = (typeof ROLES)[number];
  25. export const Models = ["gpt-3.5-turbo", "gpt-4"] as const;
  26. export const TTSModels = ["tts-1", "tts-1-hd"] as const;
  27. export type ChatModel = ModelType;
  28. export interface MultimodalContent {
  29. type: "text" | "image_url";
  30. text?: string;
  31. image_url?: {
  32. url: string;
  33. };
  34. }
  35. export interface RequestMessage {
  36. role: MessageRole;
  37. content: string | MultimodalContent[];
  38. }
  39. export interface LLMConfig {
  40. model: string;
  41. providerName?: string;
  42. temperature?: number;
  43. top_p?: number;
  44. stream?: boolean;
  45. presence_penalty?: number;
  46. frequency_penalty?: number;
  47. size?: DalleRequestPayload["size"];
  48. quality?: DalleRequestPayload["quality"];
  49. style?: DalleRequestPayload["style"];
  50. }
  51. export interface SpeechOptions {
  52. model: string;
  53. input: string;
  54. voice: string;
  55. response_format?: string;
  56. speed?: number;
  57. onController?: (controller: AbortController) => void;
  58. }
  59. export interface ChatOptions {
  60. messages: RequestMessage[];
  61. config: LLMConfig;
  62. onUpdate?: (message: string, chunk: string) => void;
  63. onFinish: (message: string) => void;
  64. onError?: (err: Error) => void;
  65. onController?: (controller: AbortController) => void;
  66. onBeforeTool?: (tool: ChatMessageTool) => void;
  67. onAfterTool?: (tool: ChatMessageTool) => void;
  68. }
  69. export interface LLMUsage {
  70. used: number;
  71. total: number;
  72. }
  73. export interface LLMModel {
  74. name: string;
  75. displayName?: string;
  76. available: boolean;
  77. provider: LLMModelProvider;
  78. sorted: number;
  79. }
  80. export interface LLMModelProvider {
  81. id: string;
  82. providerName: string;
  83. providerType: string;
  84. sorted: number;
  85. }
  86. export abstract class LLMApi {
  87. abstract chat(options: ChatOptions): Promise<void>;
  88. abstract speech(options: SpeechOptions): Promise<ArrayBuffer>;
  89. abstract usage(): Promise<LLMUsage>;
  90. abstract models(): Promise<LLMModel[]>;
  91. }
  92. type ProviderName = "openai" | "azure" | "claude" | "palm";
  93. interface Model {
  94. name: string;
  95. provider: ProviderName;
  96. ctxlen: number;
  97. }
  98. interface ChatProvider {
  99. name: ProviderName;
  100. apiConfig: {
  101. baseUrl: string;
  102. apiKey: string;
  103. summaryModel: Model;
  104. };
  105. models: Model[];
  106. chat: () => void;
  107. usage: () => void;
  108. }
  109. export class ClientApi {
  110. public llm: LLMApi;
  111. constructor(provider: ModelProvider = ModelProvider.GPT) {
  112. switch (provider) {
  113. case ModelProvider.GeminiPro:
  114. this.llm = new GeminiProApi();
  115. break;
  116. case ModelProvider.Claude:
  117. this.llm = new ClaudeApi();
  118. break;
  119. case ModelProvider.Ernie:
  120. this.llm = new ErnieApi();
  121. break;
  122. case ModelProvider.Doubao:
  123. this.llm = new DoubaoApi();
  124. break;
  125. case ModelProvider.Qwen:
  126. this.llm = new QwenApi();
  127. break;
  128. case ModelProvider.Hunyuan:
  129. this.llm = new HunyuanApi();
  130. break;
  131. case ModelProvider.Moonshot:
  132. this.llm = new MoonshotApi();
  133. break;
  134. case ModelProvider.Iflytek:
  135. this.llm = new SparkApi();
  136. break;
  137. default:
  138. this.llm = new ChatGPTApi();
  139. }
  140. }
  141. config() {}
  142. prompts() {}
  143. masks() {}
  144. async share(messages: ChatMessage[], avatarUrl: string | null = null) {
  145. const msgs = messages
  146. .map((m) => ({
  147. from: m.role === "user" ? "human" : "gpt",
  148. value: m.content,
  149. }))
  150. .concat([
  151. {
  152. from: "human",
  153. value:
  154. "Share from [NextChat]: https://github.com/Yidadaa/ChatGPT-Next-Web",
  155. },
  156. ]);
  157. // 敬告二开开发者们,为了开源大模型的发展,请不要修改上述消息,此消息用于后续数据清洗使用
  158. // Please do not modify this message
  159. console.log("[Share]", messages, msgs);
  160. const clientConfig = getClientConfig();
  161. const proxyUrl = "/sharegpt";
  162. const rawUrl = "https://sharegpt.com/api/conversations";
  163. const shareUrl = clientConfig?.isApp ? rawUrl : proxyUrl;
  164. const res = await fetch(shareUrl, {
  165. body: JSON.stringify({
  166. avatarUrl,
  167. items: msgs,
  168. }),
  169. headers: {
  170. "Content-Type": "application/json",
  171. },
  172. method: "POST",
  173. });
  174. const resJson = await res.json();
  175. console.log("[Share]", resJson);
  176. if (resJson.id) {
  177. return `https://shareg.pt/${resJson.id}`;
  178. }
  179. }
  180. }
  181. export function getBearerToken(
  182. apiKey: string,
  183. noBearer: boolean = false,
  184. ): string {
  185. return validString(apiKey)
  186. ? `${noBearer ? "" : "Bearer "}${apiKey.trim()}`
  187. : "";
  188. }
  189. export function validString(x: string): boolean {
  190. return x?.length > 0;
  191. }
  192. export function getHeaders(ignoreHeaders: boolean = false) {
  193. const accessStore = useAccessStore.getState();
  194. const chatStore = useChatStore.getState();
  195. let headers: Record<string, string> = {};
  196. if (!ignoreHeaders) {
  197. headers = {
  198. "Content-Type": "application/json",
  199. Accept: "application/json",
  200. };
  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. }