> ## 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.

# Conversation Threads

> Stateful conversations with automatic context management

<Note>
  **Recommended Approach:** Conversation threads are the preferred way to build multi-turn conversations with the Cura's AI Model. They handle context automatically and provide a seamless experience.
</Note>

## Overview

Conversation threads enable **stateful, context-aware conversations** with the Cura AI without requiring you to manually manage message history. The server automatically:

* Stores all messages in the conversation
* Injects the last 20 messages as context on every request
* Auto-deletes inactive threads after 30 minutes
* Isolates conversations for privacy and clarity
* Links threads to patient profiles (optional)
* Note: All cURL requests are case sensetive.

## How It Works

<Steps>
  <Step title="Create a Thread">
    Make a `POST /api/cura/threads` request to get a unique 5-digit thread ID.

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

    Response:

    ```json theme={null}
    {
      "success": true,
      "threadId": "82451",
      "expiresAt": "2025-10-22T19:30:00.000Z",
      "message": "Thread created successfully. Use this threadId in your chat requests."
    }
    ```
  </Step>

  <Step title="Send Messages">
    Include the `threadId` in your chat requests. The AI automatically receives the conversation history.

    ```bash theme={null}
    curl -X POST "https://api.mycura.org/api/cura/chat" \
      -H "X-API-Key: YOUR_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "threadId": "82451",
        "message": "I have been experiencing headaches"
      }'
    ```

    The server **automatically**:

    * Loads the last 20 messages from this thread
    * Sends them to the AI as context
    * Appends the new message and response to the thread
    * Updates the expiration time
  </Step>

  <Step title="Continue the Conversation">
    Just keep using the same `threadId`. No need to send `conversationHistory` manually!

    ```bash theme={null}
    curl -X POST "https://api.mycura.org/api/cura/chat" \
      -H "X-API-Key: YOUR_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "threadId": "82451",
        "message": "What did we discuss about my symptoms?"
      }'
    ```

    The AI will remember everything from the thread automatically.
  </Step>

  <Step title="End the Thread (Optional)">
    Threads auto-delete after 30 minutes of inactivity, or you can manually delete them:

    ```bash theme={null}
    curl -X DELETE "https://api.mycura.org/api/cura/threads/82451" \
      -H "X-API-Key: YOUR_API_KEY"
    ```
  </Step>
</Steps>

## Key Features

### 5-Digit Thread IDs

Each thread gets a unique 5-digit identifier (e.g., `82451`, `19234`) that you use to reference the conversation.

```json theme={null}
{
  "threadId": "82451",
  "expiresAt": "2025-10-22T19:30:00.000Z"
}
```

### Automatic Context Injection

The server automatically loads and sends the **last 20 messages** from your thread to the AI on every request. You don't need to:

* Store messages on your end
* Send `conversationHistory` arrays
* Manage context windows

**The AI just remembers!**

### 30-Minute Auto-Expiration

Threads automatically delete themselves after **30 minutes of inactivity** to:

* Protect patient privacy
* Manage server resources
* Encourage focused conversations

The expiration timer **resets** every time a message is sent.

### Patient Linking (Optional)

Link a thread to a patient profile by providing their `patientId` or `phone` when creating the thread:

```json theme={null}
{
  "phone": "5551234567",
  "metadata": {
    "name": "Medication Questions",
    "source": "mobile_app"
  }
}
```

The AI will have access to the patient's medical information (medications, conditions, allergies) throughout the conversation.

### Thread Independence

Each thread is completely isolated. You can have **multiple concurrent threads** for different:

* Patients
* Topics (e.g., one for medications, one for symptoms)
* Sessions

Threads don't interfere with each other.

## When to Use Threads

<CardGroup cols={2}>
  <Card title="Use Threads When" icon="check" color="#10b981">
    * Building multi-turn conversations
    * Creating chatbot interfaces
    * Handling patient consultations
    * Needing automatic context management
    * Managing multiple conversations simultaneously
  </Card>

  <Card title="Don't Use Threads When" icon="xmark" color="#ef4444">
    * Sending single, one-off questions
    * Building stateless APIs
    * You want full control over context
    * Testing or debugging individual requests
  </Card>
</CardGroup>

## Thread vs. Manual Context

<Tabs>
  <Tab title="With Threads (Recommended)">
    ```javascript theme={null}
    // Create thread once
    const { threadId } = await createThread({ phone: "5551234567" });

    // Message 1
    await chat({ threadId, message: "I have headaches" });

    // Message 2 - AI remembers message 1 automatically
    await chat({ threadId, message: "What causes them?" });

    // Message 3 - AI remembers messages 1 & 2 automatically
    await chat({ threadId, message: "Summarize our discussion" });
    ```

    **Clean, simple, automatic**
  </Tab>

  <Tab title="Without Threads (Manual)">
    ```javascript theme={null}
    // Message 1
    const history1 = [];
    const resp1 = await chat({ 
      message: "I have headaches",
      conversationHistory: history1 
    });
    history1.push({ role: "user", content: "I have headaches" });
    history1.push({ role: "assistant", content: resp1.response });

    // Message 2 - Must manually send history
    const resp2 = await chat({ 
      message: "What causes them?",
      conversationHistory: history1 
    });
    history1.push({ role: "user", content: "What causes them?" });
    history1.push({ role: "assistant", content: resp2.response });

    // Message 3 - Must manually send growing history
    const resp3 = await chat({ 
      message: "Summarize our discussion",
      conversationHistory: history1 
    });
    ```

    **Complex, error-prone, manual management**
  </Tab>
