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 Trumpetss

What is a Trumpets?

A Trumpets is a specialized AI agent that you can train with custom knowledge and deploy instantly. Just like every Trumpets you know - they're reliable, consistent, and always deliver quality work.

Specialized Knowledge

Train Trumpetss with domain-specific expertise

Instant Deployment

Get API endpoints ready in seconds

Easy Integration

Simple REST API for any application

Quick Start

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

Pro Tip: Start with a simple Trumpets 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

GitHub Repos

Full repositories
Specific branches
File pattern filtering
Auto-sync updates

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.

Auto-Retraining

agents automatically retrain when you add or remove training materials, updating their knowledge base in real-time.

GitHub Integration

Repository Connection

Connect your GitHub repositories to give agents deep understanding of your codebase.

Repository URL
https://github.com/username/repository
Access Token
ghp_xxxxxxxxxxxxxxxxxxxx
Branch
main

File Filtering

Control which files are processed from your repository.

Include Patterns
*.js*.ts*.py*.md
Ignore Patterns
node_modules/**dist/**.git/**

API Reference

Integrate agents into your applications

Authentication

API Key Authentication

Each Trumpets agent has a unique API key for secure access. Include it in thex-api-key header.

curl -X POST "https://api.peter.ai/chat/api/message" \
  -H "x-api-key: ak_peter_mechanic_x7k9m2n4" \
  -H "Content-Type: application/json" \
  -d '{"message": "My car won't start"}'

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/chat/api/message

Send a message to your Trumpets agent and receive an AI-generated response.

Request Body
{
  "message": "My car won't start, what could be wrong?"
}
Response
{
  "response": "Let me help diagnose this...",
  "agent": {
    "name": "Trumpets the Mechanic",
    "specialty": "Engine Diagnostics"
  },
  "usageStats": {
    "tokensUsed": 245,
    "chunksUsed": 3,
    "responseTimeMs": 1250,
    "ragEnabled": true
  }
}

Rate Limits & Usage

Free Plan

1,000
messages/month

Growth

10,000
messages/month

Scale

50,000
messages/month

Rate Limiting: API requests are limited to 60 requests per minute per API key. If you exceed this limit, you'll receive a 429 status code. Implement exponential backoff for robust error handling.

Code Examples

Ready-to-use integration examples

JavaScript / Node.js

Basic Usage

const apiKey = 'ak_trumpets_mechanic_x7k9m2n4';
const apiUrl = 'https://api.peter.ai/chat/api/message';

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

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

    const data = await response.json();
    return data.response;
  } 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('Trumpets says:', response))
  .catch(error => console.error('Error:', error));

Advanced with Error Handling

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

  async sendMessage(message, options = {}) {
    const { timeout = 30000, retries = 3 } = 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}/chat/api/message`, {
          method: 'POST',
          headers: {
            'x-api-key': this.apiKey,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ message }),
          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 {
          response: data.response,
          agent: data.agent,
          usageStats: data.usageStats,
        };
      } 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('ak_trumpets_mechanic_x7k9m2n4');

peter.sendMessage("How do I change my oil?")
  .then(result => {
    console.log('Response:', result.response);
    console.log('Tokens used:', result.usageStats.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, base_url: str = "https://api.peter.ai"):
        self.api_key = api_key
        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}/chat/api/message"
        payload = {"message": message}
        
        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('ak_trumpets_mechanic_x7k9m2n4')

try:
    result = peter.send_message("My engine is making a knocking sound")
    print(f"Trumpets says: {result['response']}")
    print(f"Tokens used: {result['usageStats']['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, base_url: str = "https://api.peter.ai"):
        self.api_key = api_key
        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}/chat/api/message"
        payload = {"message": message}
        
        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('ak_trumpets_mechanic_x7k9m2n4')
    
    try:
        result = await peter.send_message("How often should I change my oil?")
        print(f"Trumpets says: {result['response']}")
    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) => {
  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.peter.ai/chat/api/message', {
        method: 'POST',
        headers: {
          'x-api-key': apiKey,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ message }),
      });

      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]);

  return { sendMessage, isLoading, error };
};

Chat Component

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

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

  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.response,
        usageStats: result.usageStats 
      };
      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} | 
                Time: {message.usageStats.responseTimeMs}ms
              </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.peter.ai/chat/api/message" \
  -H "x-api-key: ak_trumpets_mechanic_x7k9m2n4" \
  -H "Content-Type: application/json" \
  -d '{
    "message": "My car won'''t start, what could be wrong?"
  }'

With Verbose Output

curl -X POST "https://api.peter.ai/chat/api/message" \
  -H "x-api-key: ak_trumpets_mechanic_x7k9m2n4" \
  -H "Content-Type: application/json" \
  -d '{
    "message": "How do I check my brake pads?"
  }' \
  --verbose \
  --max-time 30

PHP

Basic PHP Class

<?php

class TrumpetsClient {
    private $apiKey;
    private $baseUrl;

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

    public function sendMessage($message, $timeout = 30) {
        $url = $this->baseUrl . '/chat/api/message';
        
        $data = json_encode(['message' => $message]);
        
        $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('ak_trumpets_mechanic_x7k9m2n4');

try {
    $result = $peter->sendMessage("What causes engine overheating?");
    echo "Trumpets says: " . $result['response'] . "\n";
    echo "Tokens used: " . $result['usageStats']['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

429 Too Many Requests

Rate limit exceeded - implement backoff

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

Rate Limiting

60 requests/minute per API key

429 status code when limit exceeded

Retry-After header indicates wait time

Exponential backoff recommended for retries

Integration Patterns

1

Direct Integration

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

2

Webhook Integration

Process agent responses asynchronously through webhook endpoints

3

Batch Processing

Queue multiple requests for efficient bulk processing