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

# Create Thread

> Create a new conversation thread for stateful chat sessions

<Note>
  **Recommended:** This is the preferred way to start a conversation with the Cura AI. Threads handle context automatically.
</Note>

## Overview

Creates a new conversation thread with a unique 5-digit ID. Once created, you can send multiple messages to this thread and the AI will automatically remember the conversation history (last 20 messages).

### Authentication

<ParamField header="X-API-Key" type="string" required>
  Your Cura API key
</ParamField>

### Body Parameters

<Note>
  **All parameters are optional.** You can send an empty body `{}` for general conversations without patient context.
</Note>

<ParamField body="patientId" type="string (UUID)">
  Optional patient UUID to link this thread to a patient profile. The AI will have access to patient data.
</ParamField>

<ParamField body="phone" type="string">
  Optional patient phone number (any format: `5551234567`, `+15551234567`, `(555) 123-4567`).

  The system will automatically find the patient and link the thread.
</ParamField>

<ParamField body="metadata" type="object">
  Optional metadata to store with the thread (e.g., session info, source, tags).

  ```json theme={null}
  {
    "source": "mobile_app",
    "sessionId": "abc123",
    "name": "Medication Questions"
  }
  ```
</ParamField>

### Examples:

* `{}` - General conversation (no patient lookup) **Recommended**
* `{"phone": "5551234567"}` - With patient lookup
* `{"patientId": "uuid-123"}` - With patient ID

## Request Example

<CodeGroup>
  ```bash cURL theme={null}
  # General conversation (recommended)
  curl -X POST "https://api.mycura.org/api/cura/threads" \
    -H "X-API-Key: YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{}'

  # With patient lookup
  curl -X POST "https://api.mycura.org/api/cura/threads" \
    -H "X-API-Key: YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "phone": "5551234567",
      "metadata": {
        "source": "mobile_app"
      }
    }'
  ```

  ```javascript Node.js theme={null}
  const axios = require('axios');

  const response = await axios.post(
    'https://api.mycura.org/api/cura/threads',
    {
      phone: '5551234567',
      metadata: {
        source: 'mobile_app'
      }
    },
    {
      headers: {
        'X-API-Key': 'YOUR_API_KEY',
        'Content-Type': 'application/json'
      }
    }
  );

  console.log(response.data.threadId);
  ```

  ```python Python theme={null}
  import requests

  response = requests.post(
      'https://api.mycura.org/api/cura/threads',
      json={
          'phone': '5551234567',
          'metadata': {
              'source': 'mobile_app'
          }
      },
      headers={
          'X-API-Key': 'YOUR_API_KEY',
          'Content-Type': 'application/json'
      }
  )

  thread_id = response.json()['threadId']
  print(f"Created thread: {thread_id}")
  ```

  ```php PHP theme={null}
  <?php
  $ch = curl_init('https://api.mycura.org/api/cura/threads');
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
      'phone' => '5551234567',
      'metadata' => ['source' => 'mobile_app']
  ]));
  curl_setopt($ch, CURLOPT_HTTPHEADER, [
      'X-API-Key: YOUR_API_KEY',
      'Content-Type: application/json'
  ]);

  $response = curl_exec($ch);
  $data = json_decode($response, true);
  echo "Thread ID: " . $data['threadId'];
  ?>
  ```
</CodeGroup>

## Response

<ResponseField name="success" type="boolean">
  Whether the thread was created successfully
</ResponseField>

<ResponseField name="threadId" type="string">
  Unique 5-digit thread identifier (e.g., `"82451"`)
</ResponseField>

<ResponseField name="initialMessage" type="string (optional)">
  An initial question from the AI to start the conversation (e.g., demographic questions like gender). Display this message to the user immediately after thread creation to begin the conversation flow.
</ResponseField>

<ResponseField name="expiresAt" type="string (ISO 8601)">
  ISO 8601 timestamp when the thread will auto-delete (30 minutes from creation)
</ResponseField>

<ResponseField name="messageCount" type="number">
  Initial message count (typically 0 for new threads, or 2 if initialMessage is present)
