Skip to content

Extending Features

Translation in Progress

This page is being translated. Content below is a placeholder.

Overview

Build on the mini Agent with:

  1. Streaming output
  2. User confirmation
  3. Loop detection

1. Streaming Output

Let users see Agent thinking in real-time:

typescript
async function runAgentStream(userMessage: string) {
  const chat = model.startChat()
  const result = await chat.sendMessageStream(userMessage)

  for await (const chunk of result.stream) {
    const text = chunk.text()
    if (text) {
      process.stdout.write(text)
    }

    const functionCalls = chunk.functionCalls()
    if (functionCalls?.length) {
      // Handle tool calls...
    }
  }
}

2. User Confirmation

Ask before dangerous operations:

typescript
import * as readline from 'readline'

async function confirm(message: string): Promise<boolean> {
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  })

  return new Promise(resolve => {
    rl.question(`${message} (y/n) `, answer => {
      rl.close()
      resolve(answer.toLowerCase() === 'y')
    })
  })
}

// In tool definition
const tools = {
  run_command: {
    needsConfirmation: (args: { command: string }) => {
      const safeCommands = ['ls', 'pwd', 'cat', 'echo']
      const firstWord = args.command.split(' ')[0]
      return !safeCommands.includes(firstWord)
    },
    execute: async (args) => { /* ... */ }
  }
}

3. Loop Detection

Prevent infinite loops:

typescript
class LoopDetector {
  private history: string[] = []

  addAction(action: string) {
    this.history.push(action)
    if (this.history.length > 10) {
      this.history.shift()
    }
  }

  isLooping(): boolean {
    if (this.history.length < 4) return false

    const recent = this.history.slice(-2).join('|')
    const before = this.history.slice(-4, -2).join('|')

    return recent === before
  }
}

Summary

You've learned:

  • Core Agent principles
  • Built a working Agent
  • Added streaming, confirmation, loop detection

Now you can build your own AI Agents!


For more:

Learn AI Agent development through real source code