Register Agent Run
curl --request POST \
--url https://api.example.com/register-agent-run \
--header 'Content-Type: application/json' \
--data '
{
"agent_id": "<string>",
"timestamp": {},
"system_prompt": "<string>"
}
'import requests
url = "https://api.example.com/register-agent-run"
payload = {
"agent_id": "<string>",
"timestamp": {},
"system_prompt": "<string>"
}
headers = {"Content-Type": "application/json"}
response = requests.post(url, json=payload, headers=headers)
print(response.text)const options = {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({agent_id: '<string>', timestamp: {}, system_prompt: '<string>'})
};
fetch('https://api.example.com/register-agent-run', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.example.com/register-agent-run",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode([
'agent_id' => '<string>',
'timestamp' => [
],
'system_prompt' => '<string>'
]),
CURLOPT_HTTPHEADER => [
"Content-Type: application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"strings"
"net/http"
"io"
)
func main() {
url := "https://api.example.com/register-agent-run"
payload := strings.NewReader("{\n \"agent_id\": \"<string>\",\n \"timestamp\": {},\n \"system_prompt\": \"<string>\"\n}")
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.post("https://api.example.com/register-agent-run")
.header("Content-Type", "application/json")
.body("{\n \"agent_id\": \"<string>\",\n \"timestamp\": {},\n \"system_prompt\": \"<string>\"\n}")
.asString();require 'uri'
require 'net/http'
url = URI("https://api.example.com/register-agent-run")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
request["Content-Type"] = 'application/json'
request.body = "{\n \"agent_id\": \"<string>\",\n \"timestamp\": {},\n \"system_prompt\": \"<string>\"\n}"
response = http.request(request)
puts response.read_body{
"trace_id": "<string>",
"timestamp": {}
}Arx Endpoints
Register Agent Run
Initialize a new agent session and receive a trace_id
POST
/
register-agent-run
Register Agent Run
curl --request POST \
--url https://api.example.com/register-agent-run \
--header 'Content-Type: application/json' \
--data '
{
"agent_id": "<string>",
"timestamp": {},
"system_prompt": "<string>"
}
'import requests
url = "https://api.example.com/register-agent-run"
payload = {
"agent_id": "<string>",
"timestamp": {},
"system_prompt": "<string>"
}
headers = {"Content-Type": "application/json"}
response = requests.post(url, json=payload, headers=headers)
print(response.text)const options = {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({agent_id: '<string>', timestamp: {}, system_prompt: '<string>'})
};
fetch('https://api.example.com/register-agent-run', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.example.com/register-agent-run",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode([
'agent_id' => '<string>',
'timestamp' => [
],
'system_prompt' => '<string>'
]),
CURLOPT_HTTPHEADER => [
"Content-Type: application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"strings"
"net/http"
"io"
)
func main() {
url := "https://api.example.com/register-agent-run"
payload := strings.NewReader("{\n \"agent_id\": \"<string>\",\n \"timestamp\": {},\n \"system_prompt\": \"<string>\"\n}")
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.post("https://api.example.com/register-agent-run")
.header("Content-Type", "application/json")
.body("{\n \"agent_id\": \"<string>\",\n \"timestamp\": {},\n \"system_prompt\": \"<string>\"\n}")
.asString();require 'uri'
require 'net/http'
url = URI("https://api.example.com/register-agent-run")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
request["Content-Type"] = 'application/json'
request.body = "{\n \"agent_id\": \"<string>\",\n \"timestamp\": {},\n \"system_prompt\": \"<string>\"\n}"
response = http.request(request)
puts response.read_body{
"trace_id": "<string>",
"timestamp": {}
}Overview
This endpoint registers the start of a new agent interaction or “run”. It creates a new session with a uniquetrace_id that will be used to correlate all subsequent events for this specific agent session.
Always call this endpoint at the beginning of each new agent conversation or task to establish a tracking context.
Request
UUID
required
The unique identifier for your agent. This should be consistent across all runs of the same agent.Example:
"a1b2c3d4-e5f6-7890-1234-567890abcdef"datetime
required
The timestamp when the agent run is starting, in ISO 8601 format.Format:
YYYY-MM-DDTHH:mm:ss.sssZExample: "2024-01-15T14:30:45.123Z"string
required
The system prompt or initial instructions given to the agent for this session. This helps establish the agent’s intended behavior for security analysis.Example:
"You are a helpful customer service assistant. You should be polite and professional. Never share customer personal information."Response
UUID
required
The unique identifier for this agent session. Use this ID for all subsequent event logging and action checking within this session.Example:
"f4f4f4f4-f4f4-f4f4-f4f4-f4f4f4f4f4f4"datetime
required
The server timestamp when the session was registered, in ISO 8601 format.Example:
"2024-01-15T14:30:45.456Z"Examples
curl -X POST https://api.fabraix.com/v1/register-agent-run \
-H "x-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"agent_id": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
"timestamp": "2024-01-15T14:30:45.123Z",
"system_prompt": "You are a helpful customer service assistant. You should be polite and professional."
}'
import requests
import uuid
from datetime import datetime
# Configuration
API_KEY = "YOUR_API_KEY"
BASE_URL = "https://api.fabraix.com/v1"
# Create request
agent_id = uuid.uuid4()
request_data = {
"agent_id": str(agent_id),
"timestamp": datetime.now().isoformat(),
"system_prompt": "You are a helpful customer service assistant."
}
# Make API call
response = requests.post(
f"{BASE_URL}/register-agent-run",
headers={
"x-api-key": API_KEY,
"Content-Type": "application/json"
},
json=request_data
)
# Extract trace_id
result = response.json()
trace_id = result["trace_id"]
print(f"Session started with trace_id: {trace_id}")
const axios = require('axios');
const { v4: uuidv4 } = require('uuid');
// Configuration
const API_KEY = 'YOUR_API_KEY';
const BASE_URL = 'https://api.fabraix.com/v1';
// Create request
const agentId = uuidv4();
const requestData = {
agent_id: agentId,
timestamp: new Date().toISOString(),
system_prompt: 'You are a helpful customer service assistant.'
};
// Make API call
async function registerAgentRun() {
try {
const response = await axios.post(
`${BASE_URL}/register-agent-run`,
requestData,
{
headers: {
'x-api-key': API_KEY,
'Content-Type': 'application/json'
}
}
);
const traceId = response.data.trace_id;
console.log(`Session started with trace_id: ${traceId}`);
return traceId;
} catch (error) {
console.error('Error registering agent run:', error);
throw error;
}
}
registerAgentRun();
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/google/uuid"
)
type RegisterRequest struct {
AgentID string `json:"agent_id"`
Timestamp time.Time `json:"timestamp"`
SystemPrompt string `json:"system_prompt"`
}
type RegisterResponse struct {
TraceID string `json:"trace_id"`
Timestamp time.Time `json:"timestamp"`
}
func registerAgentRun(apiKey string) (string, error) {
url := "https://api.fabraix.com/v1/register-agent-run"
// Create request
agentID := uuid.New().String()
reqData := RegisterRequest{
AgentID: agentID,
Timestamp: time.Now(),
SystemPrompt: "You are a helpful customer service assistant.",
}
jsonData, err := json.Marshal(reqData)
if err != nil {
return "", err
}
// Make HTTP request
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
return "", err
}
req.Header.Set("x-api-key", apiKey)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
// Parse response
var result RegisterResponse
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return "", err
}
fmt.Printf("Session started with trace_id: %s\n", result.TraceID)
return result.TraceID, nil
}
Response Examples
Success Response
{
"trace_id": "f4f4f4f4-f4f4-f4f4-f4f4-f4f4f4f4f4f4",
"timestamp": "2024-01-15T14:30:45.456Z"
}
Error Responses
{
"error": {
"message": "Invalid agent_id format",
"type": "validation_error",
"code": "INVALID_AGENT_ID"
}
}
{
"error": {
"message": "Invalid API key provided",
"type": "authentication_error",
"code": "INVALID_API_KEY"
}
}
{
"error": {
"message": "Rate limit exceeded",
"type": "rate_limit_error",
"retry_after": 30
}
}
Best Practices
Consistent Agent IDs
Consistent Agent IDs
Use the same
agent_id for all runs of the same agent type. This helps with:- Analytics and monitoring
- Identifying patterns across sessions
- Debugging and troubleshooting
# Good: Consistent agent ID
CUSTOMER_SERVICE_AGENT_ID = "cs-agent-prod-v1"
# Bad: Random ID each time
agent_id = str(uuid.uuid4()) # Different every run
Descriptive System Prompts
Descriptive System Prompts
Include clear constraints and objectives in your system prompt:
# Good: Clear boundaries
system_prompt = """
You are a customer service assistant for AcmeCorp.
- Help customers with product inquiries and orders
- Never share customer personal information
- Do not process refunds over $500 without manager approval
- Always be professional and courteous
"""
# Bad: Vague prompt
system_prompt = "You are helpful"
Session Management
Session Management
Store the
trace_id properly for the entire session:class AgentSession:
def __init__(self, agent_id, system_prompt):
self.agent_id = agent_id
self.trace_id = self.register_run(system_prompt)
self.event_count = 0
def register_run(self, system_prompt):
response = fabraix.register_agent_run(
agent_id=self.agent_id,
timestamp=datetime.now(),
system_prompt=system_prompt
)
return response["trace_id"]
def log_event(self, event_type, content, schema):
# Use stored trace_id for all events
return fabraix.log_event(
trace_id=self.trace_id,
event_type=event_type,
content=content,
schema=schema
)
Error Handling
Error Handling
Implement proper retry logic for transient failures:
import time
import random
def register_with_retry(agent_id, system_prompt, max_retries=3):
for attempt in range(max_retries):
try:
return register_agent_run(agent_id, system_prompt)
except HTTPError as e:
if e.response.status_code == 429:
# Rate limited - use exponential backoff
wait_time = (2 ** attempt) + random.uniform(0, 1)
time.sleep(wait_time)
elif e.response.status_code >= 500:
# Server error - retry
if attempt < max_retries - 1:
time.sleep(1)
continue
raise
raise Exception("Max retries exceeded")
Use Cases
Multi-Turn Conversation
# Start a conversation
trace_id = register_agent_run(
agent_id="chat-agent-v1",
timestamp=datetime.now(),
system_prompt="You are a helpful assistant"
)
# Use same trace_id for entire conversation
for message in conversation:
log_event(trace_id, "user", message)
response = process_message(message)
log_event(trace_id, "model_output", response)
Task-Based Agent
# Start a task
trace_id = register_agent_run(
agent_id="task-agent-v1",
timestamp=datetime.now(),
system_prompt="Process customer orders"
)
# Use trace_id throughout task execution
for order in orders_to_process:
log_event(trace_id, "environment", order)
result = process_order(order)
log_event(trace_id, "tool", result)
Autonomous Agent
# Start autonomous operation
trace_id = register_agent_run(
agent_id="auto-agent-v1",
timestamp=datetime.now(),
system_prompt="Monitor system health and respond to issues"
)
# Long-running agent with same trace_id
while running:
event = wait_for_event()
log_event(trace_id, "environment", event)
if requires_action(event):
action = determine_action(event)
if check_action(trace_id, action):
execute_action(action)
Related Endpoints
- POST /event - Log events after registering a run
- POST /check - Validate actions using the trace_id
FAQ
When should I create a new trace_id?
When should I create a new trace_id?
Create a new trace_id for:
- Each new conversation with a user
- Each distinct task or job
- When the agent’s context is reset
- After a significant time gap (e.g., new day)
Can I reuse a trace_id?
Can I reuse a trace_id?
No, trace_ids should be unique for each session. Reusing them will mix events from different sessions and compromise security analysis.
What happens if I don't register a run?
What happens if I don't register a run?
Events and checks submitted without a valid trace_id will be rejected with a 404 error. Always register a run first.
How long are trace_ids valid?
How long are trace_ids valid?
Trace_ids remain valid indefinitely for historical analysis, but should not be reused for new sessions after the original session ends.
Was this page helpful?