</ResponseField>

<ResponseField name="message" type="string">
  Success message with usage instructions
</ResponseField>

### Success Response (201)

```json theme={null}
{
  "success": true,
  "threadId": "82451",
  "initialMessage": "Are you male or female?",
  "expiresAt": "2025-11-10T15:30:00Z",
  "messageCount": 2,
  "message": "Thread created successfully. Use this threadId in your chat requests."
}
```

<Note>
  The `initialMessage` field may or may not be present depending on whether the AI has an initial question. Always check for its presence and display it to the user if available.
</Note>

## Error Responses

<ResponseExample>
  ```json 401 Unauthorized theme={null}
  {
    "error": "Unauthorized - Invalid API key"
  }
  ```

  ```json 500 Internal Server Error theme={null}
  {
    "error": "Failed to create thread"
  }
  ```
</ResponseExample>

## Thread Features

<CardGroup cols={2}>
  <Card title="Unique 5-Digit ID" icon="fingerprint">
    Each thread gets a unique identifier that's easy to reference and share
  </Card>

  <Card title="Auto-Expires in 30 Min" icon="clock">
    Threads automatically delete after 30 minutes of inactivity for privacy
  </Card>

  <Card title="Automatic Context" icon="brain">
    Last 20 messages auto-loaded on every request - no manual history management
  </Card>

  <Card title="Patient Linking" icon="user">
    Optional patient linking gives AI access to medical information
  </Card>
</CardGroup>

## Usage Flow

<Steps>
  <Step title="Create Thread">
    Make this request to get a `threadId`
  </Step>

  <Step title="Save Thread ID">
    Store the `threadId` on your client (localStorage, state, session, etc.)
  </Step>

  <Step title="Send Messages">
    Use the `threadId` in your [chat requests](/api-reference/endpoint/chat)
  </Step>

  <Step title="Continue Conversation">
    Keep using the same `threadId` - context is automatic!
  </Step>
</Steps>

## Best Practices

<AccordionGroup>
  <Accordion title="Create threads at session start">
    When a user opens your app or starts a new conversation, create a thread immediately:

    ```javascript theme={null}
    // On app load
    useEffect(() => {
      if (!sessionStorage.threadId) {
        createThread().then(thread => {
          sessionStorage.threadId = thread.threadId;
        });
      }
    }, []);
    ```
  </Accordion>

  <Accordion title="Link to patients when available">
    If you have patient information, include it for better AI context:

    ```javascript theme={null}
    // With patient
    await createThread({ phone: user.phone });

    // Without patient (anonymous)
    await createThread({});
    ```
  </Accordion>

  <Accordion title="Use metadata for tracking">
    Store useful information in metadata for analytics:

    ```javascript theme={null}
    await createThread({
      phone: user.phone,
      metadata: {
        platform: 'iOS',
        version: '2.1.0',
        sessionId: generateSessionId()
      }
    });
    ```
  </Accordion>

  <Accordion title="Handle expiration gracefully">
    Monitor `expiresAt` and create new threads when needed:

    ```javascript theme={null}
    if (new Date(thread.expiresAt) < new Date()) {
      // Thread expired, create new one
      const newThread = await createThread({ phone: user.phone });
      sessionStorage.threadId = newThread.threadId;
    }
    ```
  </Accordion>
</AccordionGroup>

## Related Endpoints

<CardGroup cols={3}>
  <Card title="Chat" icon="message" href="/api-reference/endpoint/chat">
    Send messages to the thread
  </Card>

  <Card title="Get Thread" icon="circle-info" href="/api-reference/endpoint/get-thread">
    Retrieve thread information
  </Card>

  <Card title="Delete Thread" icon="trash" href="/api-reference/endpoint/delete-thread">
    Manually end a conversation
  </Card>
</CardGroup>

## Next Steps

<Card title="Learn About Conversation Threads" icon="graduation-cap" href="/conversation-threads">
  Comprehensive guide to using threads effectively
</Card>
