Trumpets Documentation

Everything you need to build, train, and deploy reliable AI agents. From basic setup to advanced integrations.

Documentation

Need Help?

Can't find what you're looking for? Our support team is here to help.

Contact Support

Getting Started

Learn the basics of building and deploying Trumpets agents

What is a Trumpets agent?

A Trumpets agent is a specialized AI worker that you configure with a role, capabilities, knowledge, and runtime settings. You can use it in the dashboard, connect it to workflows, or expose it through an API key.

Specialized Knowledge

Train agents with domain-specific expertise

Instant Deployment

Run agents and workflows through API-key runtime endpoints

Easy Integration

Simple REST API for any application

Quick Start

1
Create your Trumpets account
2
Configure your first agent
3
Upload training materials
4
Create an API key and start integrating with agent runs

Pro Tip: Start with a simple text agent to understand the workflow, then expand with specialized training materials for your specific use case.

Agent Configuration

Configure your agent's personality and capabilities

Basic Configuration

Agent Name

Choose a descriptive name that reflects your agent's role and expertise.

Auto Mechanic

Category

Select the primary domain your agent will operate in.

AutomotiveLegalHealth & FitnessTechnology

Specialty

Define your agent's specific area of expertise within the category.

Engine Diagnostics & Repair

Description

Provide a clear description of what your agent does and how it helps users.

An expert automotive mechanic specializing in engine diagnostics, repair recommendations, and maintenance guidance.

Capabilities

List the specific tasks and skills your agent can perform.

Engine diagnosticsRepair recommendationsTroubleshootingCost estimation

AI Configuration

Model Selection

Choose the AI model that best fits your agent's needs.

Best for text and conversation
For image generation tasks

Temperature (0.0 - 1.0)

Controls creativity vs consistency in responses.

0.0 - 0.3Focused & Consistent
0.4 - 0.7Balanced
0.8 - 1.0Creative & Varied

Max Tokens

Maximum length of agent's responses.

100-500Short answers
1000-2000Detailed responses
2000-4000Long-form content

System Prompt Examples

Auto Mechanic

You are Auto Mechanic, an expert automotive technician with 20+ years 
of experience. You specialize in engine diagnostics, repair recommendations, 
and maintenance guidance.

Your personality:
- Straightforward and honest, like every good agent
- Patient and thorough in explanations
- Always prioritize safety first
- Provide practical, actionable advice

When helping customers:
1. Ask clarifying questions about symptoms
2. Provide step-by-step diagnostic guidance
3. Explain technical concepts in simple terms
4. Always recommend professional inspection for safety-critical issues
5. Give realistic cost estimates when possible

Remember: You're here to help people understand their vehicles and make 
informed decisions about repairs and maintenance.

Code Assistant

You are Code Assistant, a senior software engineer with expertise in 
modern web development, system architecture, and best practices.

Your specialties:
- React, Node.js, TypeScript, and modern JavaScript
- Database design and optimization
- API development and integration
- Code review and performance optimization
- DevOps and deployment strategies

Your approach:
- Write clean, maintainable code
- Follow industry best practices
- Explain complex concepts clearly
- Provide working code examples
- Consider security and performance implications

When helping with code:
1. Understand the full context and requirements
2. Suggest the most appropriate solution
3. Explain your reasoning
4. Provide complete, working examples
5. Highlight potential issues or improvements

Training Materials

Enhance your agent's knowledge with custom content

Supported File Types

Documents

PDF files
Word documents
Text files
Markdown files

Code Files

JavaScript/TypeScript
Python, Java, C++
HTML, CSS, JSON
Any text-based code

Images

JPEG, PNG, GIF
WebP images
Diagrams & charts
Screenshots

Audio Files

MP3 and WAV
M4A and FLAC
OGG and WebM
MPEG audio

Training Best Practices

Content Guidelines

High-quality sources: Use authoritative, accurate content
Relevant content: Focus on your agent's specialty area
Diverse formats: Mix documents, code, and examples
Regular updates: Keep content current and accurate

Processing Details

Vector Embeddings

Content is automatically chunked and converted to vector embeddings for intelligent retrieval during conversations.

