proxy.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. /**
  2. * Proxy stream function for apps that route LLM calls through a server.
  3. * The server manages auth and proxies requests to LLM providers.
  4. */
  5. // Internal import for JSON parsing utility
  6. import {
  7. type AssistantMessage,
  8. type AssistantMessageEvent,
  9. type Context,
  10. EventStream,
  11. type Model,
  12. parseStreamingJson,
  13. type SimpleStreamOptions,
  14. type StopReason,
  15. type ToolCall,
  16. } from "@earendil-works/pi-ai";
  17. // Create stream class matching ProxyMessageEventStream
  18. class ProxyMessageEventStream extends EventStream<AssistantMessageEvent, AssistantMessage> {
  19. constructor() {
  20. super(
  21. (event) => event.type === "done" || event.type === "error",
  22. (event) => {
  23. if (event.type === "done") return event.message;
  24. if (event.type === "error") return event.error;
  25. throw new Error("Unexpected event type");
  26. },
  27. );
  28. }
  29. }
  30. /**
  31. * Proxy event types - server sends these with partial field stripped to reduce bandwidth.
  32. */
  33. export type ProxyAssistantMessageEvent =
  34. | { type: "start" }
  35. | { type: "text_start"; contentIndex: number }
  36. | { type: "text_delta"; contentIndex: number; delta: string }
  37. | { type: "text_end"; contentIndex: number; contentSignature?: string }
  38. | { type: "thinking_start"; contentIndex: number }
  39. | { type: "thinking_delta"; contentIndex: number; delta: string }
  40. | { type: "thinking_end"; contentIndex: number; contentSignature?: string }
  41. | { type: "toolcall_start"; contentIndex: number; id: string; toolName: string }
  42. | { type: "toolcall_delta"; contentIndex: number; delta: string }
  43. | { type: "toolcall_end"; contentIndex: number }
  44. | {
  45. type: "done";
  46. reason: Extract<StopReason, "stop" | "length" | "toolUse">;
  47. usage: AssistantMessage["usage"];
  48. }
  49. | {
  50. type: "error";
  51. reason: Extract<StopReason, "aborted" | "error">;
  52. errorMessage?: string;
  53. usage: AssistantMessage["usage"];
  54. };
  55. type ProxySerializableStreamOptions = Pick<
  56. SimpleStreamOptions,
  57. | "temperature"
  58. | "maxTokens"
  59. | "reasoning"
  60. | "cacheRetention"
  61. | "sessionId"
  62. | "headers"
  63. | "metadata"
  64. | "transport"
  65. | "thinkingBudgets"
  66. | "maxRetryDelayMs"
  67. >;
  68. export interface ProxyStreamOptions extends ProxySerializableStreamOptions {
  69. /** Local abort signal for the proxy request */
  70. signal?: AbortSignal;
  71. /** Auth token for the proxy server */
  72. authToken: string;
  73. /** Proxy server URL (e.g., "https://genai.example.com") */
  74. proxyUrl: string;
  75. }
  76. /**
  77. * Stream function that proxies through a server instead of calling LLM providers directly.
  78. * The server strips the partial field from delta events to reduce bandwidth.
  79. * We reconstruct the partial message client-side.
  80. *
  81. * Use this as the `streamFn` option when creating an Agent that needs to go through a proxy.
  82. *
  83. * @example
  84. * ```typescript
  85. * const agent = new Agent({
  86. * streamFn: (model, context, options) =>
  87. * streamProxy(model, context, {
  88. * ...options,
  89. * authToken: await getAuthToken(),
  90. * proxyUrl: "https://genai.example.com",
  91. * }),
  92. * });
  93. * ```
  94. */
  95. function buildProxyRequestOptions(options: ProxyStreamOptions): ProxySerializableStreamOptions {
  96. return {
  97. temperature: options.temperature,
  98. maxTokens: options.maxTokens,
  99. reasoning: options.reasoning,
  100. cacheRetention: options.cacheRetention,
  101. sessionId: options.sessionId,
  102. headers: options.headers,
  103. metadata: options.metadata,
  104. transport: options.transport,
  105. thinkingBudgets: options.thinkingBudgets,
  106. maxRetryDelayMs: options.maxRetryDelayMs,
  107. };
  108. }
  109. export function streamProxy(model: Model<any>, context: Context, options: ProxyStreamOptions): ProxyMessageEventStream {
  110. const stream = new ProxyMessageEventStream();
  111. (async () => {
  112. // Initialize the partial message that we'll build up from events
  113. const partial: AssistantMessage = {
  114. role: "assistant",
  115. stopReason: "stop",
  116. content: [],
  117. api: model.api,
  118. provider: model.provider,
  119. model: model.id,
  120. usage: {
  121. input: 0,
  122. output: 0,
  123. cacheRead: 0,
  124. cacheWrite: 0,
  125. totalTokens: 0,
  126. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
  127. },
  128. timestamp: Date.now(),
  129. };
  130. let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
  131. const abortHandler = () => {
  132. if (reader) {
  133. reader.cancel("Request aborted by user").catch(() => {});
  134. }
  135. };
  136. if (options.signal) {
  137. options.signal.addEventListener("abort", abortHandler);
  138. }
  139. try {
  140. const response = await fetch(`${options.proxyUrl}/api/stream`, {
  141. method: "POST",
  142. headers: {
  143. Authorization: `Bearer ${options.authToken}`,
  144. "Content-Type": "application/json",
  145. },
  146. body: JSON.stringify({
  147. model,
  148. context,
  149. options: buildProxyRequestOptions(options),
  150. }),
  151. signal: options.signal,
  152. });
  153. if (!response.ok) {
  154. let errorMessage = `Proxy error: ${response.status} ${response.statusText}`;
  155. try {
  156. const errorData = (await response.json()) as { error?: string };
  157. if (errorData.error) {
  158. errorMessage = `Proxy error: ${errorData.error}`;
  159. }
  160. } catch {
  161. // Couldn't parse error response
  162. }
  163. throw new Error(errorMessage);
  164. }
  165. reader = response.body!.getReader();
  166. const decoder = new TextDecoder();
  167. let buffer = "";
  168. while (true) {
  169. const { done, value } = await reader.read();
  170. if (done) break;
  171. if (options.signal?.aborted) {
  172. throw new Error("Request aborted by user");
  173. }
  174. buffer += decoder.decode(value, { stream: true });
  175. const lines = buffer.split("\n");
  176. buffer = lines.pop() || "";
  177. for (const line of lines) {
  178. if (line.startsWith("data: ")) {
  179. const data = line.slice(6).trim();
  180. if (data) {
  181. const proxyEvent = JSON.parse(data) as ProxyAssistantMessageEvent;
  182. const event = processProxyEvent(proxyEvent, partial);
  183. if (event) {
  184. stream.push(event);
  185. }
  186. }
  187. }
  188. }
  189. }
  190. if (options.signal?.aborted) {
  191. throw new Error("Request aborted by user");
  192. }
  193. stream.end();
  194. } catch (error) {
  195. const errorMessage = error instanceof Error ? error.message : String(error);
  196. const reason = options.signal?.aborted ? "aborted" : "error";
  197. partial.stopReason = reason;
  198. partial.errorMessage = errorMessage;
  199. stream.push({
  200. type: "error",
  201. reason,
  202. error: partial,
  203. });
  204. stream.end();
  205. } finally {
  206. if (options.signal) {
  207. options.signal.removeEventListener("abort", abortHandler);
  208. }
  209. }
  210. })();
  211. return stream;
  212. }
  213. /**
  214. * Process a proxy event and update the partial message.
  215. */
  216. function processProxyEvent(
  217. proxyEvent: ProxyAssistantMessageEvent,
  218. partial: AssistantMessage,
  219. ): AssistantMessageEvent | undefined {
  220. switch (proxyEvent.type) {
  221. case "start":
  222. return { type: "start", partial };
  223. case "text_start":
  224. partial.content[proxyEvent.contentIndex] = { type: "text", text: "" };
  225. return { type: "text_start", contentIndex: proxyEvent.contentIndex, partial };
  226. case "text_delta": {
  227. const content = partial.content[proxyEvent.contentIndex];
  228. if (content?.type === "text") {
  229. content.text += proxyEvent.delta;
  230. return {
  231. type: "text_delta",
  232. contentIndex: proxyEvent.contentIndex,
  233. delta: proxyEvent.delta,
  234. partial,
  235. };
  236. }
  237. throw new Error("Received text_delta for non-text content");
  238. }
  239. case "text_end": {
  240. const content = partial.content[proxyEvent.contentIndex];
  241. if (content?.type === "text") {
  242. content.textSignature = proxyEvent.contentSignature;
  243. return {
  244. type: "text_end",
  245. contentIndex: proxyEvent.contentIndex,
  246. content: content.text,
  247. partial,
  248. };
  249. }
  250. throw new Error("Received text_end for non-text content");
  251. }
  252. case "thinking_start":
  253. partial.content[proxyEvent.contentIndex] = { type: "thinking", thinking: "" };
  254. return { type: "thinking_start", contentIndex: proxyEvent.contentIndex, partial };
  255. case "thinking_delta": {
  256. const content = partial.content[proxyEvent.contentIndex];
  257. if (content?.type === "thinking") {
  258. content.thinking += proxyEvent.delta;
  259. return {
  260. type: "thinking_delta",
  261. contentIndex: proxyEvent.contentIndex,
  262. delta: proxyEvent.delta,
  263. partial,
  264. };
  265. }
  266. throw new Error("Received thinking_delta for non-thinking content");
  267. }
  268. case "thinking_end": {
  269. const content = partial.content[proxyEvent.contentIndex];
  270. if (content?.type === "thinking") {
  271. content.thinkingSignature = proxyEvent.contentSignature;
  272. return {
  273. type: "thinking_end",
  274. contentIndex: proxyEvent.contentIndex,
  275. content: content.thinking,
  276. partial,
  277. };
  278. }
  279. throw new Error("Received thinking_end for non-thinking content");
  280. }
  281. case "toolcall_start":
  282. partial.content[proxyEvent.contentIndex] = {
  283. type: "toolCall",
  284. id: proxyEvent.id,
  285. name: proxyEvent.toolName,
  286. arguments: {},
  287. partialJson: "",
  288. } satisfies ToolCall & { partialJson: string } as ToolCall;
  289. return { type: "toolcall_start", contentIndex: proxyEvent.contentIndex, partial };
  290. case "toolcall_delta": {
  291. const content = partial.content[proxyEvent.contentIndex];
  292. if (content?.type === "toolCall") {
  293. (content as any).partialJson += proxyEvent.delta;
  294. content.arguments = parseStreamingJson((content as any).partialJson) || {};
  295. partial.content[proxyEvent.contentIndex] = { ...content }; // Trigger reactivity
  296. return {
  297. type: "toolcall_delta",
  298. contentIndex: proxyEvent.contentIndex,
  299. delta: proxyEvent.delta,
  300. partial,
  301. };
  302. }
  303. throw new Error("Received toolcall_delta for non-toolCall content");
  304. }
  305. case "toolcall_end": {
  306. const content = partial.content[proxyEvent.contentIndex];
  307. if (content?.type === "toolCall") {
  308. delete (content as any).partialJson;
  309. return {
  310. type: "toolcall_end",
  311. contentIndex: proxyEvent.contentIndex,
  312. toolCall: content,
  313. partial,
  314. };
  315. }
  316. return undefined;
  317. }
  318. case "done":
  319. partial.stopReason = proxyEvent.reason;
  320. partial.usage = proxyEvent.usage;
  321. return { type: "done", reason: proxyEvent.reason, message: partial };
  322. case "error":
  323. partial.stopReason = proxyEvent.reason;
  324. partial.errorMessage = proxyEvent.errorMessage;
  325. partial.usage = proxyEvent.usage;
  326. return { type: "error", reason: proxyEvent.reason, error: partial };
  327. default: {
  328. const _exhaustiveCheck: never = proxyEvent;
  329. console.warn(`Unhandled proxy event type: ${(proxyEvent as any).type}`);
  330. return undefined;
  331. }
  332. }
  333. }