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

# Research Examples

> Examples for filtering, continuations, and saved runs

## Receive the Final Report

Read the event stream and print `final_result.result` once it arrives. This is the authoritative report.
`stream: true` additionally emits provisional text deltas; concatenating all of them mixes partial and final drafts.
For a live text display, track each delta’s `phase` and `checkpoint` and handle `synthesis_discarded`.

```python Python theme={null}
import json
import os
import sys
import httpx

payload = {"query": "What changed in battery recycling this year?", "mode": "deep"}

received_report = False

with httpx.stream(
    "POST",
    "https://agent.tinyfish.ai/v1/automation/run-research",
    headers={"X-API-Key": os.environ["TINYFISH_API_KEY"]},
    json=payload,
    timeout=2700,
) as response:
    response.raise_for_status()
    for line in response.iter_lines():
        if not line.startswith("data:"):
            continue
        event = json.loads(line[5:].strip())
        if event["event"] == "created":
            print(f"Run: {event['research_run_id']}", file=sys.stderr)
        elif event["event"] == "final_result":
            print(event["result"], flush=True)
            received_report = True
            if event.get("termination_reason") == "synthesis_failed":
                print("Report contains interim findings.", file=sys.stderr)
        elif event["event"] == "error":
            raise RuntimeError(event.get("message", "Research failed"))
        elif event["event"] == "done":
            break

if not received_report:
    raise RuntimeError("No report received; retrieve the run before retrying.")
```

```typescript TypeScript theme={null}
import { TinyFish } from "@tiny-fish/sdk";

const client = new TinyFish();
const stream = await client.research.stream({
  query: "What changed in battery recycling this year?",
  mode: "deep",
});
let receivedReport = false;
for await (const event of stream) {
  if (event.event === "created") console.error("Run:", event.research_run_id);
  else if (event.event === "final_result") {
    console.log(event.result);
    receivedReport = true;
    if (event.termination_reason === "synthesis_failed") console.error("Report contains interim findings.");
  } else if (event.event === "error") throw new Error(event.message);
}
if (!receivedReport) throw new Error("No report received; retrieve the run before retrying.");
```

## Reconnect to a Run

`events()` attaches to a run that is already running, replays its saved events, and follows it until `done`. Pass the
last event id you saw to resume without replaying. Stopping the loop detaches without cancelling the run.

```python Python theme={null}
from tinyfish import TinyFish

client = TinyFish()
with client.research.events(research_run_id) as stream:
    for event in stream:
        print(event.event)
```

```typescript TypeScript theme={null}
import { TinyFish } from "@tiny-fish/sdk";

const client = new TinyFish();
const stream = await client.research.events(researchRunId);
for await (const event of stream) {
  console.log(event.event);
}
```

## Restrict Research to Trusted Domains

Use `include` to prioritize domains while retaining other results. Use `exclusive` to restrict results to the allowlist.
Blocked domains are always removed. Each list accepts at most 150 entries.

```json theme={null}
{
  "query": "Compare current public-health recommendations",
  "domain_filter": {
    "mode": "exclusive",
    "domains": ["who.int", "cdc.gov"],
    "block": []
  }
}
```

## Continue Research

Each follow-up starts a new run with a new `research_run_id`. Use the `session_id` from the SSE `session` event
to continue that conversation. Set the mode, domain filter, and output language explicitly on the new request
when you need them; do not assume the previous request settings are inherited.

```json theme={null}
{
  "query": "Which conclusion has the strongest primary-source support?",
  "mode": "deep",
  "session_id": "019..."
}
```

If you only have a run ID, including after an async start, wait for that run to complete and pass it as
`prior_run_id` to carry its report and source context into a new run. Do not send both continuation fields.

```json theme={null}
{
  "query": "Update this report with developments from the last week",
  "mode": "deep",
  "prior_run_id": "019..."
}
```

Completed follow-ups use the same mode-based pricing as other runs.
See [follow-up billing](https://docs.tinyfish.ai/tinyresearch/reference.md#limits).

## Retrieve Saved Runs

```python Python theme={null}
from tinyfish import TinyFish

client = TinyFish()
page = client.research.list(status="COMPLETED", limit=20)
for run in page.data:
    print(run.research_run_id, run.query)

run = client.research.get(research_run_id)
if run.deep_result:
    print(run.status, run.deep_result.result)
```

```typescript TypeScript theme={null}
import { TinyFish } from "@tiny-fish/sdk";

const client = new TinyFish();
const page = await client.research.list({
  status: "COMPLETED",
  limit: 20,
});
for (const run of page.data) {
  console.log(run.research_run_id, run.query);
}

const run = await client.research.get(researchRunId);
console.log(run.status, run.deep_result?.result);
```

```bash cURL theme={null}
curl "https://agent.tinyfish.ai/v1/research-run?status=COMPLETED&limit=20" \
  -H "X-API-Key: $TINYFISH_API_KEY"

curl "https://agent.tinyfish.ai/v1/research-run/$RESEARCH_RUN_ID" \
  -H "X-API-Key: $TINYFISH_API_KEY"
```

Pass `page.pagination.next_cursor` as `cursor` to get the next page.

## Cancel a Running Run

```python Python theme={null}
result = client.research.cancel(research_run_id)
print(result.status, result.cancelled)
```

```typescript TypeScript theme={null}
const result = await client.research.cancel(researchRunId);
console.log(result.status, result.cancelled);
```

```bash cURL theme={null}
curl -X POST \
  "https://agent.tinyfish.ai/v1/research-run/$RESEARCH_RUN_ID/cancel" \
  -H "X-API-Key: $TINYFISH_API_KEY"
```

```json theme={null}
{
  "research_run_id": "019...",
  "status": "CANCELLED",
  "cancelled": true
}
```

A run that already finished returns its status with `cancelled: false`.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.