Serpex Haystack Integration
Serpex integration for Haystack - bringing web search to your Haystack pipelines.
Overview
Serpex is the web search API and extract API for AI agents: ranked web results, optionally with page content as markdown. This integration allows you to seamlessly incorporate web search results into your Haystack RAG (Retrieval-Augmented Generation) pipelines and AI applications.
Key Features
- 🔍 Web Search: nothing to configure, every search is routed automatically; optional page content as markdown
- ⚡ Reliable: Automatic retries with exponential backoff
- 🎯 Rich Results: Get organic search results with titles, snippets, and URLs
- 🕒 Date filters:
after:YYYY-MM-DD/before:YYYY-MM-DDin the query (alsosite:and-site:) - 🔒 Type-Safe: Fully typed with comprehensive type hints
- 📝 Haystack Native: Seamless integration with Haystack 2.0+ components
Installation
pip install serpex-haystack
Quick Start
Get Your API Key
Sign up at Serpex.dev to get your API key.
Basic Usage
from haystack import Pipeline
from haystack.components.builders import PromptBuilder
from haystack.components.generators import OpenAIGenerator
from haystack.utils import Secret
from haystack_integrations.components.websearch.serpex import SerpexWebSearch
# Create a web search component
web_search = SerpexWebSearch(
api_key=Secret.from_env_var("SERPEX_API_KEY"),
)
# Use it standalone
results = web_search.run(query="What is Haystack AI?")
for doc in results["documents"]:
print(f"Title: {doc.meta['title']}")
print(f"URL: {doc.meta['url']}")
print(f"Snippet: {doc.content}\n")
RAG Pipeline Example
from haystack import Pipeline
from haystack.components.builders import PromptBuilder
from haystack.components.generators import OpenAIGenerator
from haystack.utils import Secret
from haystack_integrations.components.websearch.serpex import SerpexWebSearch
# Create a simple RAG pipeline with web search
prompt_template = """
Based on the following search results, answer the question.
Search Results:
{% for doc in documents %}
- {{ doc.meta.title }}: {{ doc.content }}
Source: {{ doc.meta.url }}
{% endfor %}
Question: {{ query }}
Answer:
"""
pipe = Pipeline()
pipe.add_component("search", SerpexWebSearch(api_key=Secret.from_env_var("SERPEX_API_KEY")))
pipe.add_component("prompt", PromptBuilder(template=prompt_template))
pipe.add_component("llm", OpenAIGenerator(api_key=Secret.from_env_var("OPENAI_API_KEY")))
pipe.connect("search.documents", "prompt.documents")
pipe.connect("prompt", "llm")
# Run the pipeline
result = pipe.run({
"search": {"query": "Latest developments in AI agents"},
"prompt": {"query": "Latest developments in AI agents"}
})
print(result["llm"]["replies"][0])
Advanced Features
Page content
# Each Document carries the page content (markdown) for the top 5 results;
# the snippet moves to meta["snippet"].
web_search = SerpexWebSearch(include_content=True, content_results=5)
results = web_search.run(query="AI news")
# Or per call
results = web_search.run(query="Python tutorials", include_content=True)
Best-effort: a page that can't be extracted keeps the snippet as content and
carries meta["content_error"].
Deprecated parameters
Every search is routed automatically, so there is nothing to select. engine (in
__init__ and run()) and time_range (in run()) are deprecated and ignored
by the Serpex API. They are still accepted so existing code keeps running, emit a
DeprecationWarning, and are not sent. Pipelines saved with an older version
still load: their engine value is dropped. Removed in 3.0. For a date filter put
after:YYYY-MM-DD / before:YYYY-MM-DD in the query instead of time_range.
Timeouts and retries
web_search = SerpexWebSearch(
api_key=Secret.from_env_var("SERPEX_API_KEY"),
timeout=60.0, # Request timeout in seconds
retry_attempts=3 # Total attempts on a transport error, 429 or 5xx
)
The default timeout is 60 s (100 s with include_content), longer than the
server's own budget, so a slow search isn't abandoned after the server has billed
it. Only transport errors, 429 and 5xx are retried; 4xx errors (bad request,
invalid key, no credits) fail immediately.
Errors
A failed request raises SerpexError (a Haystack ComponentError) whose message is one
sentence: the HTTP status, the API's reason, whether it was charged and whether to retry,
for example Out of Serpex credits (HTTP 402). Balance: 0 credits. Top up at ... or
Serpex rate limit exceeded (limit: 5 requests per second). Retry in 292 ms. It also
carries status_code, details (the API's error body) and retryable.
from haystack_integrations.components.websearch.serpex import SerpexError
try:
web_search.run(query="AI news")
except SerpexError as e:
print(e.status_code, e.retryable, e)
The component calls the API through the official serpex
SDK (>=2.12.0), so request parameters, timeouts and error parsing follow the SDK. Requests carry
User-Agent: serpex-python/<sdk version> serpex-haystack/<version>.
Component Reference
SerpexWebSearch
A Haystack component for fetching web search results via the Serpex API.
Parameters
- api_key (
Secret, optional): Serpex API key. Defaults toSERPEX_API_KEYenvironment variable. - timeout (
float, optional): Request timeout in seconds. Defaults to 60, or 100 withinclude_content. - retry_attempts (
int, optional): Total attempts on a transport error, 429 or 5xx. Defaults to2. - include_content (
bool, optional): Also fetch page content (markdown) for the top results. Defaults toFalse. - content_results (
int, optional): How many top results get content,5or10. Defaults to5. - engine (
str, optional): Deprecated — ignored by the Serpex API and not sent.
Inputs
- query (
str): The search query string. - include_content (
bool, optional): Overrides the component setting for this call. - engine, time_range (optional): Deprecated — ignored by the Serpex API and not sent.
Outputs
- documents (
List[Document]): List of Haystack Document objects containing search results.
Raises SerpexError when the request fails (after retries for 429, 5xx and transport errors).
Each document includes:
- content: The page content (markdown) when
include_contentis on and the page was extracted; otherwise the snippet - meta:
title: Result titleurl: Result URLposition: Position in search resultsquery: Original search querysnippet,content_error: Only withinclude_contentengine: Deprecated, always"auto"; removed in 3.0
Examples
Check out the examples directory for more use cases:
Why Serpex?
- 🌐 Real-Time Web Search: current results for any query, as structured JSON
- 📄 Page Content Extraction: turn URLs into LLM-ready markdown
- 🤖 Built for AI: made for agents, LLM tools and RAG pipelines
Documentation
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Development Setup
# Clone the repository
git clone https://github.com/divyeshradadiya/serpex-haystack.git
cd serpex-haystack
# Install with development dependencies
pip install -e ".[dev]"
# Run tests
pytest
# Run linting
ruff check .
black --check .
# Run type checking
mypy src/
License
This project is licensed under the Apache 2.0 License - see the LICENSE file for details.
Support
- 📧 Email: support@serpex.dev
- 💬 Discord: Join our community
- 🐛 Issues: GitHub Issues
- 📖 Docs: docs.serpex.dev
Acknowledgments
Built with ❤️ for the Haystack community by Divyesh Radadiya
Note: This is a community-maintained integration. For Serpex API support, visit serpex.dev.
Metadata
Release files for serpex-haystack 2.0.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| serpex_haystack-2.0.0.tar.gz | 22.5 kB | Without provenance | Details for serpex_haystack-2.0.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| serpex_haystack-2.0.0-py3-none-any.whl | Python 3 | none | any | Details for serpex_haystack-2.0.0-py3-none-any.whl |
Total release size: 37.1 kB
Release files / serpex_haystack-2.0.0.tar.gz
| Download URL | serpex_haystack-2.0.0.tar.gz |
|---|---|
| Size | 22.5 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
0847b56585b39a4c6aa76ae5ba126128df5de947a9a63320237c6d8b790b2773
|
|
BLAKE2b-256 checksum How to use checksums |
db9283dba33a8838cecc26d8c8c2f6380548f5365197affbbaed21360c911c11
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.11.17
|
Release files / serpex_haystack-2.0.0-py3-none-any.whl
| Download URL | serpex_haystack-2.0.0-py3-none-any.whl |
|---|---|
| Size | 14.6 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
531da4926cc985a5a2c1ad544d116c880f8fe2a3f7850184993a4aee384b75e2
|
|
BLAKE2b-256 checksum How to use checksums |
01f1e954736a2d25b18ce9e642488f47f67630ab4d7725e9d5b46443cabc851e
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.11.17
|
Security for serpex-haystack 2.0.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.