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

# Human Intelligence API

> Real-time conversations with personas powered by real human expertise

## Overview

The Human Intelligence API enables real-time conversations with personas trained on real human expertise. It uses Server-Sent Events (SSE) for streaming responses and supports file attachments, course context, and authenticated/anonymous users.

## Request Body

<ParamField body="message" type="string" required>
  The user's message content
</ParamField>

<ParamField body="thread_id" type="string">
  Existing thread ID. If not provided, a new thread will be created automatically. The thread ID is returned in the response headers (`X-Thread-Id`) and in the message data.
</ParamField>

<ParamField body="language" type="string" default="en">
  **🧪 Experimental Feature**

  ISO 639-1 language code for responses. The persona will respond naturally in the specified language while maintaining their authentic voice and real human expertise.

  **Supported Languages (65):** English, Spanish, French, German, Chinese, Japanese, Arabic, Hebrew, Hindi, Portuguese, Russian, Italian, Korean, and 52 more.

  **RTL Languages:** Arabic (`ar`), Hebrew (`he`), Persian (`fa`), Urdu (`ur`) automatically render right-to-left.

  **Examples:** `en` (English), `es` (Spanish), `fr` (French), `zh` (Chinese), `ar` (Arabic), `he` (Hebrew)

  <Note>This feature is in experimental phase. Language quality may vary by language and coaching context.</Note>
</ParamField>

<ParamField body="context" type="object" required>
  Context information for the conversation

  <Expandable title="context properties">
    <ParamField body="context.coachId" type="string" required>
      Persona identifier (trained with real human knowledge)
    </ParamField>

    <ParamField body="context.modeId" type="string">
      Consultation mode ID (e.g., for different coaching specialties)
    </ParamField>

    <ParamField body="context.courseId" type="string">
      Course ID if the conversation is part of a structured course
    </ParamField>

    <ParamField body="context.userId" type="string">
      User identifier (for authenticated users)
    </ParamField>

    <ParamField body="context.isAuthenticated" type="boolean">
      Whether the user is authenticated
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="attachments" type="array">
  File attachments for the message

  <Expandable title="attachment object">
    <ParamField body="id" type="string" required>
      File ID (file must be uploaded)
    </ParamField>

    <ParamField body="type" type="string" required>
      MIME type (e.g., "image/png", "application/pdf")
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="action" type="string">
  Special action to execute:

  * `create_knowledge` - Create knowledge content (requires coach authentication)
</ParamField>

## Response

The API returns a streaming response using Server-Sent Events (SSE). The thread ID is included in both:

* Response header: `X-Thread-Id`
* SSE message data

<ResponseField name="X-Thread-Id" type="header">
  Thread ID for the conversation (in response headers)
</ResponseField>

**SSE Event Format:**

* Each chunk is prefixed with `data: `
* Contains text chunks from the persona's response (powered by real human knowledge)
* Final chunk signals completion

