anthropic.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. import { ACCESS_CODE_PREFIX, Anthropic, ApiPath } from "@/app/constant";
  2. import { ChatOptions, 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. export type MultiBlockContent = {
  15. type: "image" | "text";
  16. source?: {
  17. type: string;
  18. media_type: string;
  19. data: string;
  20. };
  21. text?: string;
  22. };
  23. export type AnthropicMessage = {
  24. role: (typeof ClaudeMapper)[keyof typeof ClaudeMapper];
  25. content: string | MultiBlockContent[];
  26. };
  27. export interface AnthropicChatRequest {
  28. model: string; // The model that will complete your prompt.
  29. messages: AnthropicMessage[]; // The prompt that you want Claude to complete.
  30. max_tokens: number; // The maximum number of tokens to generate before stopping.
  31. stop_sequences?: string[]; // Sequences that will cause the model to stop generating completion text.
  32. temperature?: number; // Amount of randomness injected into the response.
  33. top_p?: number; // Use nucleus sampling.
  34. top_k?: number; // Only sample from the top K options for each subsequent token.
  35. metadata?: object; // An object describing metadata about the request.
  36. stream?: boolean; // Whether to incrementally stream the response using server-sent events.
  37. }
  38. export interface ChatRequest {
  39. model: string; // The model that will complete your prompt.
  40. prompt: string; // The prompt that you want Claude to complete.
  41. max_tokens_to_sample: number; // The maximum number of tokens to generate before stopping.
  42. stop_sequences?: string[]; // Sequences that will cause the model to stop generating completion text.
  43. temperature?: number; // Amount of randomness injected into the response.
  44. top_p?: number; // Use nucleus sampling.
  45. top_k?: number; // Only sample from the top K options for each subsequent token.
  46. metadata?: object; // An object describing metadata about the request.
  47. stream?: boolean; // Whether to incrementally stream the response using server-sent events.
  48. }
  49. export interface ChatResponse {
  50. completion: string;
  51. stop_reason: "stop_sequence" | "max_tokens";
  52. model: string;
  53. }
  54. export type ChatStreamResponse = ChatResponse & {
  55. stop?: string;
  56. log_id: string;
  57. };
  58. const ClaudeMapper = {
  59. assistant: "assistant",
  60. user: "user",
  61. system: "user",
  62. } as const;
  63. export class ClaudeApi implements LLMApi {
  64. extractMessage(res: any) {
  65. console.log("[Response] claude response: ", res);
  66. return res.completion;
  67. }
  68. async chatComplete(options: ChatOptions): Promise<void> {
  69. const ClaudeMapper: Record<RequestMessage["role"], string> = {
  70. assistant: "Assistant",
  71. user: "Human",
  72. system: "Human",
  73. };
  74. const accessStore = useAccessStore.getState();
  75. const shouldStream = !!options.config.stream;
  76. const prompt = options.messages
  77. .map((v) => ({
  78. role: ClaudeMapper[v.role] ?? "Human",
  79. content: v.content,
  80. }))
  81. .map((v) => `\n\n${v.role}: ${v.content}`)
  82. .join("");
  83. const modelConfig = {
  84. ...useAppConfig.getState().modelConfig,
  85. ...useChatStore.getState().currentSession().mask.modelConfig,
  86. ...{
  87. model: options.config.model,
  88. },
  89. };
  90. const requestBody: ChatRequest = {
  91. prompt,
  92. stream: shouldStream,
  93. model: modelConfig.model,
  94. max_tokens_to_sample: modelConfig.max_tokens,
  95. temperature: modelConfig.temperature,
  96. top_p: modelConfig.top_p,
  97. // top_k: modelConfig.top_k,
  98. top_k: 5,
  99. };
  100. const path = this.path(Anthropic.ChatPath1);
  101. const controller = new AbortController();
  102. options.onController?.(controller);
  103. const payload = {
  104. method: "POST",
  105. body: JSON.stringify(requestBody),
  106. signal: controller.signal,
  107. headers: {
  108. "Content-Type": "application/json",
  109. // Accept: "application/json",
  110. "x-api-key": accessStore.anthropicApiKey,
  111. "anthropic-version": accessStore.anthropicApiVersion,
  112. Authorization: getAuthKey(accessStore.anthropicApiKey),
  113. },
  114. // mode: "no-cors" as RequestMode,
  115. };
  116. if (shouldStream) {
  117. try {
  118. const context = {
  119. text: "",
  120. finished: false,
  121. };
  122. const finish = () => {
  123. if (!context.finished) {
  124. options.onFinish(context.text);
  125. context.finished = true;
  126. }
  127. };
  128. controller.signal.onabort = finish;
  129. fetchEventSource(path, {
  130. ...payload,
  131. async onopen(res) {
  132. const contentType = res.headers.get("content-type");
  133. console.log("response content type: ", contentType);
  134. if (contentType?.startsWith("text/plain")) {
  135. context.text = await res.clone().text();
  136. return finish();
  137. }
  138. if (
  139. !res.ok ||
  140. !res.headers
  141. .get("content-type")
  142. ?.startsWith(EventStreamContentType) ||
  143. res.status !== 200
  144. ) {
  145. const responseTexts = [context.text];
  146. let extraInfo = await res.clone().text();
  147. try {
  148. const resJson = await res.clone().json();
  149. extraInfo = prettyObject(resJson);
  150. } catch {}
  151. if (res.status === 401) {
  152. responseTexts.push(Locale.Error.Unauthorized);
  153. }
  154. if (extraInfo) {
  155. responseTexts.push(extraInfo);
  156. }
  157. context.text = responseTexts.join("\n\n");
  158. return finish();
  159. }
  160. },
  161. onmessage(msg) {
  162. if (msg.data === "[DONE]" || context.finished) {
  163. return finish();
  164. }
  165. const chunk = msg.data;
  166. try {
  167. const chunkJson = JSON.parse(chunk) as ChatStreamResponse;
  168. const delta = chunkJson.completion;
  169. if (delta) {
  170. context.text += delta;
  171. options.onUpdate?.(context.text, delta);
  172. }
  173. } catch (e) {
  174. console.error("[Request] parse error", chunk, msg);
  175. }
  176. },
  177. onclose() {
  178. finish();
  179. },
  180. onerror(e) {
  181. options.onError?.(e);
  182. },
  183. openWhenHidden: true,
  184. });
  185. } catch (e) {
  186. console.error("failed to chat", e);
  187. options.onError?.(e as Error);
  188. }
  189. } else {
  190. try {
  191. controller.signal.onabort = () => options.onFinish("");
  192. const res = await fetch(path, payload);
  193. const resJson = await res.json();
  194. const message = this.extractMessage(resJson);
  195. options.onFinish(message);
  196. } catch (e) {
  197. console.error("failed to chat", e);
  198. options.onError?.(e as Error);
  199. }
  200. }
  201. }
  202. async chat(options: ChatOptions): Promise<void> {
  203. const visionModel = isVisionModel(options.config.model);
  204. const accessStore = useAccessStore.getState();
  205. const shouldStream = !!options.config.stream;
  206. const prompt = options.messages
  207. .filter((v) => {
  208. if (!v.content) return false;
  209. if (typeof v.content === "string" && !v.content.trim()) return false;
  210. return true;
  211. })
  212. .map((v) => {
  213. const { role, content } = v;
  214. const insideRole = ClaudeMapper[role] ?? "user";
  215. if (!visionModel || typeof content === "string") {
  216. return {
  217. role: insideRole,
  218. content: getMessageTextContent(v),
  219. };
  220. }
  221. return {
  222. role: insideRole,
  223. content: content
  224. .filter((v) => v.image_url || v.text)
  225. .map(({ type, text, image_url }) => {
  226. if (type === "text") {
  227. return {
  228. type,
  229. text: text!,
  230. };
  231. }
  232. const { url = "" } = image_url || {};
  233. const colonIndex = url.indexOf(":");
  234. const semicolonIndex = url.indexOf(";");
  235. const comma = url.indexOf(",");
  236. const mimeType = url.slice(colonIndex + 1, semicolonIndex);
  237. const encodeType = url.slice(semicolonIndex + 1, comma);
  238. const data = url.slice(comma + 1);
  239. return {
  240. type: "image" as const,
  241. source: {
  242. type: encodeType,
  243. media_type: mimeType,
  244. data,
  245. },
  246. };
  247. }),
  248. };
  249. });
  250. const modelConfig = {
  251. ...useAppConfig.getState().modelConfig,
  252. ...useChatStore.getState().currentSession().mask.modelConfig,
  253. ...{
  254. model: options.config.model,
  255. },
  256. };
  257. const requestBody: AnthropicChatRequest = {
  258. messages: prompt,
  259. stream: shouldStream,
  260. model: modelConfig.model,
  261. max_tokens: modelConfig.max_tokens,
  262. temperature: modelConfig.temperature,
  263. top_p: modelConfig.top_p,
  264. // top_k: modelConfig.top_k,
  265. top_k: 5,
  266. };
  267. const path = this.path(Anthropic.ChatPath);
  268. const controller = new AbortController();
  269. options.onController?.(controller);
  270. const payload = {
  271. method: "POST",
  272. body: JSON.stringify(requestBody),
  273. signal: controller.signal,
  274. headers: {
  275. "Content-Type": "application/json",
  276. Accept: "application/json",
  277. "x-api-key": accessStore.anthropicApiKey,
  278. "anthropic-version": accessStore.anthropicApiVersion,
  279. Authorization: getAuthKey(accessStore.anthropicApiKey),
  280. },
  281. // mode: (!clientConfig?.isApp && pathObj.hostname === location.hostname ? "same-origin" : "cors") as RequestMode,
  282. // mode: "no-cors" as RequestMode,
  283. credentials: "include" as RequestCredentials,
  284. };
  285. if (shouldStream) {
  286. try {
  287. const context = {
  288. text: "",
  289. finished: false,
  290. };
  291. const finish = () => {
  292. if (!context.finished) {
  293. options.onFinish(context.text);
  294. context.finished = true;
  295. }
  296. };
  297. controller.signal.onabort = finish;
  298. fetchEventSource(path, {
  299. ...payload,
  300. async onopen(res) {
  301. const contentType = res.headers.get("content-type");
  302. console.log("response content type: ", contentType);
  303. if (contentType?.startsWith("text/plain")) {
  304. context.text = await res.clone().text();
  305. return finish();
  306. }
  307. if (
  308. !res.ok ||
  309. !res.headers
  310. .get("content-type")
  311. ?.startsWith(EventStreamContentType) ||
  312. res.status !== 200
  313. ) {
  314. const responseTexts = [context.text];
  315. let extraInfo = await res.clone().text();
  316. try {
  317. const resJson = await res.clone().json();
  318. extraInfo = prettyObject(resJson);
  319. } catch {}
  320. if (res.status === 401) {
  321. responseTexts.push(Locale.Error.Unauthorized);
  322. }
  323. if (extraInfo) {
  324. responseTexts.push(extraInfo);
  325. }
  326. context.text = responseTexts.join("\n\n");
  327. return finish();
  328. }
  329. },
  330. onmessage(msg) {
  331. let chunkJson:
  332. | undefined
  333. | {
  334. type: "content_block_delta" | "content_block_stop";
  335. delta?: {
  336. type: "text_delta";
  337. text: string;
  338. };
  339. index: number;
  340. };
  341. try {
  342. chunkJson = JSON.parse(msg.data);
  343. } catch (e) {
  344. console.error("[Response] parse error", msg.data);
  345. }
  346. if (!chunkJson || chunkJson.type === "content_block_stop") {
  347. return finish();
  348. }
  349. const { delta } = chunkJson;
  350. if (delta?.text) {
  351. context.text += delta.text;
  352. options.onUpdate?.(context.text, delta.text);
  353. }
  354. },
  355. onclose() {
  356. finish();
  357. },
  358. onerror(e) {
  359. options.onError?.(e);
  360. throw e;
  361. },
  362. openWhenHidden: true,
  363. });
  364. } catch (e) {
  365. console.error("failed to chat", e);
  366. options.onError?.(e as Error);
  367. }
  368. } else {
  369. try {
  370. controller.signal.onabort = () => options.onFinish("");
  371. const res = await fetch(path, payload);
  372. const resJson = await res.json();
  373. const message = this.extractMessage(resJson);
  374. options.onFinish(message);
  375. } catch (e) {
  376. console.error("failed to chat", e);
  377. options.onError?.(e as Error);
  378. }
  379. }
  380. }
  381. async usage() {
  382. return {
  383. used: 0,
  384. total: 0,
  385. };
  386. }
  387. async models() {
  388. const provider = {
  389. id: "anthropic",
  390. providerName: "Anthropic",
  391. providerType: "anthropic",
  392. };
  393. return [
  394. {
  395. name: "claude-instant-1.2",
  396. available: true,
  397. provider,
  398. },
  399. {
  400. name: "claude-2.0",
  401. available: true,
  402. provider,
  403. },
  404. {
  405. name: "claude-2.1",
  406. available: true,
  407. provider,
  408. },
  409. {
  410. name: "claude-3-opus-20240229",
  411. available: true,
  412. provider,
  413. },
  414. {
  415. name: "claude-3-sonnet-20240229",
  416. available: true,
  417. provider,
  418. },
  419. {
  420. name: "claude-3-haiku-20240307",
  421. available: true,
  422. provider,
  423. },
  424. ];
  425. }
  426. path(path: string): string {
  427. const accessStore = useAccessStore.getState();
  428. let baseUrl: string = accessStore.anthropicUrl;
  429. // if endpoint is empty, use default endpoint
  430. if (baseUrl.trim().length === 0) {
  431. const isApp = !!getClientConfig()?.isApp;
  432. baseUrl = isApp
  433. ? DEFAULT_API_HOST + "/api/proxy" + ApiPath.Anthropic
  434. : ApiPath.Anthropic;
  435. }
  436. if (!baseUrl.startsWith("http") && !baseUrl.startsWith("/api")) {
  437. baseUrl = "https://" + baseUrl;
  438. }
  439. baseUrl = trimEnd(baseUrl, "/");
  440. return `${baseUrl}/${path}`;
  441. }
  442. }
  443. function trimEnd(s: string, end = " ") {
  444. if (end.length === 0) return s;
  445. while (s.endsWith(end)) {
  446. s = s.slice(0, -end.length);
  447. }
  448. return s;
  449. }
  450. function bearer(value: string) {
  451. return `Bearer ${value.trim()}`;
  452. }
  453. function getAuthKey(apiKey = "") {
  454. const accessStore = useAccessStore.getState();
  455. const isApp = !!getClientConfig()?.isApp;
  456. let authKey = "";
  457. if (apiKey) {
  458. // use user's api key first
  459. authKey = bearer(apiKey);
  460. } else if (
  461. accessStore.enabledAccessControl() &&
  462. !isApp &&
  463. !!accessStore.accessCode
  464. ) {
  465. // or use access code
  466. authKey = bearer(ACCESS_CODE_PREFIX + accessStore.accessCode);
  467. }
  468. return authKey;
  469. }