EN ▾
Get API key

LLM Web Search API: Ground Answers With Live Results

An LLM web search API sounds like one product, but it is two pieces: a search service that returns results, and a model that writes the answer. Our API is the second piece. It does not browse, so you connect it to search yourself.

Magnifying lens filtering document tiles into an ordered column, representing search results grounding a language model

Summary

  1. This API is text only and does not browse the web; you supply search results as context.

  2. Two patterns work: fetch results first and paste them into the prompt, or let the model call a search tool.

  3. Five snippets of about 300 tokens each add roughly $0.0002 to a request at $0.15 per 1M input tokens.

  4. Tool calling and JSON mode are supported, so the loop is short.

What "search" means for a language model

A language model only knows what was in its training data and what you put in the prompt. It cannot open a page on its own. When a product says it has web search, there is always a loop around the model: something turns the question into a search query, calls a search service, reads the results, and hands the useful text back to the model to write the answer.

That loop is called grounding, or retrieval-augmented generation when the sources are documents you control. Grounding does two things for you. It brings in facts newer than the model's training, and it lets the model quote a source instead of guessing.

Our endpoint is a hosted, OpenAI-compatible text API with a single model, model ID uncensored. It has no built-in browsing tool. What it has is a 100,000-token context window, tool calling and JSON mode, which is everything you need to build the loop yourself.

Choosing a search service

Any service that returns results as JSON will do. Common choices are a general web search API, a news search API, or a search service built for AI agents that returns cleaned page text. Compare them on these points and check each provider's current pricing and terms:

  • What comes back. Titles and short snippets are cheap and quick. Full page text costs more tokens but gives better answers.
  • Freshness. News and price questions need recent indexing.
  • Rate limits and cost per query. Your search bill is separate from your model bill and can be the larger of the two.
  • Terms of use. Some providers restrict storing or redistributing results.

Keep the search call behind one small function so you can swap providers without touching the rest of your code.

Pattern 1: search first, then answer

This is the simplest approach and the right default. Your code runs the search, formats the top results, and sends them with the question in one request.

import os
import requests
from openai import OpenAI

client = OpenAI(
    base_url="https://api.localnsfwllm.com/v1",
    api_key=os.environ["LLM_API_KEY"],
)

def search_web(query, n=5):
    # Replace with your search provider. Return a list of dicts.
    r = requests.get(
        os.environ["SEARCH_URL"],
        params={"q": query, "count": n},
        headers={"Authorization": "Bearer " + os.environ["SEARCH_KEY"]},
        timeout=15,
    )
    r.raise_for_status()
    return [
        {"title": x["title"], "url": x["url"], "snippet": x["snippet"]}
        for x in r.json()["results"][:n]
    ]

def answer(question):
    results = search_web(question)
    context = "\n\n".join(
        f"[{i+1}] {x['title']} ({x['url']})\n{x['snippet']}"
        for i, x in enumerate(results)
    )
    messages = [
        {"role": "system", "content": "Answer using only the numbered sources. Cite them like [1]. If the sources do not contain the answer, say so."},
        {"role": "user", "content": f"Sources:\n{context}\n\nQuestion: {question}"},
    ]
    resp = client.chat.completions.create(
        model="uncensored", messages=messages, temperature=0.3
    )
    return resp.choices[0].message.content

print(answer("What changed in the latest Python release?"))

The system message does the heavy lifting. Telling the model to use only the numbered sources, and to say so when they are not enough, cuts down on invented details. Low temperature helps for the same reason.

Pattern 2: let the model call a search tool

When some questions need a search and others do not, give the model a tool and let it decide. The API supports tools, tool_choice and results sent back as role: "tool" messages.

import json

tools = [{
    "type": "function",
    "function": {
        "name": "search_web",
        "description": "Search the web for current information.",
        "parameters": {
            "type": "object",
            "properties": {"query": {"type": "string"}},
            "required": ["query"],
        },
    },
}]

