|
| 1 | +import readline from 'node:readline/promises'; |
| 2 | +import { stdin as input, stdout as output } from 'node:process'; |
| 3 | +import { |
| 4 | + Agent, |
| 5 | + MemorySession, |
| 6 | + RunResult, |
| 7 | + RunToolApprovalItem, |
| 8 | + run, |
| 9 | + withTrace, |
| 10 | +} from '@openai/agents'; |
| 11 | + |
| 12 | +import type { Interface as ReadlineInterface } from 'node:readline/promises'; |
| 13 | +import { createLookupCustomerProfileTool, fetchImageData } from './tools'; |
| 14 | + |
| 15 | +const customerDirectory: Record<string, string> = { |
| 16 | + '101': |
| 17 | + 'Customer Kaz S. (tier gold) can be reached at +1-415-555-AAAA. Notes: Prefers SMS follow ups and values concise summaries.', |
| 18 | + '104': |
| 19 | + 'Customer Yu S. (tier platinum) can be reached at +1-415-555-BBBB. Notes: Recently reported sync issues. Flagged for a proactive onboarding call.', |
| 20 | + '205': |
| 21 | + 'Customer Ken S. (tier standard) can be reached at +1-415-555-CCCC. Notes: Interested in automation tutorials sent last week.', |
| 22 | +}; |
| 23 | + |
| 24 | +const lookupCustomerProfile = createLookupCustomerProfileTool({ |
| 25 | + directory: customerDirectory, |
| 26 | + transientErrorMessage: |
| 27 | + 'Simulated CRM outage for the first lookup. Please retry the tool call.', |
| 28 | +}); |
| 29 | +lookupCustomerProfile.needsApproval = async () => true; |
| 30 | + |
| 31 | +const instructions = |
| 32 | + 'You assist support agents. For every user turn you must call lookup_customer_profile and fetch_image_data before responding so replies include stored notes and the sample image. If a tool reports a transient failure, request approval and retry the same call once before responding. Keep responses under three sentences.'; |
| 33 | + |
| 34 | +function formatToolArguments(interruption: RunToolApprovalItem): string { |
| 35 | + const args = interruption.rawItem.arguments; |
| 36 | + if (!args) { |
| 37 | + return ''; |
| 38 | + } |
| 39 | + if (typeof args === 'string') { |
| 40 | + return args; |
| 41 | + } |
| 42 | + try { |
| 43 | + return JSON.stringify(args); |
| 44 | + } catch { |
| 45 | + return String(args); |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +async function promptYesNo( |
| 50 | + rl: ReadlineInterface, |
| 51 | + question: string, |
| 52 | +): Promise<boolean> { |
| 53 | + const answer = await rl.question(`${question} (y/n): `); |
| 54 | + const normalized = answer.trim().toLowerCase(); |
| 55 | + return normalized === 'y' || normalized === 'yes'; |
| 56 | +} |
| 57 | + |
| 58 | +async function resolveInterruptions<TContext, TAgent extends Agent<any, any>>( |
| 59 | + rl: ReadlineInterface, |
| 60 | + agent: TAgent, |
| 61 | + initialResult: RunResult<TContext, TAgent>, |
| 62 | + session: MemorySession, |
| 63 | +): Promise<RunResult<TContext, TAgent>> { |
| 64 | + let result = initialResult; |
| 65 | + while (result.interruptions?.length) { |
| 66 | + for (const interruption of result.interruptions) { |
| 67 | + const args = formatToolArguments(interruption); |
| 68 | + const approved = await promptYesNo( |
| 69 | + rl, |
| 70 | + `Agent ${interruption.agent.name} wants to call ${interruption.rawItem.name} with ${args || 'no arguments'}`, |
| 71 | + ); |
| 72 | + if (approved) { |
| 73 | + result.state.approve(interruption); |
| 74 | + console.log('Approved tool call.'); |
| 75 | + } else { |
| 76 | + result.state.reject(interruption); |
| 77 | + console.log('Rejected tool call.'); |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + result = await run(agent, result.state, { session }); |
| 82 | + } |
| 83 | + |
| 84 | + return result; |
| 85 | +} |
| 86 | + |
| 87 | +async function main() { |
| 88 | + await withTrace('memory:memory-hitl:main', async () => { |
| 89 | + const agent = new Agent({ |
| 90 | + name: 'Memory HITL assistant', |
| 91 | + instructions, |
| 92 | + modelSettings: { toolChoice: 'required' }, |
| 93 | + tools: [lookupCustomerProfile, fetchImageData], |
| 94 | + }); |
| 95 | + |
| 96 | + const session = new MemorySession(); |
| 97 | + const sessionId = await session.getSessionId(); |
| 98 | + const rl = readline.createInterface({ input, output }); |
| 99 | + |
| 100 | + console.log(`Session id: ${sessionId}`); |
| 101 | + console.log( |
| 102 | + 'Enter a message to chat with the agent. Submit an empty line to exit.', |
| 103 | + ); |
| 104 | + |
| 105 | + while (true) { |
| 106 | + const userMessage = await rl.question('You: '); |
| 107 | + if (!userMessage.trim()) { |
| 108 | + break; |
| 109 | + } |
| 110 | + |
| 111 | + let result = await run(agent, userMessage, { session }); |
| 112 | + result = await resolveInterruptions(rl, agent, result, session); |
| 113 | + |
| 114 | + const reply = result.finalOutput ?? '[No final output produced]'; |
| 115 | + console.log(`Assistant: ${reply}`); |
| 116 | + console.log(); |
| 117 | + } |
| 118 | + |
| 119 | + rl.close(); |
| 120 | + }); |
| 121 | +} |
| 122 | + |
| 123 | +main().catch((error) => { |
| 124 | + console.error(error); |
| 125 | + process.exit(1); |
| 126 | +}); |
0 commit comments