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

# Post Message

> Send a message to an existing conversation. The AI agent will respond based on the conversation context and your codebase knowledge graph.

## Use Cases

* Ask questions about your codebase
* Request debugging assistance
* Get explanations of code functionality
* Ask for code improvements or refactoring suggestions
* Inquire about code relationships and dependencies

## Authentication

This endpoint requires API key authentication via the `x-api-key` header.

```bash theme={null}
x-api-key: YOUR_API_KEY
```

<AccordionGroup>
  <Accordion title="Request & Response">
    | Location | Field                   | Type           | Required | Default | Description                                                                            |
    | -------- | ----------------------- | -------------- | -------- | ------- | -------------------------------------------------------------------------------------- |
    | Path     | `conversation_id`       | string         | required | -       | The unique identifier of the conversation (obtained from Create Conversation endpoint) |
    | Query    | `stream`                | boolean        | optional | `true`  | Stream response in real-time. Set to `false` for complete response.                    |
    | Query    | `session_id`            | string         | optional | null    | Session ID for reconnection to existing streaming session                              |
    | Query    | `prev_human_message_id` | string         | optional | null    | Previous message ID for deterministic session handling                                 |
    | Query    | `cursor`                | string         | optional | null    | Stream cursor position for replay functionality                                        |
    | Form     | `content`               | string         | required | -       | Your message or question. Cannot be empty or whitespace-only.                          |
    | Form     | `node_ids`              | string         | optional | -       | JSON-encoded array of `NodeContext` objects to reference specific code nodes           |
    | Form     | `tunnel_url`            | string         | optional | -       | VS Code extension tunnel URL for local server routing                                  |
    | Form     | `attachment_ids`        | string         | optional | -       | JSON-encoded array of pre-uploaded attachment ID strings to include with your message  |
    | Response | `message`               | string         | -        | -       | AI agent's response content                                                            |
    | Response | `citations`             | array\[string] | -        | -       | Source code references used in the response                                            |
    | Response | `tool_calls`            | array          | -        | -       | Tool invocations made by the agent during response generation                          |

    **NodeContext Object Structure:**

    ```json theme={null}
    {
      "node_id": "string",
      "name": "string"
    }
    ```

    **Request Form Data Example:**

    ```
    content=How does the authentication system work?
    node_ids=[{"node_id":"node_123","name":"auth.ts"}]
    ```
  </Accordion>
</AccordionGroup>

## Node Context

Providing `node_ids` helps the agent focus on specific parts of your codebase. Because the endpoint uses `multipart/form-data`, pass `node_ids` as a JSON-encoded string in the form field:

```
content=How does this authentication function work?
node_ids=[{"node_id":"node_123","name":"AuthService.authenticate"},{"node_id":"node_456","name":"TokenValidator"}]
```

<Tip>
  You can find node IDs by using the [Search Codebase](/api-reference/endpoint/search-codebase) endpoint or through the Potpie UI.
</Tip>

## Error Responses

<AccordionGroup>
  <Accordion title="400 Bad Request">
    The endpoint validates that message content is not empty.

    ```json theme={null}
    {
      "detail": "Message content cannot be empty"
    }
    ```

    **Causes:**

    * Empty string provided in `content` field
    * Whitespace-only content
    * Missing `content` field entirely

    **Solution:** Provide non-empty message content:

    ```json theme={null}
    {
      "content": "How does authentication work?"
    }
    ```
  </Accordion>

  <Accordion title="401 Unauthorized">
    The endpoint requires a valid API key for authentication.

    ```json theme={null}
    {
      "detail": "API key is required"
    }
    ```

    **Causes:**

    * Missing `x-api-key` header
    * Invalid or expired API key

    **Solution:** Include a valid API key in the request header.
  </Accordion>

  <Accordion title="402 Payment Required">
    The endpoint returns this error when you have exceeded your plan's usage limits.

    ```json theme={null}
    {
      "detail": "Subscription required to create a conversation."
    }
    ```

    **Causes:**

    * Message limit exceeded for your current plan
    * Subscription has expired

    **Solution:** Upgrade your subscription plan or wait for limits to reset.
  </Accordion>

  <Accordion title="404 Not Found">
    The endpoint returns this error when the conversation doesn't exist or you lack access.

    ```json theme={null}
    {
      "detail": "Conversation not found"
    }
    ```

    **Causes:**

    * Invalid `conversation_id` in URL path
    * Conversation was deleted
    * You don't have access to this conversation

    **Solution:** Verify the conversation ID and ensure you have proper access permissions.
  </Accordion>

  <Accordion title="500 Internal Server Error">
    The endpoint returns this error when unexpected exceptions occur during message processing.

    ```json theme={null}
    {
      "detail": "Internal server error"
    }
    ```

    **Causes:**

    * Celery worker unavailable for message processing
    * Database connection failures
    * Invalid node IDs or attachment IDs

    **Solution:** Retry the request after a brief delay. Verify all node IDs and attachment IDs are valid.
  </Accordion>
</AccordionGroup>

## Complete Workflow

