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

# Chat Completions

> OpenAI-compatible endpoint for custom chat agents

## Overview

The Chat Completions endpoint allows UserTrace to interact with your custom chat agents using the OpenAI Chat Completions format. This is the primary endpoint for text-based agent testing.

## Endpoint

```
POST /v1/chat/completions
```

## Request Headers

```http theme={null}
Content-Type: application/json
Authorization: Bearer your-api-key
```

## Request Body

<ParamField body="messages" type="array" required>
  Array of message objects representing the conversation history

  <Expandable title="Message Object">
    <ParamField body="role" type="string" required>
      The role of the message sender. One of: `system`, `user`, `assistant`
    </ParamField>

    <ParamField body="content" type="string" required>
      The content of the message
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="user_id" type="string">
  Unique identifier for the simulated user. Optional if your agent doesn't require user management.
</ParamField>

<ParamField body="session_id" type="string">
  Session identifier for conversation tracking. Optional if your agent doesn't require session management.
</ParamField>

<ParamField body="metadata" type="object">
  Additional context about the simulation scenario

  <Expandable title="Metadata Fields">
    <ParamField body="scenario_id" type="string">
      Identifier for the test scenario
    </ParamField>

    <ParamField body="persona" type="string">
      User persona for the simulation
    </ParamField>

    <ParamField body="time_of_day" type="string">
      Context about timing (e.g., "morning\_rush", "evening")
    </ParamField>
  </Expandable>
</ParamField>

## Request Examples

### Minimal Request

```json theme={null}
{
  "messages": [
    {
      "role": "user",
      "content": "Hello, I need help"
    }
  ]
}
```

### Full Request with Context

```json theme={null}
{
  "messages": [
    {
      "role": "system",
      "content": "You are a helpful customer service agent."
    },
    {
      "role": "user", 
      "content": "I need help with my order #12345"
    }
  ],
  "user_id": "sim_user_abc123",
  "session_id": "session_xyz789",
  "metadata": {
    "scenario_id": "financial_stress_delivery",
    "persona": "delivery_worker_bengaluru",
    "time_of_day": "morning_rush",
    "stress_level": "high"
  }
}
```

## Response Format

<ParamField body="choices" type="array" required>
  Array containing the agent's response

  <Expandable title="Choice Object">
    <ParamField body="index" type="integer">
      Index of the choice (typically 0)
    </ParamField>

    <ParamField body="message" type="object" required>
      The agent's response message

      <Expandable title="Message Object">
        <ParamField body="role" type="string">
          Always "assistant" for agent responses
        </ParamField>

        <ParamField body="content" type="string">
          The agent's response content
        </ParamField>

        <ParamField body="tool_calls" type="array">
          Array of tool calls made by the agent (if applicable)
        </ParamField>
      </Expandable>
    </ParamField>

    <ParamField body="finish_reason" type="string">
      Reason the response ended. Typically "stop"
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="session_id" type="string">
  Session identifier echoed from request
</ParamField>

<ParamField body="chat_id" type="string">
  Unique identifier for this conversation
</ParamField>

<ParamField body="metadata" type="object">
  Agent performance metrics

  <Expandable title="Metadata Fields">
    <ParamField body="agent_confidence" type="number">
      Confidence score for the response (0-1)
    </ParamField>

    <ParamField body="response_time_ms" type="integer">
      Time taken to generate response in milliseconds
    </ParamField>

    <ParamField body="tools_used" type="array">
      List of tools/functions used in the response
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="evaluation_metadata" type="object">
  Additional data for evaluation purposes

  <Expandable title="Evaluation Fields">
    <ParamField body="order_found" type="boolean">
      Whether relevant data was found (context-specific)
    </ParamField>

    <ParamField body="tone" type="string">
      Detected tone of the response
    </ParamField>

    <ParamField body="resolution_step" type="integer">
      Step in the resolution process
    </ParamField>

    <ParamField body="customer_acknowledged" type="boolean">
      Whether customer concern was acknowledged
    </ParamField>
  </Expandable>
</ParamField>

## Response Examples

### Basic Response

```json theme={null}
{
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "I'd be happy to help you with your order. Let me look up order #12345 for you."
      },
      "finish_reason": "stop"
    }
  ],
  "session_id": "session_xyz789",
  "chat_id": "chat_456def",
  "metadata": {
    "agent_confidence": 0.95,
    "response_time_ms": 1200,
    "tools_used": ["order_lookup"]
  },
  "evaluation_metadata": {
    "order_found": true,
    "tone": "empathetic",
    "resolution_step": 1,
    "customer_acknowledged": true
  }
}
```

### Response with Tool Calls

```json theme={null}
{
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "I found your order! Order #12345 is currently being prepared and will be shipped within 2 hours.",
        "tool_calls": [
          {
            "id": "call_abc123",
            "type": "function",
            "function": {
              "name": "get_order_status",
              "arguments": "{\"order_id\": \"12345\"}",
              "result": {
                "order_id": "12345",
                "status": "preparing",
                "estimated_ship_time": "2 hours",
                "tracking_number": null
              }
            }
          }
        ]
      },
      "finish_reason": "stop"
    }
  ],
  "session_id": "session_xyz789",
  "chat_id": "chat_456def",
  "evaluation_metadata": {
    "tool_called": "get_order_status",
    "tool_success": true,
    "response_included_status": true,
    "customer_informed": true
  }
}
```

## Error Responses

### 400 Bad Request

```json theme={null}
{
  "error": {
    "message": "Invalid request format: missing required field 'messages'",
    "type": "invalid_request_error",
    "code": "bad_request"
  }
}
```

### 429 Rate Limit

```json theme={null}
{
  "error": {
    "message": "Rate limit exceeded. Please wait before making another request.",
    "type": "rate_limit_error",
    "code": "rate_limit_exceeded"
  }
}
```

### 500 Internal Error

```json theme={null}
{
  "error": {
    "message": "Internal server error. Please try again later.",
    "type": "internal_error", 
    "code": "server_error"
  }
}
```

## Implementation Notes

### Tool Calling

If your agent uses function calling, you must handle all tool execution internally. The simulated user will send simple text requests, and your agent should:

1. Execute any necessary function calls
2. Include complete tool call information in the response
3. Provide the final answer incorporating tool results

### Performance Requirements

* **Response Time**: Target \< 5 seconds for standard requests
* **Throughput**: Support 100 RPS for parallel simulations
* **Availability**: 99.9% uptime during testing windows

### Best Practices

* Include relevant `evaluation_metadata` to help with scoring
* Use consistent `session_id` for multi-turn conversations
* Handle edge cases gracefully with appropriate error responses
* Log requests and responses for debugging

<Note>
  **Testing**: Use tools like curl, Postman, or our SDK to test your endpoint before connecting to UserTrace.
</Note>