<RequestExample>
  ```bash cURL theme={null}
  curl -X POST "https://api.myweave.ai/functions/v1/chat" \
    -H "Content-Type: application/json" \
    -H "X-API-Key: your-api-key-here" \
    -d '{
      "message": "Hello, I need help with leadership development",
      "context": {
        "coachId": "coach_xyz789",
        "userId": "user_123",
        "isAuthenticated": true
      }
    }' \
    --no-buffer
  ```

  ```bash cURL with Thread theme={null}
  curl -X POST "https://api.myweave.ai/functions/v1/chat" \
    -H "Content-Type: application/json" \
    -H "X-API-Key: your-api-key-here" \
    -d '{
      "message": "Can you give me some examples?",
      "thread_id": "550e8400-e29b-41d4-a716-446655440000",
      "context": {
        "coachId": "coach_xyz789",
        "userId": "user_123"
      }
    }' \
    --no-buffer
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('https://api.myweave.ai/functions/v1/chat', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-API-Key': 'your-api-key-here'
    },
    body: JSON.stringify({
      message: "Hello, I need help with leadership development",
      context: {
        coachId: "coach_xyz789",
        userId: "user_123",
        isAuthenticated: true
      }
    })
  });

  // Get thread ID from headers
  const threadId = response.headers.get('X-Thread-Id');
  console.log('Thread ID:', threadId);

  // Handle streaming response
  const reader = response.body?.getReader();
  const decoder = new TextDecoder();

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    
    const chunk = decoder.decode(value);
    const lines = chunk.split('\n');
    
    for (const line of lines) {
      if (line.startsWith('data: ')) {
        const text = line.slice(6);
        console.log('Chunk:', text);
      }
    }
  }
  ```

  ```javascript With File Attachments theme={null}
  const response = await fetch('https://api.myweave.ai/functions/v1/chat', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-API-Key': 'your-api-key-here'
    },
    body: JSON.stringify({
      message: "Can you review this document?",
      thread_id: "550e8400-e29b-41d4-a716-446655440000",
      context: {
        coachId: "coach_xyz789",
        userId: "user_123"
      },
      attachments: [
        {
          id: "file-abc123xyz",
          type: "application/pdf"
        }
      ]
    })
  });
  ```

  ```javascript Multilingual Chat (Spanish) theme={null}
  const response = await fetch('https://api.myweave.ai/functions/v1/chat', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-API-Key': 'your-api-key-here'
    },
    body: JSON.stringify({
      message: "Hola, necesito ayuda con desarrollo de liderazgo",
      language: "es", // AI will respond in Spanish
      context: {
        coachId: "coach_xyz789",
        userId: "user_123"
      }
    })
  });
  // AI responds: "¡Hola! Estaré encantado de ayudarte con el desarrollo de liderazgo..."
  ```

  ```bash Multilingual Chat (Arabic - RTL) theme={null}
  curl -X POST "https://api.myweave.ai/functions/v1/chat" \
    -H "Content-Type: application/json" \
    -H "X-API-Key: your-api-key-here" \
    -d '{
      "message": "مرحبا، أحتاج مساعدة في تطوير القيادة",
      "language": "ar",
      "context": {
        "coachId": "coach_xyz789",
        "userId": "user_123"
      }
    }' \
    --no-buffer
  ```

  ```javascript Multilingual Chat (Hebrew - RTL) theme={null}
  const response = await fetch('https://api.myweave.ai/functions/v1/chat', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-API-Key': 'your-api-key-here'
    },
    body: JSON.stringify({
      message: "שלום, אני צריך עזרה בפיתוח מנהיגות",
      language: "he", // AI will respond in Hebrew (RTL)
      context: {
        coachId: "coach_xyz789",
        userId: "user_123"
      }
    })
  });
  // AI responds: "!שלום! אשמח לעזור לך בפיתוח מנהיגות. בוא נתחיל..."
  ```

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

  url = "https://api.myweave.ai/functions/v1/chat"
  headers = {
      "Content-Type": "application/json",
      "X-API-Key": "your-api-key-here"
  }

  payload = {
      "message": "Hello, I need help with leadership development",
      "context": {
          "coachId": "coach_xyz789",
          "userId": "user_123",
          "isAuthenticated": True
      }
  }

  response = requests.post(url, headers=headers, json=payload, stream=True)

  # Get thread ID from headers
  thread_id = response.headers.get('X-Thread-Id')
  print(f"Thread ID: {thread_id}")

  # Stream the response
  for line in response.iter_lines():
      if line:
          decoded_line = line.decode('utf-8')
          if decoded_line.startswith('data: '):
              text = decoded_line[6:]
              print("Chunk:", text)
  ```
</RequestExample>

<ResponseExample>
  ```text Streaming Response theme={null}
  data: Hello! I'd be happy to help you with leadership development.
  data:  Let's start by understanding your current goals...
  data: 

  [Response completes]
  ```

  ```json 400 Bad Request theme={null}
  {
    "error": "Missing required parameters: message and coachId"
  }
  ```

  ```json 401 Unauthorized (create_knowledge) theme={null}
  {
    "error": "User not authorized to create knowledge for this expert"
  }
  ```

  ```json 404 Not Found theme={null}
  {
    "error": "Coach not found"
  }
  ```
</ResponseExample>

## Features

* **Real-time Streaming**: Server-sent events for live responses
* **Multilingual Support**: Personas respond in 65 languages including RTL languages (Arabic, Hebrew, Persian, Urdu)
* **Human Expertise**: Each persona trained on real human knowledge and expertise
* **Automatic Thread Management**: Threads created automatically, ID returned in headers
* **File Attachments**: Support for images, PDFs, and documents
* **Course Integration**: Connect conversations to structured courses and lessons
* **Mode-based Conversations**: Different consultation modes per persona
* **Anonymous & Authenticated**: Works for both user types
* **Knowledge Creation**: Special `create_knowledge` action for persona owners (requires authentication)

## Thread Management

**First Message (New Thread):**

* Don't include `thread_id` in request
* API creates new thread automatically
* Thread ID returned in `X-Thread-Id` header
* Store this ID for continuing the conversation

**Follow-up Messages (Existing Thread):**

* Include `thread_id` from previous response
* Continues the conversation in same thread
* Maintains full conversation context

## Authentication

* **For Users**: No authentication required for basic chat
* **For Persona Owners**: Bearer token required when using `action: "create_knowledge"`
  * Include `Authorization: Bearer <jwt_token>` header
  * Must be authenticated as the persona owner specified in `coachId`

## Use Cases

* **1-on-1 Conversations**: Real-time persona consultations powered by real human expertise
* **Course Learning**: Contextual help within structured courses built on human knowledge
* **Document Review**: Upload files for persona feedback based on real expertise
* **Knowledge Creation**: Persona owners can create training content via chat
* **Global Multilingual Support**: Personas respond in user's native language while maintaining authentic human voice

## Supported Languages (65) 🧪 Experimental

The Chat API supports 65 languages for AI responses. Simply include the `language` parameter with the ISO 639-1 code.

<Warning>
  **Experimental Feature**: Multilingual support is currently in beta. While the AI can respond in all listed languages, quality and accuracy may vary. We recommend testing thoroughly for production use cases.
</Warning>

### Language Codes Reference

| Code | Language   | Native Name      | Flag | Notes            |
| ---- | ---------- | ---------------- | ---- | ---------------- |
| `en` | English    | English          | 🌍   | Default language |
| `sq` | Albanian   | Shqip            | 🇦🇱 |                  |
| `am` | Amharic    | አማርኛ             | 🇪🇹 |                  |
| `ar` | Arabic     | العربية          | 🇸🇦 | **RTL**          |
| `hy` | Armenian   | Հայերեն          | 🇦🇲 |                  |
| `bn` | Bengali    | বাংলা            | 🇧🇩 |                  |
| `bs` | Bosnian    | Bosanski         | 🇧🇦 |                  |
| `bg` | Bulgarian  | Български        | 🇧🇬 |                  |
| `my` | Burmese    | မြန်မာ           | 🇲🇲 |                  |
| `ca` | Catalan    | Català           | 🇪🇸 |                  |
| `zh` | Chinese    | 中文               | 🇨🇳 |                  |
| `hr` | Croatian   | Hrvatski         | 🇭🇷 |                  |
| `cs` | Czech      | Čeština          | 🇨🇿 |                  |
| `da` | Danish     | Dansk            | 🇩🇰 |                  |
| `nl` | Dutch      | Nederlands       | 🇳🇱 |                  |
| `et` | Estonian   | Eesti            | 🇪🇪 |                  |
| `fi` | Finnish    | Suomi            | 🇫🇮 |                  |
| `fr` | French     | Français         | 🇫🇷 |                  |
| `ka` | Georgian   | ქართული          | 🇬🇪 |                  |
| `de` | German     | Deutsch          | 🇩🇪 |                  |
| `el` | Greek      | Ελληνικά         | 🇬🇷 |                  |
| `gu` | Gujarati   | ગુજરાતી          | 🇮🇳 |                  |
| `he` | Hebrew     | עברית            | 🇮🇱 | **RTL**          |
| `hi` | Hindi      | हिन्दी           | 🇮🇳 |                  |
| `hu` | Hungarian  | Magyar           | 🇭🇺 |                  |
| `is` | Icelandic  | Íslenska         | 🇮🇸 |                  |
| `id` | Indonesian | Bahasa Indonesia | 🇮🇩 |                  |
| `it` | Italian    | Italiano         | 🇮🇹 |                  |
| `ja` | Japanese   | 日本語              | 🇯🇵 |                  |
| `kn` | Kannada    | ಕನ್ನಡ            | 🇮🇳 |                  |
| `kk` | Kazakh     | Қазақша          | 🇰🇿 |                  |
| `ko` | Korean     | 한국어              | 🇰🇷 |                  |
| `lv` | Latvian    | Latviešu         | 🇱🇻 |                  |
| `lt` | Lithuanian | Lietuvių         | 🇱🇹 |                  |
| `mk` | Macedonian | Македонски       | 🇲🇰 |                  |
| `ms` | Malay      | Bahasa Melayu    | 🇲🇾 |                  |
| `ml` | Malayalam  | മലയാളം           | 🇮🇳 |                  |
| `mr` | Marathi    | मराठी            | 🇮🇳 |                  |
| `mn` | Mongolian  | Монгол           | 🇲🇳 |                  |
| `no` | Norwegian  | Norsk            | 🇳🇴 |                  |
| `fa` | Persian    | فارسی            | 🇮🇷 | **RTL**          |
| `pl` | Polish     | Polski           | 🇵🇱 |                  |
| `pt` | Portuguese | Português        | 🇵🇹 |                  |
| `pa` | Punjabi    | ਪੰਜਾਬੀ           | 🇮🇳 |                  |
| `ro` | Romanian   | Română           | 🇷🇴 |                  |
| `ru` | Russian    | Русский          | 🇷🇺 |                  |
| `sr` | Serbian    | Српски           | 🇷🇸 |                  |
| `sk` | Slovak     | Slovenčina       | 🇸🇰 |                  |
| `sl` | Slovenian  | Slovenščina      | 🇸🇮 |                  |
| `so` | Somali     | Soomaali         | 🇸🇴 |                  |
| `es` | Spanish    | Español          | 🇪🇸 |                  |
| `sw` | Swahili    | Kiswahili        | 🇰🇪 |                  |
| `sv` | Swedish    | Svenska          | 🇸🇪 |                  |
| `tl` | Tagalog    | Tagalog          | 🇵🇭 |                  |
| `ta` | Tamil      | தமிழ்            | 🇮🇳 |                  |
| `te` | Telugu     | తెలుగు           | 🇮🇳 |                  |
| `th` | Thai       | ไทย              | 🇹🇭 |                  |
| `tr` | Turkish    | Türkçe           | 🇹🇷 |                  |
| `uk` | Ukrainian  | Українська       | 🇺🇦 |                  |
| `ur` | Urdu       | اردو             | 🇵🇰 | **RTL**          |
| `vi` | Vietnamese | Tiếng Việt       | 🇻🇳 |                  |

### Right-to-Left (RTL) Languages

Four languages automatically render right-to-left:

* **Arabic** (`ar`) - 🇸🇦 العربية
* **Hebrew** (`he`) - 🇮🇱 עברית
* **Persian** (`fa`) - 🇮🇷 فارسی
* **Urdu** (`ur`) - 🇵🇰 اردو

### Usage Notes

* **Defaults to English**: If `language` parameter is omitted or invalid, defaults to `en`
* **Case Sensitive**: Use lowercase codes (`es`, not `ES`)
* **Natural Responses**: AI maintains coaching style while responding in selected language
* **No Translation Needed**: User can send messages in any language; specify response language with `language` parameter
