anthropic.ts 11 KB

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