anthropic.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. import { ACCESS_CODE_PREFIX, Anthropic, ApiPath } from "@/app/constant";
  2. import { ChatOptions, getHeaders, LLMApi, MultimodalContent } from "../api";
  3. import {
  4. useAccessStore,
  5. useAppConfig,
  6. useChatStore,
  7. usePluginStore,
  8. ChatMessageTool,
  9. } from "@/app/store";
  10. import { getClientConfig } from "@/app/config/client";
  11. import { DEFAULT_API_HOST } from "@/app/constant";
  12. import {
  13. EventStreamContentType,
  14. fetchEventSource,
  15. } from "@fortaine/fetch-event-source";
  16. import Locale from "../../locales";
  17. import { prettyObject } from "@/app/utils/format";
  18. import { getMessageTextContent, isVisionModel } from "@/app/utils";
  19. import { preProcessImageContent, stream } from "@/app/utils/chat";
  20. import { cloudflareAIGatewayUrl } from "@/app/utils/cloudflare";
  21. import { RequestPayload } from "./openai";
  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. extractMessage(res: any) {
  74. console.log("[Response] claude response: ", res);
  75. return res?.content?.[0]?.text;
  76. }
  77. async chat(options: ChatOptions): Promise<void> {
  78. const visionModel = isVisionModel(options.config.model);
  79. const accessStore = useAccessStore.getState();
  80. const shouldStream = !!options.config.stream;
  81. const modelConfig = {
  82. ...useAppConfig.getState().modelConfig,
  83. ...useChatStore.getState().currentSession().mask.modelConfig,
  84. ...{
  85. model: options.config.model,
  86. },
  87. };
  88. // try get base64image from local cache image_url
  89. const messages: ChatOptions["messages"] = [];
  90. for (const v of options.messages) {
  91. const content = await preProcessImageContent(v.content);
  92. messages.push({ role: v.role, content });
  93. }
  94. const keys = ["system", "user"];
  95. // roles must alternate between "user" and "assistant" in claude, so add a fake assistant message between two user messages
  96. for (let i = 0; i < messages.length - 1; i++) {
  97. const message = messages[i];
  98. const nextMessage = messages[i + 1];
  99. if (keys.includes(message.role) && keys.includes(nextMessage.role)) {
  100. messages[i] = [
  101. message,
  102. {
  103. role: "assistant",
  104. content: ";",
  105. },
  106. ] as any;
  107. }
  108. }
  109. const prompt = messages
  110. .flat()
  111. .filter((v) => {
  112. if (!v.content) return false;
  113. if (typeof v.content === "string" && !v.content.trim()) return false;
  114. return true;
  115. })
  116. .map((v) => {
  117. const { role, content } = v;
  118. const insideRole = ClaudeMapper[role] ?? "user";
  119. if (!visionModel || typeof content === "string") {
  120. return {
  121. role: insideRole,
  122. content: getMessageTextContent(v),
  123. };
  124. }
  125. return {
  126. role: insideRole,
  127. content: content
  128. .filter((v) => v.image_url || v.text)
  129. .map(({ type, text, image_url }) => {
  130. if (type === "text") {
  131. return {
  132. type,
  133. text: text!,
  134. };
  135. }
  136. const { url = "" } = image_url || {};
  137. const colonIndex = url.indexOf(":");
  138. const semicolonIndex = url.indexOf(";");
  139. const comma = url.indexOf(",");
  140. const mimeType = url.slice(colonIndex + 1, semicolonIndex);
  141. const encodeType = url.slice(semicolonIndex + 1, comma);
  142. const data = url.slice(comma + 1);
  143. return {
  144. type: "image" as const,
  145. source: {
  146. type: encodeType,
  147. media_type: mimeType,
  148. data,
  149. },
  150. };
  151. }),
  152. };
  153. });
  154. if (prompt[0]?.role === "assistant") {
  155. prompt.unshift({
  156. role: "user",
  157. content: ";",
  158. });
  159. }
  160. const requestBody: AnthropicChatRequest = {
  161. messages: prompt,
  162. stream: shouldStream,
  163. model: modelConfig.model,
  164. max_tokens: modelConfig.max_tokens,
  165. temperature: modelConfig.temperature,
  166. top_p: modelConfig.top_p,
  167. // top_k: modelConfig.top_k,
  168. top_k: 5,
  169. };
  170. const path = this.path(Anthropic.ChatPath);
  171. const controller = new AbortController();
  172. options.onController?.(controller);
  173. if (shouldStream) {
  174. let index = -1;
  175. const [tools, funcs] = usePluginStore
  176. .getState()
  177. .getAsTools(
  178. useChatStore.getState().currentSession().mask?.plugin as string[],
  179. );
  180. return stream(
  181. path,
  182. requestBody,
  183. {
  184. ...getHeaders(),
  185. "anthropic-version": accessStore.anthropicApiVersion,
  186. },
  187. // @ts-ignore
  188. tools.map((tool) => ({
  189. name: tool?.function?.name,
  190. description: tool?.function?.description,
  191. input_schema: tool?.function?.parameters,
  192. })),
  193. funcs,
  194. controller,
  195. // parseSSE
  196. (text: string, runTools: ChatMessageTool[]) => {
  197. // console.log("parseSSE", text, runTools);
  198. let chunkJson:
  199. | undefined
  200. | {
  201. type: "content_block_delta" | "content_block_stop";
  202. content_block?: {
  203. type: "tool_use";
  204. id: string;
  205. name: string;
  206. };
  207. delta?: {
  208. type: "text_delta" | "input_json_delta";
  209. text?: string;
  210. partial_json?: string;
  211. };
  212. index: number;
  213. };
  214. chunkJson = JSON.parse(text);
  215. if (chunkJson?.content_block?.type == "tool_use") {
  216. index += 1;
  217. const id = chunkJson?.content_block.id;
  218. const name = chunkJson?.content_block.name;
  219. runTools.push({
  220. id,
  221. type: "function",
  222. function: {
  223. name,
  224. arguments: "",
  225. },
  226. });
  227. }
  228. if (
  229. chunkJson?.delta?.type == "input_json_delta" &&
  230. chunkJson?.delta?.partial_json
  231. ) {
  232. // @ts-ignore
  233. runTools[index]["function"]["arguments"] +=
  234. chunkJson?.delta?.partial_json;
  235. }
  236. return chunkJson?.delta?.text;
  237. },
  238. // processToolMessage, include tool_calls message and tool call results
  239. (
  240. requestPayload: RequestPayload,
  241. toolCallMessage: any,
  242. toolCallResult: any[],
  243. ) => {
  244. // reset index value
  245. index = -1;
  246. // @ts-ignore
  247. requestPayload?.messages?.splice(
  248. // @ts-ignore
  249. requestPayload?.messages?.length,
  250. 0,
  251. {
  252. role: "assistant",
  253. content: toolCallMessage.tool_calls.map(
  254. (tool: ChatMessageTool) => ({
  255. type: "tool_use",
  256. id: tool.id,
  257. name: tool?.function?.name,
  258. input: tool?.function?.arguments
  259. ? JSON.parse(tool?.function?.arguments)
  260. : {},
  261. }),
  262. ),
  263. },
  264. // @ts-ignore
  265. ...toolCallResult.map((result) => ({
  266. role: "user",
  267. content: [
  268. {
  269. type: "tool_result",
  270. tool_use_id: result.tool_call_id,
  271. content: result.content,
  272. },
  273. ],
  274. })),
  275. );
  276. },
  277. options,
  278. );
  279. } else {
  280. const payload = {
  281. method: "POST",
  282. body: JSON.stringify(requestBody),
  283. signal: controller.signal,
  284. headers: {
  285. ...getHeaders(), // get common headers
  286. "anthropic-version": accessStore.anthropicApiVersion,
  287. // do not send `anthropicApiKey` in browser!!!
  288. // Authorization: getAuthKey(accessStore.anthropicApiKey),
  289. },
  290. };
  291. try {
  292. controller.signal.onabort = () => options.onFinish("");
  293. const res = await fetch(path, payload);
  294. const resJson = await res.json();
  295. const message = this.extractMessage(resJson);
  296. options.onFinish(message);
  297. } catch (e) {
  298. console.error("failed to chat", e);
  299. options.onError?.(e as Error);
  300. }
  301. }
  302. }
  303. async usage() {
  304. return {
  305. used: 0,
  306. total: 0,
  307. };
  308. }
  309. async models() {
  310. // const provider = {
  311. // id: "anthropic",
  312. // providerName: "Anthropic",
  313. // providerType: "anthropic",
  314. // };
  315. return [
  316. // {
  317. // name: "claude-instant-1.2",
  318. // available: true,
  319. // provider,
  320. // },
  321. // {
  322. // name: "claude-2.0",
  323. // available: true,
  324. // provider,
  325. // },
  326. // {
  327. // name: "claude-2.1",
  328. // available: true,
  329. // provider,
  330. // },
  331. // {
  332. // name: "claude-3-opus-20240229",
  333. // available: true,
  334. // provider,
  335. // },
  336. // {
  337. // name: "claude-3-sonnet-20240229",
  338. // available: true,
  339. // provider,
  340. // },
  341. // {
  342. // name: "claude-3-haiku-20240307",
  343. // available: true,
  344. // provider,
  345. // },
  346. ];
  347. }
  348. path(path: string): string {
  349. const accessStore = useAccessStore.getState();
  350. let baseUrl: string = "";
  351. if (accessStore.useCustomConfig) {
  352. baseUrl = accessStore.anthropicUrl;
  353. }
  354. // if endpoint is empty, use default endpoint
  355. if (baseUrl.trim().length === 0) {
  356. const isApp = !!getClientConfig()?.isApp;
  357. baseUrl = isApp
  358. ? DEFAULT_API_HOST + "/api/proxy/anthropic"
  359. : ApiPath.Anthropic;
  360. }
  361. if (!baseUrl.startsWith("http") && !baseUrl.startsWith("/api")) {
  362. baseUrl = "https://" + baseUrl;
  363. }
  364. baseUrl = trimEnd(baseUrl, "/");
  365. // try rebuild url, when using cloudflare ai gateway in client
  366. return cloudflareAIGatewayUrl(`${baseUrl}/${path}`);
  367. }
  368. }
  369. function trimEnd(s: string, end = " ") {
  370. if (end.length === 0) return s;
  371. while (s.endsWith(end)) {
  372. s = s.slice(0, -end.length);
  373. }
  374. return s;
  375. }