api.ts 8.2 KB

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