anthropic.ts 11 KB

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