anthropic.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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. console.log("getAsTools", tools, funcs);
  181. return stream(
  182. path,
  183. requestBody,
  184. {
  185. ...getHeaders(),
  186. "anthropic-version": accessStore.anthropicApiVersion,
  187. },
  188. // @ts-ignore
  189. tools.map((tool) => ({
  190. name: tool?.function?.name,
  191. description: tool?.function?.description,
  192. input_schema: tool?.function?.parameters,
  193. })),
  194. funcs,
  195. controller,
  196. // parseSSE
  197. (text: string, runTools: ChatMessageTool[]) => {
  198. // console.log("parseSSE", text, runTools);
  199. let chunkJson:
  200. | undefined
  201. | {
  202. type: "content_block_delta" | "content_block_stop";
  203. content_block?: {
  204. type: "tool_use";
  205. id: string;
  206. name: string;
  207. };
  208. delta?: {
  209. type: "text_delta" | "input_json_delta";
  210. text?: string;
  211. partial_json?: string;
  212. };
  213. index: number;
  214. };
  215. chunkJson = JSON.parse(text);
  216. if (chunkJson?.content_block?.type == "tool_use") {
  217. index += 1;
  218. const id = chunkJson?.content_block.id;
  219. const name = chunkJson?.content_block.name;
  220. runTools.push({
  221. id,
  222. type: "function",
  223. function: {
  224. name,
  225. arguments: "",
  226. },
  227. });
  228. }
  229. if (
  230. chunkJson?.delta?.type == "input_json_delta" &&
  231. chunkJson?.delta?.partial_json
  232. ) {
  233. // @ts-ignore
  234. runTools[index]["function"]["arguments"] +=
  235. chunkJson?.delta?.partial_json;
  236. }
  237. return chunkJson?.delta?.text;
  238. },
  239. // processToolMessage, include tool_calls message and tool call results
  240. (
  241. requestPayload: RequestPayload,
  242. toolCallMessage: any,
  243. toolCallResult: any[],
  244. ) => {
  245. // @ts-ignore
  246. requestPayload?.messages?.splice(
  247. // @ts-ignore
  248. requestPayload?.messages?.length,
  249. 0,
  250. {
  251. role: "assistant",
  252. content: toolCallMessage.tool_calls.map(
  253. (tool: ChatMessageTool) => ({
  254. type: "tool_use",
  255. id: tool.id,
  256. name: tool?.function?.name,
  257. input: JSON.parse(tool?.function?.arguments as string),
  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. }