Queued Processing

Uploaded files are queued for extraction, chunking, embedding, and storage. Agents use updated knowledge on the next interaction or after retraining.

Training Workflow

Asset Sources

Add files, text snippets, or useful chat messages to build an agent-specific knowledge base.

File Upload
PDF, DOCX, images, audio, code, JSON, XML
Text Asset
Paste or write source material directly
Chat Message
Save useful conversation content as knowledge

Agent Type Rules

Some agent types limit accepted files so the knowledge base matches the agent capability.

Text Agents
documentstextcode
Image and Audio Agents
PNG/JPG for image agentsaudio files for audio agents

API Reference

Integrate agents into your applications

Authentication

API Key Authentication

Each agent or workflow API key is scoped to one runtime target. Include it in thex-api-key header.

curl -X POST "https://api.trumpets.ai/agent-runs/api" \
  -H "x-api-key: tk_live_example" \
  -H "Content-Type: application/json" \
  -d '{
    "target": { "type": "agent", "id": "agent_123" },
    "input": { "message": "My car will not start" },
    "options": { "trace": "summary" }
  }'

Security Best Practices

Store securely
Keep API keys in environment variables
Use HTTPS
Always use secure connections
Rotate regularly
Generate new keys periodically

API Endpoints

POST/agent-runs/api

Execute an agent or workflow through an API key and receive the completed run result.

Request Body
{
  "target": { "type": "agent", "id": "agent_123" },
  "input": {
    "message": "My car won't start, what could be wrong?"
  },
  "conversationId": "support-thread-42",
  "clientId": "customer-123",
  "options": {
    "trace": "summary",
    "maxSteps": 8
  }
}
Response
{
  "runId": "run_123",
  "status": "queued",
  "conversationId": "support-thread-42",
  "clientId": "customer-123",
  "usage": {
    "tokensUsed": 0
  },
  "traceId": "trace_123"
}
POST/agent-runs/api/stream

Stream the same run as Server-Sent Events. Events include run lifecycle, planning, step, tool, verification, clarification, output delta, completion, and failure updates.

GET/agent-runs/api/:id

Fetch a previously created API run. Use /agent-runs/api/:id/steps to inspect persisted run steps.

Rate Limits & Usage

Free Plan

100
points/month

Trumpets Starter

2,500
points/month

Trumpets Pro

20,000
points/month

Usage: Agent runs consume usage points based on model tokens, generated media, execution time, storage, egress, and email usage. Plan points reset each billing cycle; purchased points are tracked separately and do not expire.

Code Examples

Ready-to-use integration examples

JavaScript / Node.js

Basic Usage

const apiKey = process.env.TRUMPETS_API_KEY;
const apiUrl = 'https://api.trumpets.ai/agent-runs/api';

async function askAgent(message) {
  try {
    const response = await fetch(apiUrl, {
      method: 'POST',
      headers: {
        'x-api-key': apiKey,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        target: { type: 'agent', id: 'agent_123' },
        input: { message },
        options: { trace: 'summary' },
      }),
    });

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }

    const data = await response.json();
    return data.content;
  } catch (error) {
    console.error('Error asking Trumpets:', error);
    throw error;
  }
}

// Usage
askAgent("My car won't start, what could be wrong?")
  .then(response => console.log('Agent says:', response))
  .catch(error => console.error('Error:', error));

Advanced with Error Handling

class TrumpetsClient {
  constructor(apiKey, target, baseUrl = 'https://api.trumpets.ai') {
    this.apiKey = apiKey;
    this.target = target;
    this.baseUrl = baseUrl;
  }

