Everything you need to build, train, and deploy reliable AI agents. From basic setup to advanced integrations.
Learn the basics of building and deploying Trumpetss
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.
Train Trumpetss with domain-specific expertise
Get API endpoints ready in seconds
Simple REST API for any application
Pro Tip: Start with a simple Trumpets to understand the workflow, then expand with specialized training materials for your specific use case.
Configure your agent's personality and capabilities
Choose a descriptive name that reflects your agent's role and expertise.
Auto MechanicSelect the primary domain your agent will operate in.
Define your agent's specific area of expertise within the category.
Engine Diagnostics & RepairProvide 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.List the specific tasks and skills your agent can perform.
Choose the AI model that best fits your agent's needs.
Controls creativity vs consistency in responses.
Maximum length of agent's responses.
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.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 improvementsEnhance your agent's knowledge with custom content
Content is automatically chunked and converted to vector embeddings for intelligent retrieval during conversations.
agents automatically retrain when you add or remove training materials, updating their knowledge base in real-time.
Connect your GitHub repositories to give agents deep understanding of your codebase.
https://github.com/username/repositoryghp_xxxxxxxxxxxxxxxxxxxxmainControl which files are processed from your repository.
Integrate agents into your applications
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"}'/chat/api/messageSend a message to your Trumpets agent and receive an AI-generated response.
{
"message": "My car won't start, what could be wrong?"
}{
"response": "Let me help diagnose this...",
"agent": {
"name": "Trumpets the Mechanic",
"specialty": "Engine Diagnostics"
},
"usageStats": {
"tokensUsed": 245,
"chunksUsed": 3,
"responseTimeMs": 1250,
"ragEnabled": true
}
}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.
Ready-to-use integration examples
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));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));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}")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())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 };
};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 -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?"
}'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
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 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');Invalid request format or missing message
Invalid or missing API key
Rate limit exceeded - implement backoff
Internal server error - retry with backoff
{
"error": "Invalid API key",
"code": "UNAUTHORIZED",
"message": "The provided API key is invalid or has been revoked",
"timestamp": "2025-01-15T10:30:00Z"
}Optimize your agent integration for production
• 60 requests/minute per API key
• 429 status code when limit exceeded
• Retry-After header indicates wait time
• Exponential backoff recommended for retries
Call Trumpets API directly from your application for real-time responses
Process agent responses asynchronously through webhook endpoints
Queue multiple requests for efficient bulk processing