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

# Search memories

> POST /v1/memories/search — retrieve the most relevant memories for a natural-language query.

## `POST /v1/memories/search`

Return the most relevant memories for a query string. Results are ranked by a multi-signal fusion score combining semantic similarity, importance, recency, and an optional task context hint.

This endpoint is synchronous — it blocks until ranked results are ready.

**Required scope:** `memory:read`

***

## Request

```bash theme={null}
curl -X POST https://api.thrindex.com/v1/memories/search \
  -H "Authorization: Bearer th_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "query": "how does the user want to be contacted",
    "agent_id": "support-agent",
    "user_id": "user-42"
  }'
```

### Body

| Field          | Type    | Required | Default        | Description                                                                                                                                               |
| -------------- | ------- | -------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `query`        | string  | yes      | —              | Natural language search query. Maximum 2048 characters.                                                                                                   |
| `agent_id`     | string  | yes      | —              | Limits results to memories belonging to this agent. Max 256 characters. Charset: `[A-Za-z0-9._:-]`                                                        |
| `user_id`      | string  | yes      | —              | Limits results to memories belonging to this user. Same constraints as `agent_id`.                                                                        |
| `k`            | integer | no       | `10`           | Maximum number of results to return. Range: `1`–`100`.                                                                                                    |
| `task_context` | string  | no       | —              | A short description of the agent's current task. Used by the fusion ranker to boost task-relevant memories. Example: `"composing a weekly digest email"`. |
| `level`        | integer | no       | — (all levels) | Filter results to a specific memory level: `0` (raw facts), `1` (abstracted patterns). Omit to search all levels.                                         |

<Note>
  `org_id` is always derived from the API key. It is never accepted in the request body.
</Note>

Maximum request body size: 8 KB.

***

## Response

### `200 OK`

```json theme={null}
{
  "results": [
    {
      "id": "3f2e1d0c-1234-5678-abcd-ef0123456789",
      "content": "User prefers weekly email digests over push notifications.",
      "agent_id": "support-agent",
      "user_id": "user-42",
      "level": 0,
      "status": "active",
      "importance": 0.82,
      "confidence": 1.0,
      "score": 0.934,
      "created_at": "2026-05-24T17:00:00.000Z"
    }
  ],
  "latency_ms": 42,
  "cache_hit": false
}
```

### Top-level fields

| Field        | Type    | Description                                                                                                            |
| ------------ | ------- | ---------------------------------------------------------------------------------------------------------------------- |
| `results`    | array   | Ranked list of matching memories, ordered by descending `score`.                                                       |
| `latency_ms` | integer | Server-side processing time in milliseconds.                                                                           |
| `cache_hit`  | boolean | `true` if the result was served from the hot cache (identical query for the same org/agent/user within the cache TTL). |

### Result object fields

| Field        | Type            | Description                                                                                                                      |
| ------------ | --------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `id`         | string (UUID)   | Memory identifier                                                                                                                |
| `content`    | string          | The memory text                                                                                                                  |
| `agent_id`   | string          | Agent that owns the memory                                                                                                       |
| `user_id`    | string          | User the memory belongs to                                                                                                       |
| `level`      | integer         | `0` = raw, `1` = abstraction                                                                                                     |
| `status`     | string          | `"active"` — deprecated memories are never returned in search results                                                            |
| `importance` | float (0–1)     | Importance score assigned by the cognition worker                                                                                |
| `confidence` | float (0–1)     | Confidence score (provided on write, defaults to `1.0`)                                                                          |
| `score`      | float           | Multi-signal fusion score. Use this to compare results **within a single response** — it is not stable across different queries. |
| `created_at` | ISO 8601 string | When the memory was created                                                                                                      |

***

## Examples

### Basic search

```bash theme={null}
curl -X POST https://api.thrindex.com/v1/memories/search \
  -H "Authorization: Bearer th_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "query": "contact preferences",
    "agent_id": "support-agent",
    "user_id": "user-42"
  }'
```

### With task context and custom result count

```bash theme={null}
curl -X POST https://api.thrindex.com/v1/memories/search \
  -H "Authorization: Bearer th_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "query": "what does the user want",
    "agent_id": "support-agent",
    "user_id": "user-42",
    "k": 5,
    "task_context": "composing a weekly digest email"
  }'
```

### Filter to abstracted memories only

```bash theme={null}
curl -X POST https://api.thrindex.com/v1/memories/search \
  -H "Authorization: Bearer th_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "query": "user preferences and patterns",
    "agent_id": "support-agent",
    "user_id": "user-42",
    "level": 1
  }'
```

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from thrindex import Thrindex

    client = Thrindex(api_key="th_live_...")

    results = client.search(
        query="how does the user want to be contacted",
        agent_id="support-agent",
        user_id="user-42",
        k=5,
        task_context="composing a notification preferences summary",
    )

    for hit in results:
        print(f"[{hit.score:.3f}] {hit.content}")

    # Inject into your system prompt
    memory_context = "\n".join(f"- {hit.content}" for hit in results)
    system_prompt = f"User context:\n{memory_context}\n\nAnswer the user's question."
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    import { ThrindexClient } from 'thrindex';

    const client = new ThrindexClient({ apiKey: 'th_live_...' });

    const results = await client.search({
      query: 'how does the user want to be contacted',
      agentId: 'support-agent',
      userId: 'user-42',
      k: 5,
      taskContext: 'composing a notification preferences summary',
    });

    for (const hit of results) {
      console.log(`[${hit.score.toFixed(3)}] ${hit.content}`);
    }

    // Inject into your system prompt
    const memoryContext = results.map(h => `- ${h.content}`).join('\n');
    const systemPrompt = `User context:\n${memoryContext}\n\nAnswer the user's question.`;
    ```
  </Tab>
</Tabs>

***

## Errors

| Status | Code                | Description                                                                                              |
| ------ | ------------------- | -------------------------------------------------------------------------------------------------------- |
| `400`  | `validation_error`  | Missing `query`, invalid `agent_id`/`user_id` charset, `k` out of range `1`–`100`, unknown field in body |
| `401`  | `unauthorized`      | Missing or invalid API key                                                                               |
| `401`  | `forbidden`         | API key lacks `memory:read` scope                                                                        |
| `413`  | `payload_too_large` | Request body exceeds 8 KB                                                                                |
| `429`  | `rate_limited`      | Rate limit exceeded                                                                                      |
| `500`  | `internal_error`    | Server error                                                                                             |
