anthropic.ts 11 KB

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