api.ts 7.5 KB

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