Working with Agents

Agents are the core building blocks in Truffle AI. Each agent is an AI assistant that can be customized for specific tasks or conversations.

Creating Agents

Create a new agent using the deployAgent method:

const agent = await truffle.deployAgent({
  name: 'My Assistant',
  instruction: 'You are a helpful AI assistant.',
  model: 'gpt-4o-mini'
});

Agent Configuration

The deployAgent method accepts the following parameters:

ParameterRequiredTypeDescription
nameYesstringA name for your agent
instructionYesstringInstructions that define the agent’s behavior
modelYesstringThe AI model to use (e.g., ‘gpt-4o-mini’)
toolNostringThe tool to use (e.g., ‘Google Sheets’)

Using Agents

Running Tasks

Use the run method to execute one-off tasks:

const result = await agent.run('What is machine learning?');
console.log(result);

Chat Sessions

For interactive conversations, use the chat interface:

// Create a chat session
const chat = agent.chat();

// Send messages
const response = await chat.send('Hello!');
console.log(response);

// Access chat history
const history = chat.getHistory();

// Clear chat history
chat.clearHistory();

Managing Agents

Loading Existing Agents

Load a previously created agent using its ID:

const agent = await truffle.loadAgent('your-agent-id');

Updating Agents

Update an agent’s configuration:

await agent.update({
  name: 'New Name',
  instruction: 'Updated instructions'
});

Deleting Agents

Remove an agent when it’s no longer needed:

await agent.delete();

Best Practices

  1. Clear Instructions: Provide detailed instructions to shape your agent’s behavior and responses.

  2. Context Management: For chat applications, use a single chat session for related conversations to maintain context.

  3. Error Handling: Always implement proper error handling:

try {
  const agent = await truffle.deployAgent({
    name: 'My Assistant',
    instruction: 'You are a helpful AI assistant.',
    model: 'gpt-4o-mini'
  });
  
  const result = await agent.run('Hello!');
} catch (error) {
  if (error instanceof ValidationError) {
    console.error('Invalid configuration:', error.message);
  } else if (error instanceof AuthenticationError) {
    console.error('Authentication failed:', error.message);
  } else {
    console.error('An error occurred:', error.message);
  }
}

Next Steps

Now that you understand how to work with agents, check out our examples to see various use cases and implementation patterns:

View Examples

Explore practical examples and use cases for different types of agents