api.ts 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  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. export const ROLES = ["system", "user", "assistant"] as const;
  12. export type MessageRole = (typeof ROLES)[number];
  13. export const Models = ["gpt-3.5-turbo", "gpt-4"] as const;
  14. export type ChatModel = ModelType;
  15. export interface RequestMessage {
  16. role: MessageRole;
  17. content: string;
  18. }
  19. export interface LLMConfig {
  20. model: string;
  21. temperature?: number;
  22. top_p?: number;
  23. stream?: boolean;
  24. presence_penalty?: number;
  25. frequency_penalty?: number;
  26. }
  27. export interface ChatOptions {
  28. messages: RequestMessage[];
  29. config: LLMConfig;
  30. onUpdate?: (message: string, chunk: string) => void;
  31. onFinish: (message: string) => void;
  32. onError?: (err: Error) => void;
  33. onController?: (controller: AbortController) => void;
  34. }
  35. export interface LLMUsage {
  36. used: number;
  37. total: number;
  38. }
  39. export interface LLMModel {
  40. name: string;
  41. available: boolean;
  42. provider: LLMModelProvider;
  43. }
  44. export interface LLMModelProvider {
  45. id: string;
  46. providerName: string;
  47. providerType: string;
  48. }
  49. export abstract class LLMApi {
  50. abstract chat(options: ChatOptions): Promise<void>;
  51. abstract usage(): Promise<LLMUsage>;
  52. abstract models(): Promise<LLMModel[]>;
  53. }
  54. type ProviderName = "openai" | "azure" | "claude" | "palm";
  55. interface Model {
  56. name: string;
  57. provider: ProviderName;
  58. ctxlen: number;
  59. }
  60. interface ChatProvider {
  61. name: ProviderName;
  62. apiConfig: {
  63. baseUrl: string;
  64. apiKey: string;
  65. summaryModel: Model;
  66. };
  67. models: Model[];
  68. chat: () => void;
  69. usage: () => void;
  70. }
  71. export class ClientApi {
  72. public llm: LLMApi;
  73. constructor(provider: ModelProvider = ModelProvider.GPT) {
  74. if (provider === ModelProvider.GeminiPro) {
  75. this.llm = new GeminiProApi();
  76. return;
  77. }
  78. this.llm = new ChatGPTApi();
  79. }
  80. config() {}
  81. prompts() {}
  82. masks() {}
  83. async share(messages: ChatMessage[], avatarUrl: string | null = null) {
  84. const msgs = messages
  85. .map((m) => ({
  86. from: m.role === "user" ? "human" : "gpt",
  87. value: m.content,
  88. }))
  89. .concat([
  90. {
  91. from: "human",
  92. value:
  93. "Share from [NextChat]: https://github.com/Yidadaa/ChatGPT-Next-Web",
  94. },
  95. ]);
  96. // 敬告二开开发者们,为了开源大模型的发展,请不要修改上述消息,此消息用于后续数据清洗使用
  97. // Please do not modify this message
  98. console.log("[Share]", messages, msgs);
  99. const clientConfig = getClientConfig();
  100. const proxyUrl = "/sharegpt";
  101. const rawUrl = "https://sharegpt.com/api/conversations";
  102. const shareUrl = clientConfig?.isApp ? rawUrl : proxyUrl;
  103. const res = await fetch(shareUrl, {
  104. body: JSON.stringify({
  105. avatarUrl,
  106. items: msgs,
  107. }),
  108. headers: {
  109. "Content-Type": "application/json",
  110. },
  111. method: "POST",
  112. });
  113. const resJson = await res.json();
  114. console.log("[Share]", resJson);
  115. if (resJson.id) {
  116. return `https://shareg.pt/${resJson.id}`;
  117. }
  118. }
  119. }
  120. export function getHeaders() {
  121. const accessStore = useAccessStore.getState();
  122. const headers: Record<string, string> = {
  123. "Content-Type": "application/json",
  124. "x-requested-with": "XMLHttpRequest",
  125. Accept: "application/json",
  126. };
  127. const modelConfig = useChatStore.getState().currentSession().mask.modelConfig;
  128. const isGoogle = modelConfig.model.startsWith("gemini");
  129. const isAzure = accessStore.provider === ServiceProvider.Azure;
  130. const authHeader = isAzure ? "api-key" : "Authorization";
  131. const apiKey = isGoogle
  132. ? accessStore.googleApiKey
  133. : isAzure
  134. ? accessStore.azureApiKey
  135. : accessStore.openaiApiKey;
  136. const clientConfig = getClientConfig();
  137. const makeBearer = (s: string) => `${isAzure ? "" : "Bearer "}${s.trim()}`;
  138. const validString = (x: string) => x && x.length > 0;
  139. // when using google api in app, not set auth header
  140. if (!(isGoogle && clientConfig?.isApp)) {
  141. // use user's api key first
  142. if (validString(apiKey)) {
  143. headers[authHeader] = makeBearer(apiKey);
  144. } else if (
  145. accessStore.enabledAccessControl() &&
  146. validString(accessStore.accessCode)
  147. ) {
  148. headers[authHeader] = makeBearer(
  149. ACCESS_CODE_PREFIX + accessStore.accessCode,
  150. );
  151. }
  152. }
  153. return headers;
  154. }