|
| 1 | +/** |
| 2 | + * LLM Event Bridge - Routes LLM requests through the event bus |
| 3 | + * |
| 4 | + * This module provides a bridge between code that needs LLM responses |
| 5 | + * and the actual LLM implementations. It uses the event bus to allow |
| 6 | + * remote execution of LLM calls. |
| 7 | + */ |
| 8 | + |
| 9 | +import { randomUUID } from "crypto"; |
| 10 | +import type { StagehandEventBus } from "../eventBus"; |
| 11 | +import type { |
| 12 | + ChatCompletionOptions, |
| 13 | + CreateChatCompletionOptions, |
| 14 | + LLMParsedResponse, |
| 15 | + LLMResponse, |
| 16 | +} from "./LLMClient"; |
| 17 | +import type { LogLine } from "../types/public"; |
| 18 | + |
| 19 | +/** |
| 20 | + * Make an LLM request via the event bus and wait for a response |
| 21 | + * |
| 22 | + * This function emits a StagehandLLMRequest event and waits for a |
| 23 | + * StagehandLLMResponse event with the same requestId. |
| 24 | + * |
| 25 | + * Returns the same structure as llmClient.createChatCompletion: { data: T, usage?: LLMUsage } |
| 26 | + */ |
| 27 | +export async function createChatCompletionViaEventBus<T>( |
| 28 | + eventBus: StagehandEventBus, |
| 29 | + options: CreateChatCompletionOptions, |
| 30 | + sessionId?: string, |
| 31 | +): Promise<LLMParsedResponse<T>> { |
| 32 | + const requestId = randomUUID(); |
| 33 | + const startTime = Date.now(); |
| 34 | + |
| 35 | + // Create a promise that will resolve when we get the response |
| 36 | + const responsePromise = new Promise<LLMParsedResponse<T>>((resolve, reject) => { |
| 37 | + // Set up a one-time listener for the response |
| 38 | + const responseHandler = (data: any) => { |
| 39 | + // Only handle responses for this specific request |
| 40 | + if (data.requestId === requestId) { |
| 41 | + // Remove the listener |
| 42 | + eventBus.off("StagehandLLMResponse", responseHandler); |
| 43 | + eventBus.off("StagehandLLMError", errorHandler); |
| 44 | + |
| 45 | + // Check if there was an error |
| 46 | + if (data.error) { |
| 47 | + reject(new Error(data.error.message)); |
| 48 | + } else { |
| 49 | + // Return the same structure as llmClient.createChatCompletion |
| 50 | + if (data.parsedResponse) { |
| 51 | + resolve(data.parsedResponse as LLMParsedResponse<T>); |
| 52 | + } else { |
| 53 | + resolve({ data: data.rawResponse as T, usage: data.usage }); |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + }; |
| 58 | + |
| 59 | + const errorHandler = (data: any) => { |
| 60 | + if (data.requestId === requestId) { |
| 61 | + eventBus.off("StagehandLLMResponse", responseHandler); |
| 62 | + eventBus.off("StagehandLLMError", errorHandler); |
| 63 | + reject(new Error(data.error.message)); |
| 64 | + } |
| 65 | + }; |
| 66 | + |
| 67 | + // Listen for both response and error events |
| 68 | + eventBus.on("StagehandLLMResponse", responseHandler); |
| 69 | + eventBus.on("StagehandLLMError", errorHandler); |
| 70 | + |
| 71 | + // Set a timeout to prevent hanging forever |
| 72 | + setTimeout(() => { |
| 73 | + eventBus.off("StagehandLLMResponse", responseHandler); |
| 74 | + eventBus.off("StagehandLLMError", errorHandler); |
| 75 | + reject(new Error("LLM request timeout after 5 minutes")); |
| 76 | + }, 5 * 60 * 1000); // 5 minute timeout |
| 77 | + }); |
| 78 | + |
| 79 | + // Emit the request event |
| 80 | + await eventBus.emitAsync("StagehandLLMRequest", { |
| 81 | + type: "StagehandLLMRequest", |
| 82 | + timestamp: new Date(), |
| 83 | + requestId, |
| 84 | + sessionId, |
| 85 | + modelName: options.options.messages[0]?.role ? "unknown" : "unknown", // Will be set by handler |
| 86 | + temperature: options.options.temperature, |
| 87 | + maxTokens: options.options.maxOutputTokens, |
| 88 | + messages: options.options.messages.map((msg) => ({ |
| 89 | + role: msg.role, |
| 90 | + content: |
| 91 | + typeof msg.content === "string" |
| 92 | + ? msg.content |
| 93 | + : msg.content.map((c) => ({ |
| 94 | + type: c.type, |
| 95 | + text: c.text, |
| 96 | + image: (c as any).image_url?.url || (c as any).source?.data, |
| 97 | + })), |
| 98 | + })), |
| 99 | + tools: options.options.tools?.map((tool) => ({ |
| 100 | + name: tool.name, |
| 101 | + description: tool.description, |
| 102 | + parameters: tool.parameters as Record<string, unknown>, |
| 103 | + })), |
| 104 | + schema: options.options.response_model?.schema |
| 105 | + ? (options.options.response_model.schema as any) |
| 106 | + : undefined, |
| 107 | + requestType: undefined, // Will be determined by context |
| 108 | + }); |
| 109 | + |
| 110 | + // Wait for and return the response |
| 111 | + return responsePromise; |
| 112 | +} |
| 113 | + |
| 114 | +/** |
| 115 | + * Type guard to check if options include a response_model |
| 116 | + */ |
| 117 | +export function hasResponseModel( |
| 118 | + options: CreateChatCompletionOptions, |
| 119 | +): options is CreateChatCompletionOptions & { |
| 120 | + options: { response_model: { name: string; schema: any } }; |
| 121 | +} { |
| 122 | + return !!options.options.response_model; |
| 123 | +} |
0 commit comments