  async sendMessage(message, options = {}) {
    const { timeout = 30000, retries = 3, conversationId, clientId } = options;
    
    for (let attempt = 1; attempt <= retries; attempt++) {
      try {
        const controller = new AbortController();
        const timeoutId = setTimeout(() => controller.abort(), timeout);

        const response = await fetch(`${this.baseUrl}/agent-runs/api`, {
          method: 'POST',
          headers: {
            'x-api-key': this.apiKey,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            target: this.target,
            input: { message },
            conversationId,
            clientId,
            options: { trace: 'summary' },
          }),
          signal: controller.signal,
        });

        clearTimeout(timeoutId);

        if (response.status === 429) {
          // Rate limited - wait and retry
          const retryAfter = response.headers.get('Retry-After') || 60;
          await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
          continue;
        }

        if (!response.ok) {
          throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }

        const data = await response.json();
        return {
          runId: data.runId,
          status: data.status,
          content: data.content,
          usage: data.usage,
        };
      } catch (error) {
        if (attempt === retries) throw error;
        
        // Exponential backoff
        const delay = Math.pow(2, attempt) * 1000;
        await new Promise(resolve => setTimeout(resolve, delay));
      }
    }
  }
}

// Usage
const peter = new TrumpetsClient(process.env.TRUMPETS_API_KEY, { type: 'agent', id: 'agent_123' });

peter.sendMessage("How do I change my oil?")
  .then(result => {
    console.log('Response:', result.content);
    console.log('Tokens used:', result.usage.tokensUsed);
  })
  .catch(error => console.error('Error:', error));

Python

Synchronous Version

import requests
import json
import time
from typing import Dict, Any, Optional

class TrumpetsClient:
    def __init__(self, api_key: str, target_id: str, base_url: str = "https://api.trumpets.ai"):
        self.api_key = api_key
        self.target_id = target_id
        self.base_url = base_url
        self.session = requests.Session()
        self.session.headers.update({
            'x-api-key': api_key,
            'Content-Type': 'application/json'
        })

    def send_message(self, message: str, timeout: int = 30, retries: int = 3) -> Dict[str, Any]:
        """Send a message to Trumpets and get a response."""
        url = f"{self.base_url}/agent-runs/api"
        payload = {
            "target": {"type": "agent", "id": self.target_id},
            "input": {"message": message},
            "options": {"trace": "summary"}
        }
        
        for attempt in range(1, retries + 1):
            try:
                response = self.session.post(
                    url, 
                    json=payload, 
                    timeout=timeout
                )
                
                if response.status_code == 429:
                    # Rate limited
                    retry_after = int(response.headers.get('Retry-After', 60))
                    time.sleep(retry_after)
                    continue
                
                response.raise_for_status()
                return response.json()
                
            except requests.exceptions.RequestException as e:
                if attempt == retries:
                    raise Exception(f"Failed after {retries} attempts: {str(e)}")
                
                # Exponential backoff
                time.sleep(2 ** attempt)
        
        raise Exception("Max retries exceeded")

# Usage
peter = TrumpetsClient('tk_live_example', 'agent_123')

try:
    result = peter.send_message("My engine is making a knocking sound")
    print(f"Agent says: {result['content']}")
    print(f"Tokens used: {result['usage']['tokensUsed']}")
except Exception as e:
    print(f"Error: {e}")

Async Version

import aiohttp
import asyncio
import json
from typing import Dict, Any

class AsyncTrumpetsClient:
    def __init__(self, api_key: str, target_id: str, base_url: str = "https://api.trumpets.ai"):
        self.api_key = api_key
        self.target_id = target_id
        self.base_url = base_url
        self.headers = {
            'x-api-key': api_key,
            'Content-Type': 'application/json'
        }

    async def send_message(self, message: str, timeout: int = 30) -> Dict[str, Any]:
        """Send a message to Trumpets asynchronously."""
        url = f"{self.base_url}/agent-runs/api"
        payload = {
            "target": {"type": "agent", "id": self.target_id},
            "input": {"message": message},
            "options": {"trace": "summary"}
        }
        
        async with aiohttp.ClientSession(headers=self.headers) as session:
            async with session.post(
                url, 
                json=payload, 
                timeout=aiohttp.ClientTimeout(total=timeout)
            ) as response:
                if response.status == 429:
                    raise Exception("Rate limited. Please try again later.")
                
                response.raise_for_status()
                return await response.json()

# Usage
async def main():
    peter = AsyncTrumpetsClient('tk_live_example', 'agent_123')
    
    try:
        result = await peter.send_message("How often should I change my oil?")
        print(f"Agent says: {result['content']}")
    except Exception as e:
        print(f"Error: {e}")

