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

# Update Agent

> Updates one or more fields on an agent. Only send the fields you want to change. Architecture cannot be changed after creation.

## Overview

Updates an existing agent's configuration. Send only the fields you want to modify — all other fields remain unchanged.

**Authentication:** Session-based (Better Auth)
**Scope:** Active organization from session

## Request

**Path Parameters:**

| Parameter | Type   | Required | Description            |
| --------- | ------ | -------- | ---------------------- |
| `agentId` | string | ✅        | Agent ID (ULID format) |

**Headers:**

```
Authorization: Bearer YOUR_SESSION_TOKEN
Content-Type: application/json
```

**Request Body:**

```json theme={null}
{
  "name": "Updated Agent Name",
  "description": "Updated description",
  "sysMsg": "Updated system prompt...",
  "languages": ["english", "urdu"],
  "agentArchitecture": "pipeline",
  "model": "gpt_4o_mini",
  "stt": "deepgram",
  "voiceId": "cartesia-voice-456",
  "realtimeProvider": "gemini",
  "greetingType": "agentFirst",
  "greetingMessage": "Hello! How can I assist you?",
  "lastMessage": "Goodbye!",
  "temperature": 0.7,
  "inactivityTimeout": 30,
  "mode": "public"
}
```

**Optional Fields:**

| Field               | Type   | Validation                        | Description                       |
| ------------------- | ------ | --------------------------------- | --------------------------------- |
| `name`              | string | 2-50 chars                        | Agent display name                |
| `description`       | string | Max 200 chars                     | Internal description              |
| `sysMsg`            | string | Max 5000 chars                    | System prompt                     |
| `languages`         | array  | 1+ items                          | Language codes (en, ur, sd)       |
| `agentArchitecture` | string | Fixed after create                | `pipeline`, `realtime`, or `text` |
| `model`             | string | Required for pipeline/text        | LLM model                         |
| `stt`               | string | Required for pipeline             | STT provider                      |
| `voiceId`           | string | Required for pipeline             | Voice ID                          |
| `realtimeProvider`  | string | Required for realtime             | `openai` or `gemini`              |
| `greetingType`      | string | `agentFirst` or `userFirst`       | Who speaks first                  |
| `greetingMessage`   | string | Optional                          | Greeting text                     |
| `lastMessage`       | string | Max 100 chars                     | Farewell message                  |
| `temperature`       | number | 0.1–1.0                           | Response randomness               |
| `inactivityTimeout` | number | 10–60 seconds                     | Silence timeout                   |
| `mode`              | string | `public`, `private`, `commercial` | Visibility mode                   |

## Response

**Status:** `200 OK`

```json theme={null}
{
  "success": true,
  "agent": {
    "id": "agent_abc123",
    "name": "Updated Agent Name",
    "description": "Updated description",
    "agentArchitecture": "pipeline",
    "mode": "public",
    "model": "gpt_4o_mini",
    "stt": "deepgram",
    "voiceId": "cartesia-voice-456",
    "sysMsg": "Updated system prompt...",
    "functionCallingEnabled": true,
    "enabledFunctions": ["web_search", "end_call"],
    "enabledCustomFunctions": [],
    "greetingType": "agentFirst",
    "greetingMessage": "Hello! How can I assist you?",
    "lastMessage": "Goodbye!",
    "temperature": 0.7,
    "inactivityTimeout": 30,
    "createdAt": "2024-01-10T09:00:00Z",
    "updatedAt": "2024-01-15T14:30:00Z",
    "userId": "user_xyz789",
    "organizationId": "org_123",
    "languages": [
      {
        "id": "lang_123",
        "language": "english"
      },
      {
        "id": "lang_124",
        "language": "urdu"
      }
    ],
    "VoiceOption": {
      "voiceId": "cartesia-voice-456",
      "voiceName": "Sonic British",
      "provider": "cartesia"
    }
  }
}
```

**Special Response (Missing API Keys):**