messages = [
    {"role": "system", "content": "Use search_web for anything recent or uncertain. Cite sources by URL."},
    {"role": "user", "content": "Who won the most recent chess world championship match?"},
]

for _ in range(4):  # cap the number of tool rounds
    resp = client.chat.completions.create(
        model="uncensored", messages=messages, tools=tools
    )
    msg = resp.choices[0].message
    if not msg.tool_calls:
        print(msg.content)
        break
    messages.append(msg)
    for call in msg.tool_calls:
        args = json.loads(call.function.arguments)
        found = search_web(args["query"])
        messages.append({
            "role": "tool",
            "tool_call_id": call.id,
            "content": json.dumps(found),
        })

Two details matter. Cap the loop, as above, so a confused model cannot call search forever. And parse arguments defensively, since a model can return malformed JSON now and then; on a parse error, send the error text back as the tool result and let it retry.

Keeping the context clean and cheap

Grounding is only as good as what you paste in. A few habits that pay off:

  • Trim results. Five snippets are usually better than ten. Strip navigation text and duplicate sources before sending.
  • Put sources before the question. The model reads the question last, which keeps it in focus.
  • Keep the system rule short and firm. One sentence about citing and admitting gaps is enough.
  • Fetch full pages only when snippets fail. A page can be thousands of tokens; extract the relevant paragraphs first.
  • Treat page text as data. A web page can contain text that looks like an instruction. Tell the model that sources are untrusted material to quote from, never commands to follow.

Failure modes and how to handle them

Search returns nothing useful

Send the model an empty source list along with the same instruction to admit gaps. It will usually say it could not find an answer, which is better than a confident guess. You can also let it rewrite the query once and search again.

Stale or conflicting sources

Ask the model to prefer the most recent source and to name the disagreement when two sources conflict. Pass the publication date in each source line when your search service provides it.

Rate limits

A full key allows 8 concurrent requests and 300 requests per minute; a trial key allows 2 and 60. A tool loop makes several model calls per user question, so budget for that multiplier. If you get HTTP 429, read the error code: rate_limited means too many requests per minute, concurrency means too many at once. On temporary overload the response carries Retry-After: 5, so wait that long and retry.

Repeated questions

Cache search results by normalized query for a few minutes. Popular questions then cost one search call instead of many, and answers stay consistent.

What it costs per question

Search adds input tokens, so it is worth doing the arithmetic. Prices on this API are $0.15 per 1M input tokens and $0.50 per 1M output tokens.

Say each question carries 5 snippets of about 300 tokens (1,500), a system message and question of 500 tokens, and the answer runs 400 tokens.

  • Input: 2,000 tokens x $0.15 per 1M = $0.0003
  • Output: 400 tokens x $0.50 per 1M = $0.0002
  • Total: $0.0005 per question, so $0.50 per 1,000 questions

The model side is almost a rounding error. The search provider's per-query fee will likely cost more than the tokens, so check it before you plan a budget. Full rates and top-up bonuses are on the pricing page, and the request format is documented in the docs. If you want to test the loop first, new accounts can claim $0.50 of trial credit on the API key page, which is about 1,000 questions of this size.

Failed or refused requests are not charged. If you build chat features around this, the common chatbot mistakes article lists other pitfalls worth avoiding.

Common questions

Does this API have built-in web search?

No. It is a text-only API with one model and no browsing tool. You add search by calling a search service yourself and passing the results to the model as context or as a tool result.

Which pattern should I start with?

Start with search first, then answer. It is easier to debug and cheaper because you control exactly what goes into the prompt. Move to tool calling when only some questions need search.

Will the model make up sources?

It can if you do not constrain it. Number your sources, ask it to cite only those numbers, and instruct it to say when the sources do not answer the question.

How many search results should I send?

Three to five good snippets usually beat ten noisy ones. The 100,000-token context window leaves room for more, but extra material tends to dilute the answer and raises cost.

Get your API key

Register, copy the key, update your base URL. That is all.

Start with free credit

Email and password, key displayed immediately.