</Tabs>

## Code Examples

### Creating a Thread

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

  async function createThread(phone) {
    const response = await axios.post(
      'https://api.mycura.org/api/cura/threads',
      { 
        phone: phone,
        metadata: { source: 'mobile_app' }
      },
      {
        headers: {
          'X-API-Key': 'YOUR_API_KEY',
          'Content-Type': 'application/json'
        }
      }
    );
    
    return response.data;
    // { threadId: "82451", expiresAt: "...", ... }
  }
  ```

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

  def create_thread(phone):
      response = requests.post(
          'https://api.mycura.org/api/cura/threads',
          json={
              'phone': phone,
              'metadata': {'source': 'mobile_app'}
          },
          headers={
              'X-API-Key': 'YOUR_API_KEY',
              'Content-Type': 'application/json'
          }
      )
      return response.json()
      # { 'threadId': '82451', 'expiresAt': '...', ... }
  ```

  ```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);
  // $data['threadId'] = '82451'
  ?>
  ```
</CodeGroup>

### Using a Thread in Conversation

<CodeGroup>
  ```javascript Node.js theme={null}
  async function chatWithThread(threadId, message) {
    const response = await axios.post(
      'https://api.mycura.org/api/cura/chat',
      { 
        threadId: threadId,
        message: message 
      },
      {
        headers: {
          'X-API-Key': 'YOUR_API_KEY',
          'Content-Type': 'application/json'
        }
      }
    );
    
    return response.data;
  }

  // Usage
  const thread = await createThread('5551234567');
  const msg1 = await chatWithThread(thread.threadId, 'I have a headache');
  const msg2 = await chatWithThread(thread.threadId, 'What could cause it?');
  const msg3 = await chatWithThread(thread.threadId, 'Summarize our chat');
  // msg3.response will include summary of headache discussion!
  ```

  ```python Python theme={null}
  def chat_with_thread(thread_id, message):
      response = requests.post(
          'https://api.mycura.org/api/cura/chat',
          json={
              'threadId': thread_id,
              'message': message
          },
          headers={
              'X-API-Key': 'YOUR_API_KEY',
              'Content-Type': 'application/json'
          }
      )
      return response.json()

  # Usage
  thread = create_thread('5551234567')
  msg1 = chat_with_thread(thread['threadId'], 'I have a headache')
  msg2 = chat_with_thread(thread['threadId'], 'What could cause it?')
  msg3 = chat_with_thread(thread['threadId'], 'Summarize our chat')
  # msg3['response'] will include summary of headache discussion!
  ```
</CodeGroup>

## Best Practices

<AccordionGroup>
  <Accordion title="Create threads at the start of a conversation session">
    When a user opens your app or starts a new chat, create a thread immediately. This ensures context is preserved throughout their session.

    ```javascript theme={null}
    // App initialization
    if (!sessionStorage.threadId) {
      const thread = await createThread();
      sessionStorage.threadId = thread.threadId;
    }
    ```
  </Accordion>

  <Accordion title="Display expiration times to users">
    Show users when their thread will expire so they know how long they have for the conversation.

    ```javascript theme={null}
    const minutesLeft = Math.floor(
      (new Date(expiresAt) - new Date()) / 1000 / 60
    );
    console.log(`Thread expires in ${minutesLeft} minutes`);
    ```
  </Accordion>

  <Accordion title="Link threads to patients when possible">
    If you have patient information, link the thread to provide better context to the AI.

    ```javascript theme={null}
    // Preferred
    await createThread({ 
      phone: "5551234567",
      metadata: { sessionId: "abc123" }
    });

    // Also works without patient
    await createThread({ 
      metadata: { anonymous: true }
    });
    ```
  </Accordion>

  <Accordion title="Clean up threads when users log out">
    Manually delete threads when a user logs out or closes the app for privacy.

    ```javascript theme={null}
    window.addEventListener('beforeunload', async () => {
      if (sessionStorage.threadId) {
        await deleteThread(sessionStorage.threadId);
      }
    });
    ```
  </Accordion>

  <Accordion title="Store threadId on your side for analytics">
    Keep track of thread IDs in your database to analyze conversation patterns and usage.

    ```javascript theme={null}
    await db.sessions.create({
      userId: currentUser.id,
      threadId: thread.threadId,
      createdAt: new Date()
    });
    ```
  </Accordion>
</AccordionGroup>

## Related Endpoints

<CardGroup cols={2}>
  <Card title="Create Thread" icon="plus" href="/api-reference/endpoint/create-thread">
    `POST /api/cura/threads`
  </Card>

  <Card title="Get Thread Info" icon="circle-info" href="/api-reference/endpoint/get-thread">
    `GET /api/cura/threads/{id}`
  </Card>

  <Card title="Delete Thread" icon="trash" href="/api-reference/endpoint/delete-thread">
    `DELETE /api/cura/threads/{id}`
  </Card>

  <Card title="Chat with Thread" icon="message" href="/api-reference/endpoint/chat">
    `POST /api/cura/chat`
  </Card>
</CardGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Quick Start" icon="rocket" href="/quickstart">
    Build your first conversation in 5 minutes
  </Card>

  <Card title="API Reference" icon="code" href="/api-reference/introduction">
    Detailed endpoint documentation
  </Card>

  <Card title="Best Practices" icon="lightbulb" href="/best-practices">
    Tips for production applications
  </Card>

  <Card title="Client Examples" icon="laptop-code" href="/client-examples">
    Code examples in multiple languages
  </Card>
</CardGroup>
