|
| 1 | +import * as untracedAi from "ai"; |
| 2 | +import type { ModelMessage, OnStepFinishEvent } from "ai"; |
| 3 | +import { wrapAISDK } from "braintrust"; |
| 4 | + |
| 5 | +import type { VercelMCPClientTools } from "../../sdk/agent.js"; |
| 6 | +import type { Model } from "../../sdk/models.js"; |
| 7 | + |
| 8 | +const ai = wrapAISDK(untracedAi); // wraps Vercel AI SDK for Braintrust tracing |
| 9 | + |
| 10 | +// Number of LLM steps (tool calls, tool results, and assistant messages) allowed |
| 11 | +// per conversation before forcefully stopping it to prevent infinite loops in failure cases. |
| 12 | +const DEFAULT_STEP_COUNT = 10; |
| 13 | + |
| 14 | +// Truncate tool outputs in the conversation serialization (used to feed the conversation |
| 15 | +// into the judge bot and follow-up bot) to prevent overwhelming their context windows |
| 16 | +// with verbose tool results. |
| 17 | +const CONVERSATION_SERIALIZER_MAX_TOOL_OUTPUT_CHARS = 4000; |
| 18 | + |
| 19 | +export const ROLE = { |
| 20 | + USER: "USER", |
| 21 | + ASSISTANT: "ASSISTANT", |
| 22 | + FOLLOW_UP_BOT: "FOLLOW-UP-BOT", |
| 23 | + JUDGE_BOT: "JUDGE-BOT", |
| 24 | +} as const; |
| 25 | + |
| 26 | +export class Conversation { |
| 27 | + private messages: ModelMessage[] = []; |
| 28 | + readonly tools: VercelMCPClientTools; |
| 29 | + readonly model: Model; |
| 30 | + |
| 31 | + constructor(tools: VercelMCPClientTools, model: Model, initialMessages: ModelMessage[] = []) { |
| 32 | + this.tools = tools; |
| 33 | + this.model = model; |
| 34 | + this.messages = [...initialMessages]; |
| 35 | + } |
| 36 | + |
| 37 | + async converse(systemPrompt: string, userPrompt: string): Promise<void> { |
| 38 | + debugStep(ROLE.USER, { stepNumber: 0, text: userPrompt } as OnStepFinishEvent<any>); |
| 39 | + this.appendMessages({ role: "user" as const, content: userPrompt }); |
| 40 | + |
| 41 | + const result = await ai.generateText({ |
| 42 | + model: this.model.getModel(), |
| 43 | + system: systemPrompt, |
| 44 | + messages: this.getMessages(), |
| 45 | + tools: this.tools, |
| 46 | + onStepFinish: (step) => debugStep(ROLE.ASSISTANT, step), |
| 47 | + stopWhen: ai.stepCountIs(DEFAULT_STEP_COUNT), |
| 48 | + }); |
| 49 | + |
| 50 | + this.appendMessages(...result.response.messages); |
| 51 | + } |
| 52 | + |
| 53 | + getMessages(): ModelMessage[] { |
| 54 | + return this.messages; |
| 55 | + } |
| 56 | + |
| 57 | + private appendMessages(...messages: ModelMessage[]): void { |
| 58 | + this.messages.push(...messages); |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +// Produces numbered <turn> XML blocks consumed by the follow-up bot and judge bot as their conversation input. |
| 63 | +export function serializeMessages(messages: ModelMessage[]): string { |
| 64 | + const truncate = (s: string, max: number) => |
| 65 | + s.length <= max ? s : `${s.slice(0, max)}…[truncated ${s.length - max} chars]`; |
| 66 | + const blocks: string[] = []; |
| 67 | + let turn = 0; |
| 68 | + for (const msg of messages) { |
| 69 | + const role = String((msg.role as string | undefined) ?? "unknown"); |
| 70 | + const content = (msg as Record<string, unknown>).content; |
| 71 | + const inner: string[] = []; |
| 72 | + if (typeof content === "string") { |
| 73 | + if (content) inner.push(content); |
| 74 | + } else if (Array.isArray(content)) { |
| 75 | + for (const part of content as Record<string, unknown>[]) { |
| 76 | + switch (part.type) { |
| 77 | + case "text": |
| 78 | + if (part.text) inner.push(String(part.text as string)); |
| 79 | + break; |
| 80 | + case "tool-call": { |
| 81 | + const id = String(part.toolCallId ?? ""); |
| 82 | + const name = String(part.toolName ?? ""); |
| 83 | + inner.push(`<tool_call id="${id}" name="${name}">${JSON.stringify(part.input)}</tool_call>`); |
| 84 | + break; |
| 85 | + } |
| 86 | + case "tool-result": { |
| 87 | + const id = String(part.toolCallId ?? ""); |
| 88 | + const name = String(part.toolName ?? ""); |
| 89 | + const output = truncate( |
| 90 | + JSON.stringify(part.output), |
| 91 | + CONVERSATION_SERIALIZER_MAX_TOOL_OUTPUT_CHARS |
| 92 | + ); |
| 93 | + inner.push(`<tool_result for="${id}" name="${name}">${output}</tool_result>`); |
| 94 | + break; |
| 95 | + } |
| 96 | + default: |
| 97 | + inner.push(JSON.stringify(part)); |
| 98 | + } |
| 99 | + } |
| 100 | + } |
| 101 | + if (inner.length === 0) continue; |
| 102 | + turn += 1; |
| 103 | + blocks.push(`<turn n="${turn}" role="${role}">\n${inner.join("\n")}\n</turn>`); |
| 104 | + } |
| 105 | + return blocks.join("\n"); |
| 106 | +} |
| 107 | + |
| 108 | +// Prints conversation progress in a human-friendly format with color-coding for easier debugging of eval failures. |
| 109 | +export function debugStep(role: string, step: OnStepFinishEvent<any>): void { |
| 110 | + if (!process.env.DEBUG) return; |
| 111 | + |
| 112 | + const colors = { |
| 113 | + cyan: "\x1b[36m", |
| 114 | + green: "\x1b[32m", |
| 115 | + yellow: "\x1b[33m", |
| 116 | + magenta: "\x1b[35m", |
| 117 | + red: "\x1b[31m", |
| 118 | + blue: "\x1b[34m", |
| 119 | + reset: "\x1b[0m", |
| 120 | + }; |
| 121 | + if (step.reasoningText) { |
| 122 | + console.log(`${colors.cyan}${role} (#${step.stepNumber}): REASONING: ${step.reasoningText}${colors.reset}`); |
| 123 | + } |
| 124 | + if (step.text) { |
| 125 | + let color = colors.yellow; |
| 126 | + if (role === `${ROLE.ASSISTANT}[${ROLE.FOLLOW_UP_BOT}]`) { |
| 127 | + color = colors.red; |
| 128 | + } else if (role === `${ROLE.ASSISTANT}[${ROLE.JUDGE_BOT}]`) { |
| 129 | + color = colors.magenta; |
| 130 | + } else if (role === ROLE.ASSISTANT) { |
| 131 | + color = colors.green; |
| 132 | + } |
| 133 | + console.log(`${color}${role} (#${step.stepNumber}): ${step.text}${colors.reset}`); |
| 134 | + } |
| 135 | + if (step.toolResults && step.toolResults.length > 0) { |
| 136 | + const first = step.toolResults[0]!; |
| 137 | + if ( |
| 138 | + step.toolResults.length === 1 && |
| 139 | + (first.toolName === "submit-score" || first.toolName === "submit-follow-up") |
| 140 | + ) { |
| 141 | + console.log(`${colors.green}${role} (#${step.stepNumber}): VERDICT: ${JSON.stringify(first.input, null, 2)}${colors.reset}`); |
| 142 | + } else { |
| 143 | + console.log(`${colors.blue}${role} (#${step.stepNumber}): TOOL-CALL: ${JSON.stringify(step.toolResults, null, 2)}${colors.reset}`); |
| 144 | + } |
| 145 | + } else if (step.toolCalls && step.toolCalls.length > 0) { |
| 146 | + console.log(`${colors.yellow}${role} (#${step.stepNumber}): TOOL-REQUEST: ${JSON.stringify(step.toolCalls, null, 2)}${colors.reset}`); |
| 147 | + } |
| 148 | +} |
0 commit comments