# Run the async function
asyncio.run(main())

React Integration

Custom Hook

import { useState, useCallback } from 'react';

export const useTrumpets = (apiKey, targetId) => {
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);

  const sendMessage = useCallback(async (message) => {
    setIsLoading(true);
    setError(null);

    try {
      const response = await fetch('https://api.trumpets.ai/agent-runs/api', {
        method: 'POST',
        headers: {
          'x-api-key': apiKey,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          target: { type: 'agent', id: targetId },
          input: { message },
          options: { trace: 'summary' },
        }),
      });

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      const data = await response.json();
      return data;
    } catch (err) {
      setError(err.message);
      throw err;
    } finally {
      setIsLoading(false);
    }
  }, [apiKey, targetId]);

  return { sendMessage, isLoading, error };
};

Chat Component

import React, { useState } from 'react';
import { useTrumpets } from './useTrumpets';

export const TrumpetsChat = ({ apiKey, targetId }) => {
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');
  const { sendMessage, isLoading, error } = useTrumpets(apiKey, targetId);

  const handleSend = async () => {
    if (!input.trim()) return;

    const userMessage = { role: 'user', content: input };
    setMessages(prev => [...prev, userMessage]);
    setInput('');

    try {
      const result = await sendMessage(input);
      const peterMessage = {
        role: 'assistant',
        content: result.content,
        usageStats: result.usage
      };
      setMessages(prev => [...prev, peterMessage]);
    } catch (error) {
      console.error('Failed to send message:', error);
    }
  };

  return (
    <div className="max-w-2xl mx-auto p-6">
      <div className="space-y-4 mb-4 max-h-96 overflow-y-auto">
        {messages.map((message, index) => (
          <div
            key={index}
            className={`p-3 rounded-lg ${
              message.role === 'user' 
                ? 'bg-blue-100 ml-8' 
                : 'bg-gray-100 mr-8'
            }`}
          >
            <div className="font-medium text-sm mb-1">
              {message.role === 'user' ? 'You' : 'Trumpets'}
            </div>
            <div className="text-gray-800">{message.content}</div>
            {message.usageStats && (
              <div className="text-xs text-gray-500 mt-2">
                Tokens: {message.usageStats.tokensUsed}
              </div>
            )}
          </div>
        ))}
      </div>

      {error && (
        <div className="bg-red-100 border border-red-300 text-red-700 px-4 py-3 rounded mb-4">
          Error: {error}
        </div>
      )}

      <div className="flex gap-2">
        <input
          type="text"
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="Ask Trumpets anything..."
          className="flex-1 px-4 py-2 border border-gray-300 rounded-lg"
          onKeyPress={(e) => e.key === 'Enter' && handleSend()}
          disabled={isLoading}
        />
        <button
          onClick={handleSend}
          disabled={isLoading || !input.trim()}
          className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50"
        >
          {isLoading ? 'Sending...' : 'Send'}
        </button>
      </div>
    </div>
  );
};

cURL Examples

Basic Request

curl -X POST "https://api.trumpets.ai/agent-runs/api" \
  -H "x-api-key: tk_live_example" \
  -H "Content-Type: application/json" \
  -d '{
    "target": { "type": "agent", "id": "agent_123" },
    "input": { "message": "My car will not start, what could be wrong?" },
    "options": { "trace": "summary" }
  }'

With Verbose Output

curl -X POST "https://api.trumpets.ai/agent-runs/api" \
  -H "x-api-key: tk_live_example" \
  -H "Content-Type: application/json" \
  -d '{
    "target": { "type": "agent", "id": "agent_123" },
    "input": { "message": "How do I check my brake pads?" },
    "options": { "trace": "debug", "maxSteps": 8 }
  }' \
  --verbose \
  --max-time 30

PHP

Basic PHP Class

<?php

class TrumpetsClient {
    private $apiKey;
    private $targetId;
    private $baseUrl;

    public function __construct($apiKey, $targetId, $baseUrl = 'https://api.trumpets.ai') {
        $this->apiKey = $apiKey;
        $this->targetId = $targetId;
        $this->baseUrl = $baseUrl;
    }

