# Grounded Search Module

A zero-dependency Python wrapper around Google's **Gemini grounded search** (the
`generateContent` API + `google_search` tool). It returns a synthesized answer
**plus the real web sources** it was grounded on — so any agent can fetch
current, cited facts instead of trusting stale training data.

> Built because a model's knowledge has a cutoff. For anything time-sensitive
> (product launches, traction, market numbers), search first, then write.

## Quick start

```bash
# one-time: store your key OUTSIDE the repo (the vault publishes on git push!)
mkdir -p ~/.config/gemini && printf '%s' 'YOUR_KEY' > ~/.config/gemini/api_key && chmod 600 ~/.config/gemini/api_key

# human-readable
python "tools/search/grounded_search.py" "How is Claude Cowork being adopted vs OpenAI Codex in 2026?"

# machine-readable (for agents / piping)
python "tools/search/grounded_search.py" "Anthropic 2026 revenue run-rate" --json
```

## For agents

Call it from Bash and parse the JSON:

```bash
python "C:/Users/darsh.shah/Documents/Darsh's Vault/tools/search/grounded_search.py" "<query>" --json
```

JSON shape:
```json
{
  "query": "...",
  "model": "gemini-flash-latest",
  "answer": "synthesized, grounded answer text",
  "sources": [{"title": "...", "url": "https://..."}],
  "queries_run": ["the search queries Gemini actually issued"],
  "grounded": true,
  "usage": { "...token counts..." }
}
```

Or import it directly in Python:
```python
from grounded_search import search          # if cwd is tools/search/
res = search("who shipped Claude Cowork and when?", system="Be terse and factual.")
```

## API key (never commit it)

Resolved in this order; first match wins:
1. `$GEMINI_API_KEY`
2. file at `$GEMINI_API_KEY_FILE`
3. `~/.config/gemini/api_key`  ← recommended (outside the publishing repo)

The repo `.gitignore` blocks `.env` and `*api_key*` as defense-in-depth, but the
real safeguard is keeping the key in your home dir, not the vault.

## Flags
- `--json` — raw JSON (default is human-readable answer + numbered sources)
- `--no-grounding` — plain model answer, no web search
- `--model <name>` — default `gemini-flash-latest`
- `--system "<instruction>"` — optional system instruction

## Notes / gotchas
- **Grounding (`google_search`) typically requires billing enabled** on the
  Google Cloud project. A `429 RESOURCE_EXHAUSTED` means the key is valid but
  out of quota — enable billing or wait, then retry. The module already retries
  429/5xx with exponential backoff and honors `Retry-After`.
- Pure stdlib (`urllib`) — no `pip install` needed. Runs on any Python 3.9+.
- Rotate the key if it has ever been pasted into a chat/screenshot.
