ScavioScavio
ProductPricingDocs
Sign InGet Started
  1. Home
  2. Tutorials
  3. How to Ground an AI Agent With a Search API (Working Code)
Tutorial

How to Ground an AI Agent With a Search API (Working Code)

Stop your agent hallucinating stale facts: ground it with live SERP data in Python and JS. Working Scavio code, real returned shape, cost per call.

Get Free API KeyAPI Docs

Grounding means injecting live search results into the prompt before the model answers, so it cites real current data instead of guessing from training. The fix for an agent that confidently quotes last year's prices is three lines: hit a search API, drop the top results into context, tell the model to answer only from them. Below is the working version in Python and JS against Scavio's /api/v1/google endpoint, the exact JSON shape it returns (checked live on 2026-06-26), and the cost math so you know what each grounded answer runs you.

Prerequisites

  • A Scavio API key (50 free credits on signup at scavio.dev)
  • Python 3.9+ or Node 18+
  • Any LLM SDK (OpenAI, Anthropic) for the answer step
  • Basic familiarity with POST requests and environment variables

Walkthrough

Step 1: 1. Call the search API with the user's question

POST the query to /api/v1/google with the Bearer header. Set light_request:false when you want the knowledge graph, related searches, and news blocks alongside organic results. That call bills 2 credits; the light version (organic only) is 1 credit. Verified live: this exact call returned 7 organic results and 8 related searches.

Python
import os, requests

KEY = os.environ['SCAVIO_API_KEY']
resp = requests.post(
    'https://api.scavio.dev/api/v1/google',
    headers={'Authorization': f'Bearer {KEY}', 'Content-Type': 'application/json'},
    json={'query': 'current openai api pricing', 'light_request': False},
).json()
results = resp['results']  # organic results array
print(len(results), 'organic results,', resp['credits_used'], 'credits')

Step 2: 2. Shape the results into grounding context

Each item in results has position, title, url, domain, and content (the snippet). Pull the top 5 into a compact block. Keep it short: more snippets means more tokens, and the top results carry most of the signal.

Python
context = '\n'.join(
    f"[{r['position']}] {r['title']} ({r['domain']})\n{r.get('content','')}"
    for r in results[:5]
)

Step 3: 3. Force the model to answer only from the context

Put the context in the system or user message and instruct the model to answer from it and cite the domain. If the answer isn't in the context, the model should say so rather than fall back to training data. That instruction is what actually stops the hallucination.

Python
prompt = (
    'Answer using ONLY the search results below. '
    'Cite the domain in brackets. If the answer is not present, say so.\n\n'
    f'{context}\n\nQuestion: current openai api pricing'
)
# send `prompt` to your LLM of choice

Step 4: 4. Cache and budget the calls

Grounding every turn is wasteful. Cache results by normalized query for a few minutes to an hour depending on how fast the facts move. Pricing and breaking news need short TTLs; definitions can cache for a day. At 2 credits per full SERP and $0.005/credit, 1,000 grounded answers is about $10 of search, or roughly $4.30/1k on the $30/7,000-credit plan.

Python
# pseudocode: check cache before calling
key = query.strip().lower()
if key in cache and not cache[key].expired:
    results = cache[key].value
else:
    results = call_scavio(query)
    cache[key] = Entry(results, ttl=600)

Python Example

Python
import os, requests

KEY = os.environ['SCAVIO_API_KEY']

def ground(question: str) -> str:
    r = requests.post(
        'https://api.scavio.dev/api/v1/google',
        headers={'Authorization': f'Bearer {KEY}'},
        json={'query': question, 'light_request': False},
    ).json()
    ctx = '\n'.join(
        f"[{x['position']}] {x['title']} ({x['domain']}): {x.get('content','')}"
        for x in r['results'][:5]
    )
    return ctx

print(ground('current openai api pricing'))

JavaScript Example

JavaScript
const KEY = process.env.SCAVIO_API_KEY;

async function ground(question) {
  const r = await fetch('https://api.scavio.dev/api/v1/google', {
    method: 'POST',
    headers: { Authorization: `Bearer ${KEY}`, 'Content-Type': 'application/json' },
    body: JSON.stringify({ query: question, light_request: false }),
  }).then((x) => x.json());
  return r.results
    .slice(0, 5)
    .map((x) => `[${x.position}] ${x.title} (${x.domain}): ${x.content ?? ''}`)
    .join('\n');
}

console.log(await ground('current openai api pricing'));

Expected Output

JSON
A context block of the top 5 organic results, each with position, title, domain, and snippet. The raw response also carries related_searches (8 in our test run), plus knowledge_graph, news_results, and shopping_ads blocks, and reports credits_used: 2 and credits_remaining so you can track spend per call.

Related Tutorials

  • Reddit RSS Feeds vs a Reddit API: What Actually Works in 2026

Frequently Asked Questions

Most developers complete this tutorial in 15 to 30 minutes. You will need a Scavio API key (free tier works) and a working Python or JavaScript environment.

A Scavio API key (50 free credits on signup at scavio.dev). Python 3.9+ or Node 18+. Any LLM SDK (OpenAI, Anthropic) for the answer step. Basic familiarity with POST requests and environment variables. A Scavio API key gives you 50 free credits on signup.

Yes. The free tier includes 50 credits on signup, which is more than enough to complete this tutorial and prototype a working solution.

Scavio has a native LangChain package (langchain-scavio), an MCP server, and a plain REST API that works with any HTTP client. This tutorial uses the raw REST API, but you can adapt to your framework of choice.

Related Resources

Best Of

Best Search API for Code Agents in 2026

Read more
Use Case

Local LLM Search Grounding via API

Read more
Best Of

Best Search APIs for Open-Source LLM Grounding in 2026

Read more
Use Case

Ground Cursor Agent with Live Web Search

Read more
Solution

Ground LLM Responses with Real-Time Search Data

Read more
Glossary

LLM Grounding

Read more

Start Building

Stop your agent hallucinating stale facts: ground it with live SERP data in Python and JS. Working Scavio code, real returned shape, cost per call.

Get Free API KeyRead the Docs
ScavioScavio

Real-time search API for AI agents. Search every platform, not just Google.

Product

  • Features
  • Pricing
  • Dashboard
  • Affiliates

Developers

  • Documentation
  • API Reference
  • Quickstart
  • MCP Integration
  • Python SDK

Alternatives

  • Tavily Alternative
  • SerpAPI Alternative
  • Firecrawl Alternative
  • Exa Alternative

Tools

  • JSON Formatter
  • cURL to Code
  • Token Counter
  • All Tools

© 2026 Scavio. All rights reserved.

Featured on TAAFT
Terms of ServicePrivacy Policy