anthropic.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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 { RequestMessage } from "@/app/typing";
  7. import {
  8. EventStreamContentType,
  9. fetchEventSource,
  10. } from "@fortaine/fetch-event-source";
  11. import Locale from "../../locales";
  12. import { prettyObject } from "@/app/utils/format";
  13. import { getMessageTextContent, isVisionModel } from "@/app/utils";
  14. import { preProcessImageContent } from "@/app/utils/chat";
  15. import { cloudflareAIGatewayUrl } from "@/app/utils/cloudflare";
  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 = [];
  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. console.log("process message", type, text, image_url);
  125. if (type === "text") {
  126. return {
  127. type,
  128. text: text!,
  129. };
  130. }
  131. const { url = "" } = image_url || {};
  132. const colonIndex = url.indexOf(":");
  133. const semicolonIndex = url.indexOf(";");
  134. const comma = url.indexOf(",");
  135. const mimeType = url.slice(colonIndex + 1, semicolonIndex);
  136. const encodeType = url.slice(semicolonIndex + 1, comma);
  137. const data = url.slice(comma + 1);
  138. return {
  139. type: "image" as const,
  140. source: {
  141. type: encodeType,
  142. media_type: mimeType,
  143. data,
  144. },
  145. };
  146. }),
  147. };
  148. });
  149. if (prompt[0]?.role === "assistant") {
  150. prompt.unshift({
  151. role: "user",
  152. content: ";",
  153. });
  154. }
  155. const requestBody: AnthropicChatRequest = {
  156. messages: prompt,
  157. stream: shouldStream,
  158. model: modelConfig.model,
  159. max_tokens: modelConfig.max_tokens,
  160. temperature: modelConfig.temperature,
  161. top_p: modelConfig.top_p,
  162. // top_k: modelConfig.top_k,
  163. top_k: 5,
  164. };
  165. const path = this.path(Anthropic.ChatPath);
  166. const controller = new AbortController();
  167. options.onController?.(controller);
  168. const payload = {
  169. method: "POST",
  170. body: JSON.stringify(requestBody),
  171. signal: controller.signal,
  172. headers: {
  173. ...getHeaders(), // get common headers
  174. "anthropic-version": accessStore.anthropicApiVersion,
  175. // do not send `anthropicApiKey` in browser!!!
  176. // Authorization: getAuthKey(accessStore.anthropicApiKey),
  177. },
  178. };
  179. if (shouldStream) {
  180. try {
  181. const context = {
  182. text: "",
  183. finished: false,
  184. };
  185. const finish = () => {
  186. if (!context.finished) {
  187. options.onFinish(context.text);
  188. context.finished = true;
  189. }
  190. };
  191. controller.signal.onabort = finish;
  192. fetchEventSource(path, {
  193. ...payload,
  194. async onopen(res) {
  195. const contentType = res.headers.get("content-type");
  196. console.log("response content type: ", contentType);
  197. if (contentType?.startsWith("text/plain")) {
  198. context.text = await res.clone().text();
  199. return finish();
  200. }
  201. if (
  202. !res.ok ||
  203. !res.headers
  204. .get("content-type")
  205. ?.startsWith(EventStreamContentType) ||
  206. res.status !== 200
  207. ) {
  208. const responseTexts = [context.text];
  209. let extraInfo = await res.clone().text();
  210. try {
  211. const resJson = await res.clone().json();
  212. extraInfo = prettyObject(resJson);
  213. } catch {}
  214. if (res.status === 401) {
  215. responseTexts.push(Locale.Error.Unauthorized);
  216. }
  217. if (extraInfo) {
  218. responseTexts.push(extraInfo);
  219. }
  220. context.text = responseTexts.join("\n\n");
  221. return finish();
  222. }
  223. },
  224. onmessage(msg) {
  225. let chunkJson:
  226. | undefined
  227. | {
  228. type: "content_block_delta" | "content_block_stop";
  229. delta?: {
  230. type: "text_delta";
  231. text: string;
  232. };
  233. index: number;
  234. };
  235. try {
  236. chunkJson = JSON.parse(msg.data);
  237. } catch (e) {
  238. console.error("[Response] parse error", msg.data);
  239. }
  240. if (!chunkJson || chunkJson.type === "content_block_stop") {
  241. return finish();
  242. }
  243. const { delta } = chunkJson;
  244. if (delta?.text) {
  245. context.text += delta.text;
  246. options.onUpdate?.(context.text, delta.text);
  247. }
  248. },
  249. onclose() {
  250. finish();
  251. },
  252. onerror(e) {
  253. options.onError?.(e);
  254. throw e;
  255. },
  256. openWhenHidden: true,
  257. });
  258. } catch (e) {
  259. console.error("failed to chat", e);
  260. options.onError?.(e as Error);
  261. }
  262. } else {
  263. try {
  264. controller.signal.onabort = () => options.onFinish("");
  265. const res = await fetch(path, payload);
  266. const resJson = await res.json();
  267. const message = this.extractMessage(resJson);
  268. options.onFinish(message);
  269. } catch (e) {
  270. console.error("failed to chat", e);
  271. options.onError?.(e as Error);
  272. }
  273. }
  274. }
  275. async usage() {
  276. return {
  277. used: 0,
  278. total: 0,
  279. };
  280. }
  281. async models() {
  282. // const provider = {
  283. // id: "anthropic",
  284. // providerName: "Anthropic",
  285. // providerType: "anthropic",
  286. // };
  287. return [
  288. // {
  289. // name: "claude-instant-1.2",
  290. // available: true,
  291. // provider,
  292. // },
  293. // {
  294. // name: "claude-2.0",
  295. // available: true,
  296. // provider,
  297. // },
  298. // {
  299. // name: "claude-2.1",
  300. // available: true,
  301. // provider,
  302. // },
  303. // {
  304. // name: "claude-3-opus-20240229",
  305. // available: true,
  306. // provider,
  307. // },
  308. // {
  309. // name: "claude-3-sonnet-20240229",
  310. // available: true,
  311. // provider,
  312. // },
  313. // {
  314. // name: "claude-3-haiku-20240307",
  315. // available: true,
  316. // provider,
  317. // },
  318. ];
  319. }
  320. path(path: string): string {
  321. const accessStore = useAccessStore.getState();
  322. let baseUrl: string = "";
  323. if (accessStore.useCustomConfig) {
  324. baseUrl = accessStore.anthropicUrl;
  325. }
  326. // if endpoint is empty, use default endpoint
  327. if (baseUrl.trim().length === 0) {
  328. const isApp = !!getClientConfig()?.isApp;
  329. baseUrl = isApp
  330. ? DEFAULT_API_HOST + "/api/proxy/anthropic"
  331. : ApiPath.Anthropic;
  332. }
  333. if (!baseUrl.startsWith("http") && !baseUrl.startsWith("/api")) {
  334. baseUrl = "https://" + baseUrl;
  335. }
  336. baseUrl = trimEnd(baseUrl, "/");
  337. // try rebuild url, when using cloudflare ai gateway in client
  338. return cloudflareAIGatewayUrl(`${baseUrl}/${path}`);
  339. }
  340. }
  341. function trimEnd(s: string, end = " ") {
  342. if (end.length === 0) return s;
  343. while (s.endsWith(end)) {
  344. s = s.slice(0, -end.length);
  345. }
  346. return s;
  347. }