api.ts 8.3 KB

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