```json theme={null}
{
  "success": true,
  "agent": { /* ... agent object ... */ },
  "missingKeys": ["openaiKey"],
  "usedDefaults": true,
  "finalModel": "gemini-2.0-flash",
  "finalStt": "gemini",
  "redirectUrl": "/organization?callbackUrl=/agents/create-agent/agent_abc123"
}
```

## Access Control

| User Role                | Can Update                       |
| ------------------------ | -------------------------------- |
| **Owner**                | ✅ Any agent in organization      |
| **Admin**                | ✅ Any agent in organization      |
| **Member (Creator)**     | ✅ Own agents (except commercial) |
| **Member (Not Creator)** | ❌ Cannot update                  |

**Commercial Agent Restriction:**

* Only Owners/Admins can update commercial agents
* Creators cannot modify their own commercial agents

## Validation Rules

### Architecture-Specific Validation

**Pipeline:**

```json theme={null}
{
  "agentArchitecture": "pipeline",
  "voiceId": "required",
  "model": "required",
  "stt": "required"
}
```

**Realtime:**

```json theme={null}
{
  "agentArchitecture": "realtime",
  "realtimeProvider": "required (openai or gemini)",
  "voiceId": "required if greetingType=agentFirst"
}
```

**Text:**

```json theme={null}
{
  "agentArchitecture": "text",
  "model": "required",
  "voiceId": "not applicable",
  "stt": "not applicable"
}
```

### Field Validation

| Field               | Rule                      | Error Message                                          |
| ------------------- | ------------------------- | ------------------------------------------------------ |
| `inactivityTimeout` | 10–60 seconds             | "Inactivity timeout must be between 10 and 60 seconds" |
| `mode`              | public/private/commercial | "Invalid agent mode"                                   |
| `languages`         | en/ur/sd only             | "Invalid language: {lang}"                             |
| `name`              | Required                  | "Name is required"                                     |
| `description`       | Required                  | "Description is required"                              |
| `sysMsg`            | Required                  | "System message is required"                           |

### Mode Change Validation

**Changing to Commercial:**

```json theme={null}
{
  "mode": "commercial"
}
```

* ✅ Allowed for Owners/Admins
* ❌ Forbidden for Members
* Error: "Only organization owners and admins can set agent as commercial"

## Error Responses

### 401 Unauthorized

```json theme={null}
{
  "error": "Unauthorized"
}
```

### 403 Forbidden

```json theme={null}
{
  "error": "You don't have permission to update this agent"
}
```

### 400 Bad Request

```json theme={null}
{
  "error": "Inactivity timeout must be between 10 and 60 seconds"
}
```

```json theme={null}
{
  "error": "For pipeline architecture, voiceId, model, and STT are required"
}
```

```json theme={null}
{
  "error": "Invalid agent mode. Must be 'public', 'private', or 'commercial'"
}
```

### 404 Not Found

```json theme={null}
{
  "error": "Agent not found"
}
```

### 500 Server Error

```json theme={null}
{
  "error": "Update failed"
}
```

## Examples

### cURL

```bash theme={null}
curl -X PUT "https://studio.talkifai.dev/api/agents/agent_abc123" \
  -H "Authorization: Bearer YOUR_SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Updated Support Bot",
    "temperature": 0.5,
    "mode": "public"
  }'
```

### JavaScript (Fetch)

```javascript theme={null}
const agentId = "agent_abc123";
const updateData = {
  name: "Updated Support Bot",
  temperature: 0.5,
  mode: "public"
};

const response = await fetch(`/api/agents/${agentId}`, {
  method: 'PUT',
  headers: {
    'Authorization': `Bearer ${sessionToken}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(updateData)
});

