api.ts 8.3 KB

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