> ## Documentation Index
> Fetch the complete documentation index at: https://docs.fabraix.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Register Agent Run

> Initialize a new agent session and receive a trace_id

## Overview

This endpoint registers the start of a new agent interaction or "run". It creates a new session with a unique `trace_id` that will be used to correlate all subsequent events for this specific agent session.

<Info>
  Always call this endpoint at the beginning of each new agent conversation or task to establish a tracking context.
</Info>

## Request

<ParamField body="agent_id" type="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"`
</ParamField>

<ParamField body="timestamp" type="datetime" required>
  The timestamp when the agent run is starting, in ISO 8601 format.

  Format: `YYYY-MM-DDTHH:mm:ss.sssZ`

  Example: `"2024-01-15T14:30:45.123Z"`
</ParamField>

<ParamField body="system_prompt" type="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."`
</ParamField>

## Response

<ResponseField name="trace_id" type="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"`
</ResponseField>

<ResponseField name="timestamp" type="datetime" required>
  The server timestamp when the session was registered, in ISO 8601 format.

  Example: `"2024-01-15T14:30:45.456Z"`
</ResponseField>

## Examples

<CodeGroup>
  ```bash cURL theme={null}
  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."
    }'
  ```

  ```python Python theme={null}
  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}")
  ```

  ```javascript JavaScript theme={null}
  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();
  ```

  ```go Go theme={null}
  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
  }
  ```
</CodeGroup>

## Response Examples

### Success Response

```json theme={null}
{
  "trace_id": "f4f4f4f4-f4f4-f4f4-f4f4-f4f4f4f4f4f4",
  "timestamp": "2024-01-15T14:30:45.456Z"
}
```

### Error Responses

<CodeGroup>
  ```json 400 Bad Request theme={null}
  {
    "error": {
      "message": "Invalid agent_id format",
      "type": "validation_error",
      "code": "INVALID_AGENT_ID"
    }
  }
  ```

  ```json 401 Unauthorized theme={null}
  {
    "error": {
      "message": "Invalid API key provided",
      "type": "authentication_error",
      "code": "INVALID_API_KEY"
    }
  }
  ```

  ```json 429 Rate Limited theme={null}
  {
    "error": {
      "message": "Rate limit exceeded",
      "type": "rate_limit_error",
      "retry_after": 30
    }
  }
  ```
</CodeGroup>

## Best Practices

<AccordionGroup>
  <Accordion title="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

    ```python theme={null}
    # 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
    ```
  </Accordion>

  <Accordion title="Descriptive System Prompts">
    Include clear constraints and objectives in your system prompt:

    ```python theme={null}
    # 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"
    ```
  </Accordion>

  <Accordion title="Session Management">
    Store the `trace_id` properly for the entire session:

    ```python theme={null}
    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
            )
    ```
  </Accordion>

  <Accordion title="Error Handling">
    Implement proper retry logic for transient failures:

    ```python theme={null}
    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")
    ```
  </Accordion>
</AccordionGroup>

## Use Cases

### Multi-Turn Conversation

```python theme={null}
# 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

```python theme={null}
# 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

```python theme={null}
# 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](/api-reference/arx/endpoint/event) - Log events after registering a run
* [POST /check](/api-reference/arx/endpoint/check) - Validate actions using the trace\_id

## FAQ

<AccordionGroup>
  <Accordion title="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)
  </Accordion>

  <Accordion title="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.
  </Accordion>

  <Accordion title="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.
  </Accordion>

  <Accordion title="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.
  </Accordion>
</AccordionGroup>