const data = await response.json();
if (data.redirectUrl) {
  // Missing API keys - redirect to configure
  window.location.href = data.redirectUrl;
}
```

### Next.js (Client Component)

```tsx theme={null}
async function updateAgent(agentId: string, updates: Partial<Agent>) {
  const response = await fetch(`/api/agents/${agentId}`, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(updates)
  });

  const data = await response.json();
  
  if (!response.ok) {
    throw new Error(data.error || "Update failed");
  }
  
  // Handle missing keys redirect
  if (data.redirectUrl) {
    router.push(data.redirectUrl);
    return;
  }
  
  // Success - agent updated
  toast.success("Agent updated successfully!");
  return data.agent;
}

// Usage
await updateAgent("agent_abc123", {
  name: "New Name",
  temperature: 0.5
});
```

### Update Languages

```javascript theme={null}
const response = await fetch(`/api/agents/${agentId}`, {
  method: 'PUT',
  headers: {
    'Authorization': `Bearer ${sessionToken}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    languages: ["english", "urdu", "sindhi"]
  })
});
```

### Change to Commercial Mode

```javascript theme={null}
// Only works for Owners/Admins
const response = await fetch(`/api/agents/${agentId}`, {
  method: 'PUT',
  headers: {
    'Authorization': `Bearer ${sessionToken}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    mode: "commercial"
  })
});

if (response.status === 403) {
  console.error("Only owners/admins can create commercial agents");
}
```

## Use Cases

### Partial Update (Recommended)

```javascript theme={null}
// Only send fields you want to change
await updateAgent(agentId, {
  temperature: 0.5  // Only change temperature
});
```

### Full Configuration Update

```javascript theme={null}
await updateAgent(agentId, {
  name: "New Name",
  description: "New description",
  sysMsg: "New system prompt...",
  languages: ["english"],
  model: "gpt_4o_mini",
  stt": "deepgram",
  voiceId: "cartesia-voice-123",
  greetingType: "agentFirst",
  greetingMessage: "Hello!",
  temperature: 0.7,
  inactivityTimeout: 30,
  mode: "public"
});
```

### Architecture-Specific Update

```javascript theme={null}
// Pipeline agent update
await updateAgent(agentId, {
  agentArchitecture: "pipeline",
  voiceId: "cartesia-voice-456",
  model: "gpt_4o_mini",
  stt: "deepgram"
});

// Realtime agent update
await updateAgent(agentId, {
  agentArchitecture: "realtime",
  realtimeProvider: "gemini",
  voiceId: "gemini-leda-en"
});