    public function sendMessage($message, $timeout = 30) {
        $url = $this->baseUrl . '/agent-runs/api';
        
        $data = json_encode([
            'target' => ['type' => 'agent', 'id' => $this->targetId],
            'input' => ['message' => $message],
            'options' => ['trace' => 'summary']
        ]);
        
        $context = stream_context_create([
            'http' => [
                'method' => 'POST',
                'header' => [
                    'x-api-key: ' . $this->apiKey,
                    'Content-Type: application/json',
                    'Content-Length: ' . strlen($data)
                ],
                'content' => $data,
                'timeout' => $timeout
            ]
        ]);

        $response = file_get_contents($url, false, $context);
        
        if ($response === false) {
            throw new Exception('Failed to send message to Trumpets');
        }

        $result = json_decode($response, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Exception('Invalid JSON response from Trumpets');
        }

        return $result;
    }
}

// Usage
$peter = new TrumpetsClient('tk_live_example', 'agent_123');

try {
    $result = $peter->sendMessage("What causes engine overheating?");
    echo "Agent says: " . $result['content'] . "\n";
    echo "Tokens used: " . $result['usage']['tokensUsed'] . "\n";
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}

?>

WordPress Plugin Integration

// WordPress shortcode for Trumpets integration
function trumpets_chat_shortcode($atts) {
    $atts = shortcode_atts([
        'api_key' => '',
        'placeholder' => 'Ask Trumpets anything...',
        'agent_name' => 'Trumpets'
    ], $atts);

    if (empty($atts['api_key'])) {
        return '<p>Error: API key required</p>';
    }

    ob_start();
    ?>
    <div id="peter-chat-<?php echo uniqid(); ?>" class="peter-chat-widget">
        <div class="peter-messages"></div>
        <div class="peter-input-container">
            <input type="text" 
                   placeholder="<?php echo esc_attr($atts['placeholder']); ?>" 
                   class="peter-input">
            <button class="peter-send-btn">Send</button>
        </div>
    </div>
    
    <script>
    (function() {
        const apiKey = '<?php echo esc_js($atts['api_key']); ?>';
        const agentName = '<?php echo esc_js($atts['agent_name']); ?>';
        
        // Trumpets chat functionality here...
    })();
    </script>
    <?php
    return ob_get_clean();
}

add_shortcode('trumpets_chat', 'trumpets_chat_shortcode');

Error Handling

Common HTTP Status Codes

400 Bad Request

Invalid request format or missing message

401 Unauthorized

Invalid or missing API key

410 Gone

Deprecated endpoint - migrate to agent-runs

500 Server Error

Internal server error - retry with backoff

Error Response Format

{
  "error": "Invalid API key",
  "code": "UNAUTHORIZED",
  "message": "The provided API key is invalid or has been revoked",
  "timestamp": "2025-01-15T10:30:00Z"
}

Best Practices

Optimize your agent integration for production

Security

✅ Do This

  • • Store API keys in environment variables
  • • Use HTTPS for all API requests
  • • Implement proper error handling
  • • Validate user inputs before sending
  • • Rotate API keys regularly
  • • Monitor API usage and costs

❌ Avoid This

  • • Hardcoding API keys in source code
  • • Exposing API keys in client-side code
  • • Sending sensitive data without encryption
  • • Ignoring rate limits and error responses
  • • Using the same API key across environments

Performance

Optimization Tips

  • • Implement request caching for repeated queries
  • • Use connection pooling for high-volume applications
  • • Set appropriate timeout values
  • • Implement exponential backoff for retries
  • • Monitor response times and adjust accordingly

Usage Controls

Usage points are consumed by runtime work

Timeouts should match your customer-facing SLA

Retries should be limited and idempotent

Monitoring should track errors, latency, and cost

Integration Patterns

1

Direct Integration

Call Trumpets API directly from your application for real-time responses

2

Streaming Integration

Use server-sent events for progress, output deltas, clarification, and completion

3

Workflow Runtime

Execute workflow targets with the same agent-runs API-key runtime