anthropic.ts 11 KB

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