Metadata-Version: 2.4
Name: serqo
Version: 0.1.1
Summary: Official Python client for the Serqo Search API
Author: Serqo
License-Expression: MIT
Project-URL: Homepage, https://serqo.io
Project-URL: Documentation, https://github.com/serqo-io/serqo-python#readme
Project-URL: Repository, https://github.com/serqo-io/serqo-python
Project-URL: Issues, https://github.com/serqo-io/serqo-python/issues
Keywords: serp,serp-api,search-api,google-search,bing-search,langchain,ai-agents,autocomplete
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

# Serqo Python SDK

Official Python client for the [Serqo Search API](https://serqo.io). Retrieve clean, structured Google & Bing SERP results in JSON with zero proxy setup. 

Get started with **100 free requests** on [serqo.io](https://serqo.io).

[![PyPI](https://img.shields.io/pypi/v/serqo.svg)](https://pypi.org/project/serqo/)
[![Python](https://img.shields.io/pypi/pyversions/serqo.svg)](https://pypi.org/project/serqo/)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)

---

## Highlights

- **Standard Library Only**: Zero external dependencies. Uses Python's built-in `urllib` and `json`.
- **Clean Structured JSON**: Returns normalized titles, organic snippets, answer boxes, sitelinks, and rich SERP features without HTML parsing overhead.
- **Drop-in SerpApi Alternative**: Sub-second latency, transparent pay-as-you-go pricing from $0.001/query, and no mandatory monthly subscriptions.
- **AI Agent Ready**: Ultra-compact token footprints for LangChain, LlamaIndex, and CrewAI pipelines.
- **Multi-Round Autocomplete**: Real-time search suggestions with A-Z alphabet soup and question keyword expansion.

---

## Installation

```sh
pip install serqo
```

---

## Quick Start

```python
import os
from serqo import Serqo

# 1. Initialize client with your API key from https://serqo.io/console/keys
client = Serqo(api_key=os.environ["SERP_API_KEY"])

# 2. Run a Google web search
response = client.search({
    "q": "open source ai agents",
    "engine": "google",
    "type": "web",
    "gl": "us",
    "hl": "en",
})

# 3. Read normalized organic results
for item in response["data"]["results"][:5]:
    print(f"- {item['title']}: {item['link']}")
```

---

## Real-Time Search Suggestions & Keyword Mining

Serqo provides programmatic access to Google's real-time autocomplete suggestions, including A-Z alphabet soup and question keyword discovery:

```python
# Direct completion (instant ~200ms suggestions)
suggest = client.autocomplete({"q": "langchain", "strategy": "normal"})
print(suggest["data"]["suggestions"])

# 26-Letter A-Z Alphabet Soup Expansion (dispatches 27 parallel sub-queries)
alphabet = client.autocomplete({
    "q": "nextjs",
    "strategy": "alphabet",
    "gl": "us",
    "hl": "en"
})
print(f"Discovered {alphabet['meta']['totalKeywords']} keywords across 26 letters:")
for item in alphabet["data"]["suggestions"][:10]:
    print(f"- [{item['group']}] {item['keyword']}")
```

Supported expansion strategies: `normal`, `alphabet`, `questions`, `prepositions`, `intent`, `seo_matrix`, `deep`.

---

## Using as a Tool with LangChain & AI Agents

Serqo's lightweight JSON payloads prevent LLM context-window bloating. Here is a production-ready LangChain `BaseTool` example:

```python
from typing import Type
from pydantic import BaseModel, Field
from langchain_core.tools import BaseTool
from serqo import Serqo

class SearchInput(BaseModel):
    query: str = Field(description="Search terms to look up on Google")

class SerqoSearchTool(BaseTool):
    name: str = "google_search"
    description: str = "Search Google for current news, technical documentation, or real-time facts."
    args_schema: Type[BaseModel] = SearchInput
    client: Serqo = None

    def __init__(self, api_key: str):
        super().__init__()
        self.client = Serqo(api_key=api_key)

    def _run(self, query: str) -> str:
        try:
            res = self.client.search({"q": query, "engine": "google", "type": "web"})
            results = res.get("data", {}).get("results", [])[:3]
            formatted = [f"[{r.get('title')}]({r.get('link')}): {r.get('snippet')}" for r in results]
            return "\n\n".join(formatted) or "No search results found."
        except Exception as e:
            return f"Search error: {str(e)}"

# Ready to use in any LangChain Agent or ReAct loop!
tool = SerqoSearchTool(api_key=os.environ["SERP_API_KEY"])
print(tool.run("what is serqo search api"))
```

---

## Pagination & Advanced Parameters

```python
# First page
page1 = client.search({"q": "best coffee", "engine": "google", "type": "web"})

# Next page using nextStart token
if page1["data"]["pagination"].get("hasNext"):
    next_start = page1["data"]["pagination"]["nextStart"]
    page2 = client.search({
        "q": "best coffee",
        "engine": "google",
        "type": "web",
        "start": next_start,
    })
```

---

## Idempotency & Safe Retries

To retry network timeouts without double-charging your account balance, pass a unique `idempotency_key`:

```python
import uuid

key = str(uuid.uuid4())
response = client.search(
    {"q": "financial reports", "engine": "google", "type": "news"},
    idempotency_key=key,
)
```

Within 24 hours, sending the same `idempotency_key` returns the cached original result with zero additional charge.

---

## Error Handling

API errors raise `SerqoError`, containing HTTP status and machine-readable error codes:

```python
from serqo import Serqo, SerqoError

try:
    res = client.search({"q": "test", "engine": "google", "type": "web"})
except SerqoError as err:
    print(f"Status: {err.status}, Code: {err.code}, RequestId: {err.request_id}")
    if err.retryable:
        print(f"Retry allowed after {err.retry_after_ms}ms")
```

Common status codes:
- `401 UNAUTHORIZED`: Missing or invalid API key.
- `402 INSUFFICIENT_CREDITS`: Account balance exhausted. Top up on [serqo.io/pricing](https://serqo.io/pricing).
- `422 INVALID_PARAM`: Missing required parameter or invalid option.
- `429 QUOTA_EXCEEDED`: Concurrency rate limit exceeded.

---

## Documentation & Support

- **Web Documentation**: [https://serqo.io/docs](https://serqo.io/docs)
- **Interactive Playground**: [https://serqo.io/console/playground](https://serqo.io/console/playground)
- **Get API Key (100 Free Credits)**: [https://serqo.io](https://serqo.io)
- **License**: MIT
