anthropic.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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 { MessageRole, 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.map((v) => {
  207. const { role, content } = v;
  208. const insideRole = ClaudeMapper[role] ?? "user";
  209. if (!visionModel || typeof content === "string") {
  210. return {
  211. role: insideRole,
  212. content: getMessageTextContent(v),
  213. };
  214. }
  215. return {
  216. role: insideRole,
  217. content: content.map(({ type, text, image_url }) => {
  218. if (type === "text") {
  219. return {
  220. type,
  221. text: text!,
  222. };
  223. }
  224. const { url = "" } = image_url || {};
  225. const colonIndex = url.indexOf(":");
  226. const semicolonIndex = url.indexOf(";");
  227. const comma = url.indexOf(",");
  228. const mimeType = url.slice(colonIndex + 1, semicolonIndex);
  229. const encodeType = url.slice(semicolonIndex + 1, comma);
  230. const data = url.slice(comma + 1);
  231. return {
  232. type: "image" as const,
  233. source: {
  234. type: encodeType,
  235. media_type: mimeType,
  236. data,
  237. },
  238. };
  239. }),
  240. };
  241. });
  242. const modelConfig = {
  243. ...useAppConfig.getState().modelConfig,
  244. ...useChatStore.getState().currentSession().mask.modelConfig,
  245. ...{
  246. model: options.config.model,
  247. },
  248. };
  249. const requestBody: AnthropicChatRequest = {
  250. messages: prompt,
  251. stream: shouldStream,
  252. model: modelConfig.model,
  253. max_tokens: modelConfig.max_tokens,
  254. temperature: modelConfig.temperature,
  255. top_p: modelConfig.top_p,
  256. // top_k: modelConfig.top_k,
  257. top_k: 5,
  258. };
  259. const path = this.path(Anthropic.ChatPath);
  260. const controller = new AbortController();
  261. options.onController?.(controller);
  262. const payload = {
  263. method: "POST",
  264. body: JSON.stringify(requestBody),
  265. signal: controller.signal,
  266. headers: {
  267. "Content-Type": "application/json",
  268. Accept: "application/json",
  269. "x-api-key": accessStore.anthropicApiKey,
  270. "anthropic-version": accessStore.anthropicApiVersion,
  271. Authorization: getAuthKey(accessStore.anthropicApiKey),
  272. },
  273. // mode: (!clientConfig?.isApp && pathObj.hostname === location.hostname ? "same-origin" : "cors") as RequestMode,
  274. // mode: "no-cors" as RequestMode,
  275. credentials: "include" as RequestCredentials,
  276. };
  277. if (shouldStream) {
  278. try {
  279. const context = {
  280. text: "",
  281. finished: false,
  282. };
  283. const finish = () => {
  284. if (!context.finished) {
  285. options.onFinish(context.text);
  286. context.finished = true;
  287. }
  288. };
  289. controller.signal.onabort = finish;
  290. fetchEventSource(path, {
  291. ...payload,
  292. async onopen(res) {
  293. const contentType = res.headers.get("content-type");
  294. console.log("response content type: ", contentType);
  295. if (contentType?.startsWith("text/plain")) {
  296. context.text = await res.clone().text();
  297. return finish();
  298. }
  299. if (
  300. !res.ok ||
  301. !res.headers
  302. .get("content-type")
  303. ?.startsWith(EventStreamContentType) ||
  304. res.status !== 200
  305. ) {
  306. const responseTexts = [context.text];
  307. let extraInfo = await res.clone().text();
  308. try {
  309. const resJson = await res.clone().json();
  310. extraInfo = prettyObject(resJson);
  311. } catch {}
  312. if (res.status === 401) {
  313. responseTexts.push(Locale.Error.Unauthorized);
  314. }
  315. if (extraInfo) {
  316. responseTexts.push(extraInfo);
  317. }
  318. context.text = responseTexts.join("\n\n");
  319. return finish();
  320. }
  321. },
  322. onmessage(msg) {
  323. if (msg.data === "[DONE]" || context.finished) {
  324. return finish();
  325. }
  326. const chunk = msg.data;
  327. try {
  328. const chunkJson = JSON.parse(chunk) as ChatStreamResponse;
  329. const delta = chunkJson.completion;
  330. if (delta) {
  331. context.text += delta;
  332. options.onUpdate?.(context.text, delta);
  333. }
  334. } catch (e) {
  335. console.error("[Request] parse error", chunk, msg);
  336. }
  337. },
  338. onclose() {
  339. finish();
  340. },
  341. onerror(e) {
  342. options.onError?.(e);
  343. throw e;
  344. },
  345. openWhenHidden: true,
  346. });
  347. } catch (e) {
  348. console.error("failed to chat", e);
  349. options.onError?.(e as Error);
  350. }
  351. } else {
  352. try {
  353. controller.signal.onabort = () => options.onFinish("");
  354. const res = await fetch(path, payload);
  355. const resJson = await res.json();
  356. const message = this.extractMessage(resJson);
  357. options.onFinish(message);
  358. } catch (e) {
  359. console.error("failed to chat", e);
  360. options.onError?.(e as Error);
  361. }
  362. }
  363. }
  364. async usage() {
  365. return {
  366. used: 0,
  367. total: 0,
  368. };
  369. }
  370. async models() {
  371. const provider = {
  372. id: "anthropic",
  373. providerName: "Anthropic",
  374. providerType: "anthropic",
  375. };
  376. return [
  377. {
  378. name: "claude-instant-1",
  379. available: true,
  380. provider,
  381. },
  382. {
  383. name: "claude-2",
  384. available: true,
  385. provider,
  386. },
  387. {
  388. name: "claude-3-opus-20240229",
  389. available: true,
  390. provider,
  391. },
  392. {
  393. name: "claude-3-sonnet-20240229",
  394. available: true,
  395. provider,
  396. },
  397. {
  398. name: "claude-3-haiku-20240307",
  399. available: true,
  400. provider,
  401. },
  402. ];
  403. }
  404. path(path: string): string {
  405. const accessStore = useAccessStore.getState();
  406. let baseUrl: string = accessStore.anthropicUrl;
  407. // if endpoint is empty, use default endpoint
  408. if (baseUrl.trim().length === 0) {
  409. const isApp = !!getClientConfig()?.isApp;
  410. baseUrl = isApp
  411. ? DEFAULT_API_HOST + "/api/proxy" + ApiPath.Anthropic
  412. : ApiPath.Anthropic;
  413. }
  414. if (!baseUrl.startsWith("http") && !baseUrl.startsWith("/api")) {
  415. baseUrl = "https://" + baseUrl;
  416. }
  417. baseUrl = trimEnd(baseUrl, "/");
  418. return `${baseUrl}/${path}`;
  419. }
  420. }
  421. function trimEnd(s: string, end = " ") {
  422. if (end.length === 0) return s;
  423. while (s.endsWith(end)) {
  424. s = s.slice(0, -end.length);
  425. }
  426. return s;
  427. }
  428. function bearer(value: string) {
  429. return `Bearer ${value.trim()}`;
  430. }
  431. function getAuthKey(apiKey = "") {
  432. const accessStore = useAccessStore.getState();
  433. const isApp = !!getClientConfig()?.isApp;
  434. let authKey = "";
  435. if (apiKey) {
  436. // use user's api key first
  437. authKey = bearer(apiKey);
  438. } else if (
  439. accessStore.enabledAccessControl() &&
  440. !isApp &&
  441. !!accessStore.accessCode
  442. ) {
  443. // or use access code
  444. authKey = bearer(ACCESS_CODE_PREFIX + accessStore.accessCode);
  445. }
  446. return authKey;
  447. }