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

# Q&A with web search and citations

> Answer questions about current events with the built-in web search tool, and show the sources the answer cites.

Early access
**Gnani Evon v3.5** is now available as an API to early access registrants.

Answer questions that need up-to-date information, and show where each fact came from. The built-in [web search](https://docs.gnani.ai/api/LLM/web-search.md) tool runs the searches for you; your code only adds the tool, then turns the `[n]` citations into links.

## When to use this

* Users ask about things that change: weather, prices, schedules, recent news.
* You need to show sources next to the answer.
* You do not want to run your own search or retrieval pipeline.

***

## Ask a question

```bash cURL theme={null}
curl https://api.vachana.ai/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "X-API-Key-ID: $GNANI_API_KEY" \
  -d '{
    "model": "evon-v3.5",
    "reasoning_effort": "none",
    "tools": [{"type": "web_search"}],
    "messages": [
      {"role": "system", "content": "Answer briefly, in the user'\''s language. Cite every fact from a search result as [n]."},
      {"role": "user", "content": "Will it rain in Mumbai this weekend?"}
    ]
  }'
```

```python Python (OpenAI SDK) theme={null}
import os
from openai import APIStatusError, OpenAI

client = OpenAI(
    base_url="https://api.vachana.ai/v1",
    api_key=os.environ["GNANI_API_KEY"],
)

SYSTEM = "Answer briefly, in the user's language. Cite every fact from a search result as [n]."
question = "Will it rain in Mumbai this weekend?"
messages = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": question}]

try:
    # Retrying does not help when the daily search limit is used up, so turn SDK retries off here.
    completion = client.with_options(max_retries=0).chat.completions.create(
        model="evon-v3.5",
        messages=messages,
        tools=[{"type": "web_search"}],
        reasoning_effort="none",
    )
except APIStatusError as error:
    if error.code not in ("web_search_limit_exceeded", "web_search_unavailable"):
        raise
    print("(Live search is not available right now; answering without it.)")
    completion = client.chat.completions.create(
        model="evon-v3.5",
        messages=messages,
        reasoning_effort="none",
    )

message = completion.choices[0].message
print(message.content)

web_search = getattr(message, "web_search", None) or {}  # not in the SDK's types
if web_search.get("sources"):
    print("\nSources:")
    for source in web_search["sources"]:
        print(f"[{source['id']}] {source['title']} — {source['url']}")
    print(f"\nSearches left today: {web_search.get('remaining_today')}")
```

```javascript JavaScript (OpenAI SDK) theme={null}
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.vachana.ai/v1",
  apiKey: process.env.GNANI_API_KEY,
});

const SYSTEM = "Answer briefly, in the user's language. Cite every fact from a search result as [n].";
const messages = [
  { role: "system", content: SYSTEM },
  { role: "user", content: "Will it rain in Mumbai this weekend?" },
];

let completion;
try {
  // Retrying does not help when the daily search limit is used up, so turn SDK retries off here.
  completion = await client.chat.completions.create(
    { model: "evon-v3.5", messages, tools: [{ type: "web_search" }], reasoning_effort: "none" },
    { maxRetries: 0 },
  );
} catch (error) {
  if (!["web_search_limit_exceeded", "web_search_unavailable"].includes(error?.code)) throw error;
  console.log("(Live search is not available right now; answering without it.)");
  completion = await client.chat.completions.create({ model: "evon-v3.5", messages, reasoning_effort: "none" });
}

const message = completion.choices[0].message;
console.log(message.content);

const sources = message.web_search?.sources ?? [];
if (sources.length) {
  console.log("\nSources:");
  for (const source of sources) console.log(`[${source.id}] ${source.title} — ${source.url}`);
  console.log(`\nSearches left today: ${message.web_search.remaining_today}`);
}
```

```python Python (requests) theme={null}
import os
import requests

URL = "https://api.vachana.ai/v1/chat/completions"
HEADERS = {"X-API-Key-ID": os.environ["GNANI_API_KEY"]}
body = {
    "model": "evon-v3.5",
    "reasoning_effort": "none",
    "tools": [{"type": "web_search"}],
    "messages": [
        {"role": "system", "content": "Answer briefly, in the user's language. Cite every fact from a search result as [n]."},
        {"role": "user", "content": "Will it rain in Mumbai this weekend?"},
    ],
}

response = requests.post(URL, headers=HEADERS, json=body, timeout=120)
code = None
if not response.ok:
    try:
        code = (response.json().get("error") or {}).get("code")
    except ValueError:
        pass
if code in ("web_search_limit_exceeded", "web_search_unavailable"):
    print("(Live search is not available right now; answering without it.)")
    body.pop("tools")
    response = requests.post(URL, headers=HEADERS, json=body, timeout=120)
response.raise_for_status()

message = response.json()["choices"][0]["message"]
print(message["content"])

web_search = message.get("web_search") or {}
if web_search.get("sources"):
    print("\nSources:")
    for source in web_search["sources"]:
        print(f"[{source['id']}] {source['title']} — {source['url']}")
    print(f"\nSearches left today: {web_search.get('remaining_today')}")
```

The output (illustrative, with placeholder sources):

```text theme={null}
Light rain is likely in Mumbai on Saturday, with a drier Sunday [1]. Carry an umbrella if you are out on Saturday afternoon [2].

Sources:
[1] Mumbai weekend forecast — https://example.com/mumbai-forecast
[2] Monsoon update for the Konkan coast — https://example.org/konkan-update

Searches left today: 9
```

***

## How it works

1. You add `{"type": "web_search"}` to `tools`. You do not write a search function.
2. The model decides whether it needs to search. For a question it can answer on its own, it may not search at all.
3. The service runs the searches and gives the results to the model, which writes the answer with numbered citations.
4. `message.web_search` lists the `queries` and the `sources`. Each source's `id` is the number cited as `[id]`.

***

## Options

> [accordion] Turn citations into links
>
> Replace each `[n]` with a Markdown link to the source with that `id`. Unknown numbers are left as they are.
>
> ```python theme={null}
> import re
>
> def link_citations(text: str, sources: list) -> str:
>     urls = {source["id"]: source["url"] for source in sources}
>
>     def to_link(match):
>         number = int(match.group(1))
>         return f"[[{number}]]({urls[number]})" if number in urls else match.group(0)
>
>     return re.sub(r"\[(\d+)\]", to_link, text)
> ```

> [accordion] Show search progress while streaming
>
> With `"stream": true`, chunks with `delta.web_search` report each search before the answer streams in `delta.content`:
>
> ```python theme={null}
> stream = client.chat.completions.create(
>     model="evon-v3.5",
>     messages=messages,
>     tools=[{"type": "web_search"}],
>     reasoning_effort="none",
>     stream=True,
> )
>
> for chunk in stream:
>     if not chunk.choices:
>         continue
>     delta = chunk.choices[0].delta
>     progress = getattr(delta, "web_search", None)  # not in the SDK's types
>     if progress:
>         print(f"\n({progress['status']}: {progress.get('query', '')})")
>     if delta.content:
>         print(delta.content, end="", flush=True)
> ```
>
> See [Web search](https://docs.gnani.ai/api/LLM/web-search.md#streaming) for every `status` value.

> [accordion] Combine with your own functions
>
> You can send your own function tools in the same request. If the model calls one, you get `tool_calls` back and run it as in [Tool calling](https://docs.gnani.ai/api/LLM/tool-calling.md). Do not name your functions `web_search` or `search`.

***

## Gotchas

> [!WARNING]
>
> **Searches are limited per day.** When they are used up, a request with the `web_search` tool is refused with `429 web_search_limit_exceeded` until midnight IST. The scripts above then ask again without the tool. See [Limits](https://docs.gnani.ai/api/LLM/limits.md).

* **A failed search does not fail the request.** The model answers from what it knows and says live search was not available. Check whether `sources` is empty before you show a "Sources" list.
* **Searched answers use more tokens.** `usage` includes the search results the model read, and counts toward your [daily token quota](https://docs.gnani.ai/api/LLM/limits.md).
* **`tool_choice` must be `auto` or `none`** when you send `web_search`. `none` turns search off for the request.
* **Search results are screened** by the [safety filters](https://docs.gnani.ai/api/LLM/safety.md). A result that fails the check is dropped.

***

## Related

> [card] [Web search](https://docs.gnani.ai/api/LLM/web-search.md)
>
> The web search tool, response fields and streaming events.

> [card] [Tool calling](https://docs.gnani.ai/api/LLM/tool-calling.md)
>
> Add your own functions next to web search.

> [card] [Streaming](https://docs.gnani.ai/api/LLM/streaming.md)
>
> Stream the answer as it is written.

> [card] [Limits](https://docs.gnani.ai/api/LLM/limits.md)
>
> Daily search and token limits.


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