// Text agent update
await updateAgent(agentId, {
  agentArchitecture: "text",
  model: "gpt_4o_mini"
});
```

## Related Endpoints

* [List Agents](/api-reference/endpoint/list-agents) — List all agents
* [Get Agent](/api-reference/endpoint/get-agent) — Get agent details
* [Create Agent](/api-reference/endpoint/create-agent) — Create new agent
* [Delete Agent](/api-reference/endpoint/delete-agent) — Delete agent


## OpenAPI

````yaml PUT /v1/agents/{agentId}
openapi: 3.1.0
info:
  title: TalkifAI API
  version: 1.0.0
  description: Build and manage AI voice and chat agents programmatically.
servers:
  - url: https://api.talkifai.dev
    description: Production
security:
  - bearerAuth: []
tags:
  - name: Agents
    description: Create and manage voice and chat agents
  - name: Voice Calls
    description: Initiate outbound calls and retrieve call data
  - name: Text Chat
    description: Text chat sessions via REST + SSE
  - name: Batch Calling
    description: Run large-scale outbound call campaigns
paths:
  /v1/agents/{agentId}:
    put:
      tags:
        - Agents
      summary: Update Agent
      description: >-
        Updates one or more fields on an existing agent. Only send fields you
        want to change. Architecture cannot be changed after creation.
      operationId: updateAgent
      parameters:
        - name: agentId
          in: path
          required: true
          schema:
            type: string
          example: 01JK5XYZ...
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                name:
                  type: string
                description:
                  type: string
                sysMsg:
                  type: string
                model:
                  type: string
                stt:
                  type: string
                voiceId:
                  type: string
                realtimeProvider:
                  type: string
                  enum:
                    - openai
                    - gemini
                greetingType:
                  type: string
                  enum:
                    - agentFirst
                    - userFirst
                greetingMessage:
                  type: string
                lastMessage:
                  type: string
                temperature:
                  type: number
                inactivityTimeout:
                  type: integer
                  minimum: 10
                  maximum: 60
                mode:
                  type: string
                  enum:
                    - public
                    - private
                    - commercial
                languages:
                  type: array
                  items:
                    type: string
                functionCallingEnabled:
                  type: boolean
                enabledFunctions:
                  type: array
                  items:
                    type: string
                enabledCustomFunctions:
                  type: array
                  items:
                    type: string
      responses:
        '200':
          description: Agent updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      agent:
                        $ref: '#/components/schemas/Agent'
        '400':
          description: Validation error
        '401':
          description: Invalid or missing API key
        '404':
          description: Agent not found
      security:
        - apiKeyHeader: []
components:
  schemas:
    Agent:
      type: object
      properties:
        id:
          type: string
          example: 5b710eca-ee67-4c3a-aeb6-8b541f451b40
        name:
          type: string
          example: Customer Support Bot
        description:
          type: string
          nullable: true
          example: Handles tier-1 support queries
        agentArchitecture:
          type: string
          enum:
            - pipeline
            - realtime
            - text
          example: pipeline
        model:
          type: string
          nullable: true
          example: gpt_4o_mini
          description: >-
            LLM model. Set for pipeline and text architectures; null for
            realtime.
        stt:
          type: string
          nullable: true
          example: deepgram
          description: >-
            Speech-to-text provider. Set for pipeline; null for realtime and
            text.
        voiceId:
          type: string
          nullable: true
          example: gemini-leda-en
          description: >-
            TTS voice ID. Required for pipeline; optional for realtime (used
            only when greetingType is agentFirst).
        realtimeProvider:
          type: string
          nullable: true
          example: openai
          description: >-
            Realtime provider. Set for realtime architecture; null for pipeline
            and text.
        sysMsg:
          type: string
          nullable: true
          example: >-
            You are a helpful customer support agent for Acme Corp. Be concise
            and friendly.
        greetingType:
          type: string
          enum:
            - agentFirst
            - userFirst
          example: agentFirst
          description: Controls who speaks first when the call connects.
        greetingMessage:
          type: string
          nullable: true
          example: Hello! How can I help you today?
          description: >-
            Opening message spoken by the agent. Only used when greetingType is
            agentFirst.
        temperature:
          type: number
          example: 0.7
          description: LLM sampling temperature (0â€“2).
        inactivityTimeout:
          type: integer
          example: 30
          description: >-
            Seconds of user silence before the agent ends the call. Range:
            10â€“60.
        lastMessage:
          type: string
          nullable: true
          example: Is there anything else I can help you with?
          description: Final message spoken by the agent before ending the call.
        mode:
          type: string
          enum:
            - public
            - private
            - commercial
          example: public
          description: >-
            Visibility mode. public: all org members. private: creator +
            admins/owners only. commercial: globally accessible.
        functionCallingEnabled:
          type: boolean
          example: false
        enabledFunctions:
          type: array
          items:
            type: string
          description: IDs of built-in functions enabled for this agent.
        enabledCustomFunctions:
          type: array
          items:
            type: string
          description: IDs of custom (webhook) functions enabled for this agent.
        languages:
          type: array
          items:
            type: object
            properties:
              id:
                type: string
              language:
                type: string
                example: en
          description: Languages the agent is configured to support.
        userId:
          type: string
          description: ID of the user who created this agent.
        organizationId:
          type: string
          description: ID of the organization this agent belongs to.
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: tk_live_...
      description: Your TalkifAI API key. Get it from Studio â†’ Settings â†’ API Keys.
    apiKeyHeader:
      type: apiKey
      in: header
      name: x-api-key
      description: >-
        Your TalkifAI API key. Generate from Studio → Settings → API Keys.
        Format: `tk_live_...`

````