anthropic.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. import { ACCESS_CODE_PREFIX, Anthropic, ApiPath } from "@/app/constant";
  2. import {
  3. ChatOptions,
  4. getHeaders,
  5. LLMApi,
  6. MultimodalContent,
  7. SpeechOptions,
  8. TranscriptionOptions,
  9. } from "../api";
  10. import { useAccessStore, useAppConfig, useChatStore } from "@/app/store";
  11. import { getClientConfig } from "@/app/config/client";
  12. import { DEFAULT_API_HOST } from "@/app/constant";
  13. import {
  14. EventStreamContentType,
  15. fetchEventSource,
  16. } from "@fortaine/fetch-event-source";
  17. import Locale from "../../locales";
  18. import { prettyObject } from "@/app/utils/format";
  19. import { getMessageTextContent, isVisionModel } from "@/app/utils";
  20. import { preProcessImageContent } from "@/app/utils/chat";
  21. import { cloudflareAIGatewayUrl } from "@/app/utils/cloudflare";
  22. export type MultiBlockContent = {
  23. type: "image" | "text";
  24. source?: {
  25. type: string;
  26. media_type: string;
  27. data: string;
  28. };
  29. text?: string;
  30. };
  31. export type AnthropicMessage = {
  32. role: (typeof ClaudeMapper)[keyof typeof ClaudeMapper];
  33. content: string | MultiBlockContent[];
  34. };
  35. export interface AnthropicChatRequest {
  36. model: string; // The model that will complete your prompt.
  37. messages: AnthropicMessage[]; // The prompt that you want Claude to complete.
  38. max_tokens: number; // The maximum number of tokens to generate before stopping.
  39. stop_sequences?: string[]; // Sequences that will cause the model to stop generating completion text.
  40. temperature?: number; // Amount of randomness injected into the response.
  41. top_p?: number; // Use nucleus sampling.
  42. top_k?: number; // Only sample from the top K options for each subsequent token.
  43. metadata?: object; // An object describing metadata about the request.
  44. stream?: boolean; // Whether to incrementally stream the response using server-sent events.
  45. }
  46. export interface ChatRequest {
  47. model: string; // The model that will complete your prompt.
  48. prompt: string; // The prompt that you want Claude to complete.
  49. max_tokens_to_sample: number; // The maximum number of tokens to generate before stopping.
  50. stop_sequences?: string[]; // Sequences that will cause the model to stop generating completion text.
  51. temperature?: number; // Amount of randomness injected into the response.
  52. top_p?: number; // Use nucleus sampling.
  53. top_k?: number; // Only sample from the top K options for each subsequent token.
  54. metadata?: object; // An object describing metadata about the request.
  55. stream?: boolean; // Whether to incrementally stream the response using server-sent events.
  56. }
  57. export interface ChatResponse {
  58. completion: string;
  59. stop_reason: "stop_sequence" | "max_tokens";
  60. model: string;
  61. }
  62. export type ChatStreamResponse = ChatResponse & {
  63. stop?: string;
  64. log_id: string;
  65. };
  66. const ClaudeMapper = {
  67. assistant: "assistant",
  68. user: "user",
  69. system: "user",
  70. } as const;
  71. const keys = ["claude-2, claude-instant-1"];
  72. export class ClaudeApi implements LLMApi {
  73. speech(options: SpeechOptions): Promise<ArrayBuffer> {
  74. throw new Error("Method not implemented.");
  75. }
  76. transcription(options: TranscriptionOptions): Promise<string> {
  77. throw new Error("Method not implemented.");
  78. }
  79. extractMessage(res: any) {
  80. console.log("[Response] claude response: ", res);
  81. return res?.content?.[0]?.text;
  82. }
  83. async chat(options: ChatOptions): Promise<void> {
  84. const visionModel = isVisionModel(options.config.model);
  85. const accessStore = useAccessStore.getState();
  86. const shouldStream = !!options.config.stream;
  87. const modelConfig = {
  88. ...useAppConfig.getState().modelConfig,
  89. ...useChatStore.getState().currentSession().mask.modelConfig,
  90. ...{
  91. model: options.config.model,
  92. },
  93. };
  94. // try get base64image from local cache image_url
  95. const messages: ChatOptions["messages"] = [];
  96. for (const v of options.messages) {
  97. const content = await preProcessImageContent(v.content);
  98. messages.push({ role: v.role, content });
  99. }
  100. const keys = ["system", "user"];
  101. // roles must alternate between "user" and "assistant" in claude, so add a fake assistant message between two user messages
  102. for (let i = 0; i < messages.length - 1; i++) {
  103. const message = messages[i];
  104. const nextMessage = messages[i + 1];
  105. if (keys.includes(message.role) && keys.includes(nextMessage.role)) {
  106. messages[i] = [
  107. message,
  108. {
  109. role: "assistant",
  110. content: ";",
  111. },
  112. ] as any;
  113. }
  114. }
  115. const prompt = messages
  116. .flat()
  117. .filter((v) => {
  118. if (!v.content) return false;
  119. if (typeof v.content === "string" && !v.content.trim()) return false;
  120. return true;
  121. })
  122. .map((v) => {
  123. const { role, content } = v;
  124. const insideRole = ClaudeMapper[role] ?? "user";
  125. if (!visionModel || typeof content === "string") {
  126. return {
  127. role: insideRole,
  128. content: getMessageTextContent(v),
  129. };
  130. }
  131. return {
  132. role: insideRole,
  133. content: content
  134. .filter((v) => v.image_url || v.text)
  135. .map(({ type, text, image_url }) => {
  136. if (type === "text") {
  137. return {
  138. type,
  139. text: text!,
  140. };
  141. }
  142. const { url = "" } = image_url || {};
  143. const colonIndex = url.indexOf(":");
  144. const semicolonIndex = url.indexOf(";");
  145. const comma = url.indexOf(",");
  146. const mimeType = url.slice(colonIndex + 1, semicolonIndex);
  147. const encodeType = url.slice(semicolonIndex + 1, comma);
  148. const data = url.slice(comma + 1);
  149. return {
  150. type: "image" as const,
  151. source: {
  152. type: encodeType,
  153. media_type: mimeType,
  154. data,
  155. },
  156. };
  157. }),
  158. };
  159. });
  160. if (prompt[0]?.role === "assistant") {
  161. prompt.unshift({
  162. role: "user",
  163. content: ";",
  164. });
  165. }
  166. const requestBody: AnthropicChatRequest = {
  167. messages: prompt,
  168. stream: shouldStream,
  169. model: modelConfig.model,
  170. max_tokens: modelConfig.max_tokens,
  171. temperature: modelConfig.temperature,
  172. top_p: modelConfig.top_p,
  173. // top_k: modelConfig.top_k,
  174. top_k: 5,
  175. };
  176. const path = this.path(Anthropic.ChatPath);
  177. const controller = new AbortController();
  178. options.onController?.(controller);
  179. const payload = {
  180. method: "POST",
  181. body: JSON.stringify(requestBody),
  182. signal: controller.signal,
  183. headers: {
  184. ...getHeaders(), // get common headers
  185. "anthropic-version": accessStore.anthropicApiVersion,
  186. // do not send `anthropicApiKey` in browser!!!
  187. // Authorization: getAuthKey(accessStore.anthropicApiKey),
  188. },
  189. };
  190. if (shouldStream) {
  191. try {
  192. const context = {
  193. text: "",
  194. finished: false,
  195. };
  196. const finish = () => {
  197. if (!context.finished) {
  198. options.onFinish(context.text);
  199. context.finished = true;
  200. }
  201. };
  202. controller.signal.onabort = finish;
  203. fetchEventSource(path, {
  204. ...payload,
  205. async onopen(res) {
  206. const contentType = res.headers.get("content-type");
  207. console.log("response content type: ", contentType);
  208. if (contentType?.startsWith("text/plain")) {
  209. context.text = await res.clone().text();
  210. return finish();
  211. }
  212. if (
  213. !res.ok ||
  214. !res.headers
  215. .get("content-type")
  216. ?.startsWith(EventStreamContentType) ||
  217. res.status !== 200
  218. ) {
  219. const responseTexts = [context.text];
  220. let extraInfo = await res.clone().text();
  221. try {
  222. const resJson = await res.clone().json();
  223. extraInfo = prettyObject(resJson);
  224. } catch {}
  225. if (res.status === 401) {
  226. responseTexts.push(Locale.Error.Unauthorized);
  227. }
  228. if (extraInfo) {
  229. responseTexts.push(extraInfo);
  230. }
  231. context.text = responseTexts.join("\n\n");
  232. return finish();
  233. }
  234. },
  235. onmessage(msg) {
  236. let chunkJson:
  237. | undefined
  238. | {
  239. type: "content_block_delta" | "content_block_stop";
  240. delta?: {
  241. type: "text_delta";
  242. text: string;
  243. };
  244. index: number;
  245. };
  246. try {
  247. chunkJson = JSON.parse(msg.data);
  248. } catch (e) {
  249. console.error("[Response] parse error", msg.data);
  250. }
  251. if (!chunkJson || chunkJson.type === "content_block_stop") {
  252. return finish();
  253. }
  254. const { delta } = chunkJson;
  255. if (delta?.text) {
  256. context.text += delta.text;
  257. options.onUpdate?.(context.text, delta.text);
  258. }
  259. },
  260. onclose() {
  261. finish();
  262. },
  263. onerror(e) {
  264. options.onError?.(e);
  265. throw e;
  266. },
  267. openWhenHidden: true,
  268. });
  269. } catch (e) {
  270. console.error("failed to chat", e);
  271. options.onError?.(e as Error);
  272. }
  273. } else {
  274. try {
  275. controller.signal.onabort = () => options.onFinish("");
  276. const res = await fetch(path, payload);
  277. const resJson = await res.json();
  278. const message = this.extractMessage(resJson);
  279. options.onFinish(message);
  280. } catch (e) {
  281. console.error("failed to chat", e);
  282. options.onError?.(e as Error);
  283. }
  284. }
  285. }
  286. async usage() {
  287. return {
  288. used: 0,
  289. total: 0,
  290. };
  291. }
  292. async models() {
  293. // const provider = {
  294. // id: "anthropic",
  295. // providerName: "Anthropic",
  296. // providerType: "anthropic",
  297. // };
  298. return [
  299. // {
  300. // name: "claude-instant-1.2",
  301. // available: true,
  302. // provider,
  303. // },
  304. // {
  305. // name: "claude-2.0",
  306. // available: true,
  307. // provider,
  308. // },
  309. // {
  310. // name: "claude-2.1",
  311. // available: true,
  312. // provider,
  313. // },
  314. // {
  315. // name: "claude-3-opus-20240229",
  316. // available: true,
  317. // provider,
  318. // },
  319. // {
  320. // name: "claude-3-sonnet-20240229",
  321. // available: true,
  322. // provider,
  323. // },
  324. // {
  325. // name: "claude-3-haiku-20240307",
  326. // available: true,
  327. // provider,
  328. // },
  329. ];
  330. }
  331. path(path: string): string {
  332. const accessStore = useAccessStore.getState();
  333. let baseUrl: string = "";
  334. if (accessStore.useCustomConfig) {
  335. baseUrl = accessStore.anthropicUrl;
  336. }
  337. // if endpoint is empty, use default endpoint
  338. if (baseUrl.trim().length === 0) {
  339. const isApp = !!getClientConfig()?.isApp;
  340. baseUrl = isApp
  341. ? DEFAULT_API_HOST + "/api/proxy/anthropic"
  342. : ApiPath.Anthropic;
  343. }
  344. if (!baseUrl.startsWith("http") && !baseUrl.startsWith("/api")) {
  345. baseUrl = "https://" + baseUrl;
  346. }
  347. baseUrl = trimEnd(baseUrl, "/");
  348. // try rebuild url, when using cloudflare ai gateway in client
  349. return cloudflareAIGatewayUrl(`${baseUrl}/${path}`);
  350. }
  351. }
  352. function trimEnd(s: string, end = " ") {
  353. if (end.length === 0) return s;
  354. while (s.endsWith(end)) {
  355. s = s.slice(0, -end.length);
  356. }
  357. return s;
  358. }