api.ts 7.3 KB

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