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

# Query API

> Natural-language search across Kalshi, Polymarket, traditional markets, X context, and SimpleFunctions content.

Use Query API when a user or agent asks a natural-language market question.

<CodeGroup>
  ```bash curl theme={null}
  curl "https://simplefunctions.dev/api/public/query?q=Fed%20rate%20cut&limit=3"
  ```

  ```bash CLI theme={null}
  sf query "Fed rate cut" --json --limit 3
  ```

  ```ts TypeScript theme={null}
  const res = await fetch(
    `https://simplefunctions.dev/api/public/query?q=${encodeURIComponent('Fed rate cut')}&limit=3`,
    { headers: { Authorization: `Bearer ${process.env.SF_API_KEY}` } }
  )
  const data = await res.json()
  ```

  ```python Python theme={null}
  import os, requests
  res = requests.get(
      'https://simplefunctions.dev/api/public/query',
      params={'q': 'Fed rate cut', 'limit': 3},
      headers={'Authorization': f"Bearer {os.environ['SF_API_KEY']}"}
  )
  data = res.json()
  ```
</CodeGroup>

## Endpoint

```http theme={null}
GET /api/public/query
```

**Auth:** optional. Anonymous calls work for `mode=full` with the cheap model. Authenticated calls (`Authorization: Bearer sf_live_...`) unlock the `model` parameter and raise the rate limit.

**Rate limits:**

* Anonymous: **10 requests / minute / IP**
* Authenticated: **60 requests / minute / key**
* Cached queries (recent identical `q`+params) bypass the rate-limit counter and return immediately.

### Query parameters

**Required**

| Parameter | Type   | Notes                                                                      |
| --------- | ------ | -------------------------------------------------------------------------- |
| `q`       | string | Natural-language event question or topic. Minimum 2 characters after trim. |

**Optional**

| Parameter     | Type           | Default  | Values                                                | Notes                                                                                                                                                                |
| ------------- | -------------- | -------- | ----------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `mode`        | string         | `full`   | `full`, `raw`                                         | `full` uses LLM-expanded recall and adds an LLM-synthesised `answer`. `raw` uses deterministic retrieval and skips both query-understanding and synthesis LLM calls. |
| `sources`     | comma list     | all      | `kalshi`, `polymarket`, `x`, `content`, `traditional` | Restrict which source clusters appear in the response.                                                                                                               |
| `limit`       | int            | `10`     | `1` – `20`                                            | Max markets returned per venue. Values > 20 are clamped to 20.                                                                                                       |
| `model`       | string         | `cheap`  | `cheap`, `medium`, `heavy`                            | Synthesis model tier. **Requires auth** for any value other than `cheap`.                                                                                            |
| `depth`       | boolean string | `false`  | `true`                                                | Enrich the top Kalshi markets with orderbook depth fields. Adds latency.                                                                                             |
| `nextActions` | string         | included | `off`                                                 | Omit the `nextActions` block (inspect / related URLs) when set to `off`.                                                                                             |

## Examples

Full answer:

```bash theme={null}
curl "https://simplefunctions.dev/api/public/query?q=Fed%20rate%20cut&limit=3"
```

Fast deterministic retrieval:

```bash theme={null}
curl "https://simplefunctions.dev/api/public/query?q=Fed%20rate%20cut&mode=raw&limit=5"
```

Only prediction venues:

```bash theme={null}
curl "https://simplefunctions.dev/api/public/query?q=US%20recession&sources=kalshi,polymarket&limit=5"
```

Include orderbook enrichment:

```bash theme={null}
curl "https://simplefunctions.dev/api/public/query?q=Fed%20rate%20cut&depth=true"
```

## Response

<Expandable title="Full response shape">
  ```json theme={null}
  {
    "query": "Fed rate cut",
    "answer": "Prediction markets are pricing...",
    "keyFactors": [],
    "kalshi": [
      {
        "title": "Will the Federal Reserve cut rates before 2027?",
        "ticker": "KXRATECUT-26DEC31",
        "price": 49,
        "volume": 102746.28,
        "pageUrl": "https://simplefunctions.dev/markets/KXRATECUT-26DEC31",
        "apiUrl": "https://simplefunctions.dev/api/public/market/KXRATECUT-26DEC31",
        "inspectUrl": "https://simplefunctions.dev/api/agent/inspect/KXRATECUT-26DEC31"
      }
    ],
    "polymarket": [],
    "traditional": [],
    "x": [],
    "content": [],
    "theses": [],
    "legislation": [],
    "meta": {
      "sources": ["kalshi", "polymarket", "traditional"],
      "mode": "full",
      "latencyMs": 0
    },
    "nextActions": {
      "inspect": [],
      "related": []
    }
  }
  ```

  Fields appear only when the corresponding source has results. `nextActions` is absolute-URL'd to `https://simplefunctions.dev/...` so an agent can follow links directly.
</Expandable>

## Errors

| Status | Body                                                                                                       | Cause                                                                                                      |
| ------ | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| `400`  | `{ "error": "Query parameter \"q\" is required (min 2 chars)" }`                                           | Missing `q` or fewer than 2 chars.                                                                         |
| `401`  | `{ "error": "Custom model tier requires a valid API key. Add header: Authorization: Bearer sf_live_xxx" }` | `model=medium` or `model=heavy` without auth.                                                              |
| `429`  | `{ "error": "Rate limit exceeded. Try again in a minute." }`                                               | Hit per-minute limit (10 anon / 60 authed).                                                                |
| `500`  | `{ "error": "..." }`                                                                                       | Upstream model or DB failure. Retry with `mode=raw` to bypass query-understanding and synthesis LLM calls. |

## Use in an agent

```bash theme={null}
curl "https://simplefunctions.dev/api/public/query?q=Fed%20rate%20cut&mode=raw&limit=3"
curl "https://simplefunctions.dev/api/agent/inspect/KXRATECUT-26DEC31"
curl "https://simplefunctions.dev/api/public/screen?keyword=Fed%20rate%20cut"
```

Use query to find candidate markets. Use inspect before acting on one ticker. Use screen when the agent needs a broader ranked market list.
