anthropic.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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 {
  7. EventStreamContentType,
  8. fetchEventSource,
  9. } from "@fortaine/fetch-event-source";
  10. import Locale from "../../locales";
  11. import { prettyObject } from "@/app/utils/format";
  12. import { getMessageTextContent, isVisionModel } from "@/app/utils";
  13. import { preProcessImageContent } from "@/app/utils/chat";
  14. import { cloudflareAIGatewayUrl } from "@/app/utils/cloudflare";
  15. export type MultiBlockContent = {
  16. type: "image" | "text";
  17. source?: {
  18. type: string;
  19. media_type: string;
  20. data: string;
  21. };
  22. text?: string;
  23. };
  24. export type AnthropicMessage = {
  25. role: (typeof ClaudeMapper)[keyof typeof ClaudeMapper];
  26. content: string | MultiBlockContent[];
  27. };
  28. export interface AnthropicChatRequest {
  29. model: string; // The model that will complete your prompt.
  30. messages: AnthropicMessage[]; // The prompt that you want Claude to complete.
  31. max_tokens: number; // The maximum number of tokens to generate before stopping.
  32. stop_sequences?: string[]; // Sequences that will cause the model to stop generating completion text.
  33. temperature?: number; // Amount of randomness injected into the response.
  34. top_p?: number; // Use nucleus sampling.
  35. top_k?: number; // Only sample from the top K options for each subsequent token.
  36. metadata?: object; // An object describing metadata about the request.
  37. stream?: boolean; // Whether to incrementally stream the response using server-sent events.
  38. }
  39. export interface ChatRequest {
  40. model: string; // The model that will complete your prompt.
  41. prompt: string; // The prompt that you want Claude to complete.
  42. max_tokens_to_sample: number; // The maximum number of tokens to generate before stopping.
  43. stop_sequences?: string[]; // Sequences that will cause the model to stop generating completion text.
  44. temperature?: number; // Amount of randomness injected into the response.
  45. top_p?: number; // Use nucleus sampling.
  46. top_k?: number; // Only sample from the top K options for each subsequent token.
  47. metadata?: object; // An object describing metadata about the request.
  48. stream?: boolean; // Whether to incrementally stream the response using server-sent events.
  49. }
  50. export interface ChatResponse {
  51. completion: string;
  52. stop_reason: "stop_sequence" | "max_tokens";
  53. model: string;
  54. }
  55. export type ChatStreamResponse = ChatResponse & {
  56. stop?: string;
  57. log_id: string;
  58. };
  59. const ClaudeMapper = {
  60. assistant: "assistant",
  61. user: "user",
  62. system: "user",
  63. } as const;
  64. const keys = ["claude-2, claude-instant-1"];
  65. export class ClaudeApi implements LLMApi {
  66. extractMessage(res: any) {
  67. console.log("[Response] claude response: ", res);
  68. return res?.content?.[0]?.text;
  69. }
  70. async chat(options: ChatOptions): Promise<void> {
  71. const visionModel = isVisionModel(options.config.model);
  72. const accessStore = useAccessStore.getState();
  73. const shouldStream = !!options.config.stream;
  74. const modelConfig = {
  75. ...useAppConfig.getState().modelConfig,
  76. ...useChatStore.getState().currentSession().mask.modelConfig,
  77. ...{
  78. model: options.config.model,
  79. },
  80. };
  81. // try get base64image from local cache image_url
  82. const messages: ChatOptions["messages"] = [];
  83. for (const v of options.messages) {
  84. const content = await preProcessImageContent(v.content);
  85. messages.push({ role: v.role, content });
  86. }
  87. const keys = ["system", "user"];
  88. // roles must alternate between "user" and "assistant" in claude, so add a fake assistant message between two user messages
  89. for (let i = 0; i < messages.length - 1; i++) {
  90. const message = messages[i];
  91. const nextMessage = messages[i + 1];
  92. if (keys.includes(message.role) && keys.includes(nextMessage.role)) {
  93. messages[i] = [
  94. message,
  95. {
  96. role: "assistant",
  97. content: ";",
  98. },
  99. ] as any;
  100. }
  101. }
  102. const prompt = messages
  103. .flat()
  104. .filter((v) => {
  105. if (!v.content) return false;
  106. if (typeof v.content === "string" && !v.content.trim()) return false;
  107. return true;
  108. })
  109. .map((v) => {
  110. const { role, content } = v;
  111. const insideRole = ClaudeMapper[role] ?? "user";
  112. if (!visionModel || typeof content === "string") {
  113. return {
  114. role: insideRole,
  115. content: getMessageTextContent(v),
  116. };
  117. }
  118. return {
  119. role: insideRole,
  120. content: content
  121. .filter((v) => v.image_url || v.text)
  122. .map(({ type, text, image_url }) => {
  123. console.log("process message", 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. const payload = {
  168. method: "POST",
  169. body: JSON.stringify(requestBody),
  170. signal: controller.signal,
  171. headers: {
  172. ...getHeaders(), // get common headers
  173. "anthropic-version": accessStore.anthropicApiVersion,
  174. // do not send `anthropicApiKey` in browser!!!
  175. // Authorization: getAuthKey(accessStore.anthropicApiKey),
  176. },
  177. };
  178. if (shouldStream) {
  179. try {
  180. const context = {
  181. text: "",
  182. finished: false,
  183. };
  184. const finish = () => {
  185. if (!context.finished) {
  186. options.onFinish(context.text);
  187. context.finished = true;
  188. }
  189. };
  190. controller.signal.onabort = finish;
  191. fetchEventSource(path, {
  192. ...payload,
  193. async onopen(res) {
  194. const contentType = res.headers.get("content-type");
  195. console.log("response content type: ", contentType);
  196. if (contentType?.startsWith("text/plain")) {
  197. context.text = await res.clone().text();
  198. return finish();
  199. }
  200. if (
  201. !res.ok ||
  202. !res.headers
  203. .get("content-type")
  204. ?.startsWith(EventStreamContentType) ||
  205. res.status !== 200
  206. ) {
  207. const responseTexts = [context.text];
  208. let extraInfo = await res.clone().text();
  209. try {
  210. const resJson = await res.clone().json();
  211. extraInfo = prettyObject(resJson);
  212. } catch {}
  213. if (res.status === 401) {
  214. responseTexts.push(Locale.Error.Unauthorized);
  215. }
  216. if (extraInfo) {
  217. responseTexts.push(extraInfo);
  218. }
  219. context.text = responseTexts.join("\n\n");
  220. return finish();
  221. }
  222. },
  223. onmessage(msg) {
  224. let chunkJson:
  225. | undefined
  226. | {
  227. type: "content_block_delta" | "content_block_stop";
  228. delta?: {
  229. type: "text_delta";
  230. text: string;
  231. };
  232. index: number;
  233. };
  234. try {
  235. chunkJson = JSON.parse(msg.data);
  236. } catch (e) {
  237. console.error("[Response] parse error", msg.data);
  238. }
  239. if (!chunkJson || chunkJson.type === "content_block_stop") {
  240. return finish();
  241. }
  242. const { delta } = chunkJson;
  243. if (delta?.text) {
  244. context.text += delta.text;
  245. options.onUpdate?.(context.text, delta.text);
  246. }
  247. },
  248. onclose() {
  249. finish();
  250. },
  251. onerror(e) {
  252. options.onError?.(e);
  253. throw e;
  254. },
  255. openWhenHidden: true,
  256. });
  257. } catch (e) {
  258. console.error("failed to chat", e);
  259. options.onError?.(e as Error);
  260. }
  261. } else {
  262. try {
  263. controller.signal.onabort = () => options.onFinish("");
  264. const res = await fetch(path, payload);
  265. const resJson = await res.json();
  266. const message = this.extractMessage(resJson);
  267. options.onFinish(message);
  268. } catch (e) {
  269. console.error("failed to chat", e);
  270. options.onError?.(e as Error);
  271. }
  272. }
  273. }
  274. async usage() {
  275. return {
  276. used: 0,
  277. total: 0,
  278. };
  279. }
  280. async models() {
  281. // const provider = {
  282. // id: "anthropic",
  283. // providerName: "Anthropic",
  284. // providerType: "anthropic",
  285. // };
  286. return [
  287. // {
  288. // name: "claude-instant-1.2",
  289. // available: true,
  290. // provider,
  291. // },
  292. // {
  293. // name: "claude-2.0",
  294. // available: true,
  295. // provider,
  296. // },
  297. // {
  298. // name: "claude-2.1",
  299. // available: true,
  300. // provider,
  301. // },
  302. // {
  303. // name: "claude-3-opus-20240229",
  304. // available: true,
  305. // provider,
  306. // },
  307. // {
  308. // name: "claude-3-sonnet-20240229",
  309. // available: true,
  310. // provider,
  311. // },
  312. // {
  313. // name: "claude-3-haiku-20240307",
  314. // available: true,
  315. // provider,
  316. // },
  317. ];
  318. }
  319. path(path: string): string {
  320. const accessStore = useAccessStore.getState();
  321. let baseUrl: string = "";
  322. if (accessStore.useCustomConfig) {
  323. baseUrl = accessStore.anthropicUrl;
  324. }
  325. // if endpoint is empty, use default endpoint
  326. if (baseUrl.trim().length === 0) {
  327. const isApp = !!getClientConfig()?.isApp;
  328. baseUrl = isApp
  329. ? DEFAULT_API_HOST + "/api/proxy/anthropic"
  330. : ApiPath.Anthropic;
  331. }
  332. if (!baseUrl.startsWith("http") && !baseUrl.startsWith("/api")) {
  333. baseUrl = "https://" + baseUrl;
  334. }
  335. baseUrl = trimEnd(baseUrl, "/");
  336. // try rebuild url, when using cloudflare ai gateway in client
  337. return cloudflareAIGatewayUrl(`${baseUrl}/${path}`);
  338. }
  339. }
  340. function trimEnd(s: string, end = " ") {
  341. if (end.length === 0) return s;
  342. while (s.endsWith(end)) {
  343. s = s.slice(0, -end.length);
  344. }
  345. return s;
  346. }