anthropic.ts 12 KB

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