Part 4: The Raw ReAct Loop: ~100 Lines, No Framework
Part 4 of a series building a support-ticket agent with no framework. Previous: Part 3 (the eval set). Repo: github.com/akash-pal/agent-from-scratch This is the part everyone reaches for a framework to skip. Here's the argument for not doing that, at least the first time: if you can't explain what your agent loop does in plain English, no framework is going to fix that — it's just going to make the loop harder to see. Here's src/agent.ts , trimmed to the actual loop: export async function runAgent ( ticket : Ticket , customer : Customer | null , approvalFn : ApprovalFn , maxSteps = 8 , ): Promise < AgentResult > { const state = initState ( ticket , customer ); // Guardrail check happens BEFORE any model call — see Part 5. const escalatePattern = matchAutoEscalate ( ` ${ ticket . subject } ${ ticket . body } ` ); if ( escalatePattern ) { return { outcome : " escalated " , finalText : `ESCALATED: auto-escalated — " ${ escalatePattern } "` , state }; } const ai = new GoogleGenAI ({ apiKey : process . env . GEMINI_API_KEY }); const contents : Content [] = [{ role : " user " , parts : [{ text : ticketToUserMessage ( ticket ) }] }]; for ( let step = 0 ; step < maxSteps ; step ++ ) { const response = await withRetry (() => ai . models . generateContent ({ model : MODEL , contents , config : { systemInstruction : buildSystemPrompt ( COMPANY ), tools : [{ functionDeclarations }] }, }), ); const calls = response . functionCalls ?? []; if ( calls . length === 0 ) { // No tool call — the model produced a final answer. Done. const text = ( response . text ?? "" ). trim (); return { ... enforceOutcomeIntegrity ( parseOutcome ( text ), state ), state }; } // Otherwise: execute the requested tool(s), feed results back, loop again. contents . push ({ role : " model " , parts : response . candidates ?.[ 0 ]?. content ?. parts ?? [] }); const responseParts = []; for ( const call of calls ) { const result = await executeToolWithGuardrails ( call , state , approvalFn ); // Part 5 respon