<CodeGroup>
  ```typescript TypeScript theme={null}
  const formData = new FormData();
  formData.append('content', 'How does the authentication flow work in this codebase?');
  // Optionally attach node context as a JSON string:
  // formData.append('node_ids', JSON.stringify([{ node_id: 'node_123', name: 'AuthService' }]));

  const response = await fetch(
    'http://localhost:8001/api/v2/conversations/conv_789/message/?stream=false',
    {
      method: 'POST',
      headers: {
        'x-api-key': 'YOUR_API_KEY'
        // Do not set Content-Type — the browser sets it automatically with the multipart boundary
      },
      body: formData
    }
  );

  const data = await response.json();
  console.log('Response:', data.message);
  ```

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

  # Send message referencing specific code nodes
  response = requests.post(
      'http://localhost:8001/api/v2/conversations/conv_789/message/',
      params={'stream': False},
      headers={
          'x-api-key': 'YOUR_API_KEY'
      },
      data={
          'content': 'Can you explain how these components interact?',
          'node_ids': json.dumps([
              {'node_id': 'node_123', 'name': 'AuthService'},
              {'node_id': 'node_456', 'name': 'UserController'}
          ])
      }
  )

  result = response.json()
  print(f"Response: {result['message']}")
  ```

  ```bash cURL theme={null}
  curl -X POST \
    'http://localhost:8001/api/v2/conversations/conv_789/message/?stream=false' \
    -H 'x-api-key: YOUR_API_KEY' \
    -F 'content=How does authentication work?'
  ```
</CodeGroup>

## Message Types

Different message patterns for different tasks:

### Question & Answer

```
"What does the parseUserData function do?"
"Where is the JWT token validated?"
"How are database migrations handled?"
```

### Debugging

```
"I'm getting 'TypeError: Cannot read property...' in UserService"
"Why is the authentication failing for OAuth users?"
"The cache is not invalidating properly, can you investigate?"
```

### Code Review

```
"Review the error handling in the payment service"
"Is the API endpoint properly secured?"
"Suggest improvements for the authentication middleware"
```

## Response Streaming

When `stream=true` (the default), the endpoint returns a streaming response via Server-Sent Events. Each event chunk contains a partial or complete agent response. When `stream=false`, the endpoint returns a single JSON object with the complete response:

```json theme={null}
{
  "message": "The authentication system uses JWT tokens...",
  "citations": ["src/auth/jwt.ts", "src/middleware/auth.ts"],
  "tool_calls": []
}
```


## OpenAPI

````yaml POST /api/v2/conversations/{conversation_id}/message/
openapi: 3.1.0
info:
  title: Potpie API
  version: 2.0.0
  description: >-
    AI-powered codebase intelligence API. Build powerful integrations with
    Potpie's parsing, conversation, search, and agent capabilities.
  contact:
    name: Potpie Support
    email: hi@potpie.ai
    url: https://potpie.ai
  license:
    name: Proprietary
    url: https://potpie.ai/terms
servers:
  - url: http://localhost:8001
    description: Local server
security:
  - ApiKeyAuth: []
tags:
  - name: Parsing
    description: Repository parsing and status management
  - name: Projects
    description: Project management and listing
  - name: Conversations
    description: AI conversation management
  - name: Agents
    description: AI agent information and selection
  - name: Search
    description: Codebase semantic search
  - name: Integrations
    description: External service integrations
paths:
  /api/v2/conversations/{conversation_id}/message/:
    post:
      tags:
        - Conversations
      summary: Post Message
      description: >-
        Send a message to an existing conversation. The AI agent will respond
        based on the conversation context and your codebase knowledge graph.
      operationId: postMessage
      parameters:
        - name: conversation_id
          in: path
          required: true
          description: The conversation ID to send the message to
          schema:
            type: string
          example: conv_xyz789abc123
        - name: stream
          in: query
          required: false
          description: Whether to stream the response
          schema:
            type: boolean
            default: true
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required:
                - content
              properties:
                content:
                  type: string
                  description: >-
                    Your message or question. Cannot be empty or
                    whitespace-only.
                  minLength: 1
                node_ids:
                  type: string
                  description: >-
                    JSON-encoded array of NodeContext objects to reference
                    specific code nodes. Example:
                    [{"node_id":"node_123","name":"AuthService"}]
                tunnel_url:
                  type: string
                  description: VS Code extension tunnel URL for local server routing
                images:
                  type: array
                  items:
                    type: string
                    format: binary
                  description: Image attachments to include with your message
            examples:
              simple:
                summary: Simple message
                value:
                  content: How does the authentication system work?
              with_context:
                summary: Message with node context
                value:
                  content: Explain this function
                  node_ids: >-
                    [{"node_id":"func_authenticate_user_123","name":"authenticate_user"}]
      responses:
        '200':
          description: Message sent successfully and response received
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    description: AI agent's response content
                  citations:
                    type: array
                    items:
                      type: string
                    description: Source code references used in the response
                  tool_calls:
                    type: array
                    items: {}
                    description: >-
                      Tool invocations made by the agent during response
                      generation
              example:
                message: The authentication system uses JWT tokens...
                citations:
                  - src/auth/jwt.ts
                  - src/middleware/auth.ts
                tool_calls: []
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '402':
          $ref: '#/components/responses/PaymentRequired'
        '404':
          $ref: '#/components/responses/NotFound'
components:
  responses:
    BadRequest:
      description: Bad request - Invalid parameters
      content:
        application/json:
          schema:
            type: object
            properties:
              detail:
                type: string
          example:
            detail: Either repo_name or repo_path must be provided
    Unauthorized:
      description: Unauthorized - Invalid or missing API key
      content:
        application/json:
          schema:
            type: object
            properties:
              detail:
                type: string
          example:
            detail: Invalid API key
    PaymentRequired:
      description: Payment required - Subscription or usage limit issue
      content:
        application/json:
          schema:
            type: object
            properties:
              detail:
                type: string
          example:
            detail: Subscription required to create a conversation
    NotFound:
      description: Resource not found
      content:
        application/json:
          schema:
            type: object
            properties:
              detail:
                type: string
          example:
            detail: Project not found
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: x-api-key
      description: >-
        API key authentication. Get your key from <a
        href="https://app.potpie.ai/settings" style="color: #60a5fa;
        font-weight: bold; text-decoration: none !important;">potpie settings
        page</a>

````