anthropic.ts 11 KB

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