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

# Chat

> Ground Agent — answers with citations; REST, streaming SSE, and optional PDF context.

# Chat API

The Chat API runs **retrieval over your indexed sources** (and optional package scope), then generates an answer with **citations**. Use **`POST /chat`** for a single JSON response, or **`POST /chat/stream`** for **Server-Sent Events** (`event: token`, `event: done`, `event: error`).

## Endpoints

```
POST /chat
POST /chat/stream
POST /chat/upload-pdf
```

## Request (`POST /chat`)

<ParamField body="query" type="string" required>
  The question to ask the Ground Agent
</ParamField>

<ParamField body="conversation_id" type="string">
  Optional. When authenticated via JWT (dashboard), continues an existing conversation.
</ParamField>

<ParamField body="top_k" type="integer" default="5">
  Number of sources to use as context (1-10)
</ParamField>

<ParamField body="max_context_tokens" type="integer" default="4000">
  Maximum tokens for context window
</ParamField>

<ParamField body="include_global" type="boolean" default="true">
  Include pre-indexed global packages in search
</ParamField>

<ParamField body="source_ids" type="string[]">
  Optional. Restrict retrieval to specific source IDs (e.g. “talk to one repo”).
</ParamField>

<ParamField body="scope" type="string">
  Optional. Use `ground_docs` to limit to Ground’s own documentation source when enabled.
</ParamField>

### Streaming (`POST /chat/stream`)

Same fields as above, plus optional **`package_mentions`** (for example `[{"package_name":"react","ecosystem":"npm"}]`) to blend in on-demand package context. Consume the **SSE** stream in your client; the `done` event includes citations, timing, and `conversation_id` when persisted.

### PDF context (`POST /chat/upload-pdf`)

Multipart form: **`file`** (PDF) and **`conversation_id`**. Requires JWT auth matching the conversation. Chunks are stored for ephemeral retrieval during that conversation’s chat turns.

## Response

<ResponseField name="answer" type="string">
  AI-generated answer based on Ground's indexed documentation
</ResponseField>

<ResponseField name="citations" type="array">
  List of sources used to generate the answer

  <Expandable title="Citation object">
    <ResponseField name="source_name" type="string">
      Name of the source (e.g., "NPM: react")
    </ResponseField>

    <ResponseField name="content" type="string">
      Excerpt from the source
    </ResponseField>

    <ResponseField name="score" type="number">
      Relevance score (0-1)
    </ResponseField>

    <ResponseField name="path" type="string">
      Path within the source
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="search_time_ms" type="number">
  Time taken to search Ground's index
</ResponseField>

<ResponseField name="completion_time_ms" type="number">
  Time taken for AI to generate answer
</ResponseField>

<ResponseField name="total_time_ms" type="number">
  Total response time
</ResponseField>

<ResponseField name="model_used" type="string">
  AI model used (e.g., "gpt-4o")
</ResponseField>

## Example

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST https://api.trygroundai.com/chat \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "query": "How do I use React hooks for state management?",
      "top_k": 5
    }'
  ```

  ```typescript TypeScript theme={null}
  import { Ground } from '@groundai/sdk';

  const ground = new Ground({ apiKey: 'YOUR_API_KEY' });

  const response = await ground.chat({
    query: 'How do I use React hooks for state management?',
    topK: 5,
  });

  console.log(response.answer);
  console.log('Sources:', response.citations.length);
  ```

  ```python Python theme={null}
  from ground import Ground

  ground = Ground(api_key="YOUR_API_KEY")

  response = ground.chat(
      query="How do I use React hooks for state management?",
      top_k=5,
  )

  print(response.answer)
  print(f"Sources: {len(response.citations)}")
  ```
</CodeGroup>

## Response Example

```json theme={null}
{
  "answer": "React hooks like `useState` and `useReducer` are used for state management...",
  "citations": [
    {
      "source_name": "NPM: react",
      "content": "useState is a Hook that lets you add React state to function components...",
      "score": 0.95,
      "path": "react/index.d.ts"
    },
    {
      "source_name": "NPM: jotai",
      "content": "Primitive and flexible state management for React...",
      "score": 0.89,
      "path": "jotai/package.json"
    }
  ],
  "search_time_ms": 84.5,
  "completion_time_ms": 3200.0,
  "total_time_ms": 3284.5,
  "model_used": "gpt-4o"
}
```

## Notes

* **API key** requests work for core Q\&A; **conversation persistence** uses **JWT** (dashboard) with `/conversations` APIs.
* Model id and latency depend on your deployment’s Azure / LLM configuration.

<CardGroup cols={2}>
  <Card title="Citations" icon="quote-left">
    Answers include source names, paths, and excerpts you can verify in the repo or doc.
  </Card>

  <Card title="Streaming" icon="bolt">
    Use `/chat/stream` for token-by-token UX in custom clients.
  </Card>

  <Card title="Package scope" icon="box">
    Combine indexed sources with on-demand package context where the API supports it.
  </Card>

  <Card title="PDF uploads" icon="paperclip">
    Attach PDFs per conversation for short-lived context (JWT).
  </Card>
</CardGroup>
