anthropic.ts 12 KB

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