Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -138,10 +138,11 @@ CLOUDFLARE_API_TOKEN=
ZAI_PLAN_API_KEY=

# Skill API Keys
# Tavily and Jina are the primary web_search backends; Gemini (GOOGLE_API_KEY)
# and Z.AI (ZAI_PLAN_API_KEY) are the fallbacks.
# Tavily, Jina and Outcrawl are the primary web_search backends; Gemini
# (GOOGLE_API_KEY) and Z.AI (ZAI_PLAN_API_KEY) are the fallbacks.
TAVILY_API_KEY=
JINA_API_KEY=
OUTCRAWL_API_KEY=
FIRECRAWL_API_KEY=

# Langfuse tracing (optional). Set both keys to enable. Values are loaded
Expand Down
1 change: 1 addition & 0 deletions intentkit/config/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,7 @@ def __init__(self) -> None:
self.moralis_api_key: str | None = self.load("MORALIS_API_KEY")
self.tavily_api_key: str | None = self.load("TAVILY_API_KEY")
self.jina_api_key: str | None = self.load("JINA_API_KEY")
self.outcrawl_api_key: str | None = self.load("OUTCRAWL_API_KEY")
self.cookiefun_api_key: str | None = self.load("COOKIEFUN_API_KEY")
self.firecrawl_api_key: str | None = self.load("FIRECRAWL_API_KEY")
self.cryptopanic_api_key: str | None = self.load("CRYPTOPANIC_API_KEY")
Expand Down
58 changes: 49 additions & 9 deletions intentkit/core/system_tools/search_web.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@
The ``web_search`` tool tries several backends in order so agents on providers
without a native search tool still get reliable web search:

1. A random pick between **Tavily** and **Jina** (only those configured and not
in a Redis cool-down). On a quota / rate-limit error the backend is put into
cool-down and the other one is tried.
1. A random pick between **Tavily**, **Jina** and **Outcrawl** (only those
configured and not in a Redis cool-down). On a quota / rate-limit error the
backend is put into cool-down and the next one is tried.
2. **Gemini** (``gemini-flash`` with Google Search grounding) as a fallback.
3. **Z.AI** MCP web search as the last resort.

If none of the four backends is configured, a ``ToolException`` is raised.
If none of the five backends is configured, a ``ToolException`` is raised.
"""

import logging
Expand All @@ -29,6 +29,7 @@

_TAVILY_API_URL = "https://api.tavily.com/search"
_JINA_SEARCH_URL = "https://s.jina.ai/"
_OUTCRAWL_SEARCH_URL = "https://api.outcrawl.ai/v1/search"
_GEMINI_SEARCH_MODEL = "gemini-flash"

# Cool-down window (seconds) applied to a metered backend after it reports a
Expand Down Expand Up @@ -91,25 +92,29 @@ async def _arun(

has_tavily = bool(config.tavily_api_key)
has_jina = bool(config.jina_api_key)
has_outcrawl = bool(config.outcrawl_api_key)
has_gemini = bool(config.google_api_key)
has_zai = bool(config.zai_plan_api_key)

if not (has_tavily or has_jina or has_gemini or has_zai):
if not (has_tavily or has_jina or has_outcrawl or has_gemini or has_zai):
raise ToolException(
"No web search backend is configured. Set at least one of "
"TAVILY_API_KEY, JINA_API_KEY, GOOGLE_API_KEY, or ZAI_PLAN_API_KEY."
"TAVILY_API_KEY, JINA_API_KEY, OUTCRAWL_API_KEY, GOOGLE_API_KEY, "
"or ZAI_PLAN_API_KEY."
)

errors: list[str] = []

# 1. A random pick between Tavily / Jina. Cooldown is checked lazily as
# each backend is reached, so a successful first call avoids the
# second Redis round-trip.
# 1. A random pick between Tavily / Jina / Outcrawl. Cooldown is checked
# lazily as each backend is reached, so a successful first call avoids
# the second Redis round-trip.
candidates: list[str] = []
if has_tavily:
candidates.append("tavily")
if has_jina:
candidates.append("jina")
if has_outcrawl:
candidates.append("outcrawl")
random.shuffle(candidates)

for backend in candidates:
Expand All @@ -120,6 +125,10 @@ async def _arun(
return await self._search_tavily(
config.tavily_api_key, query, max_results
)
if backend == "outcrawl":
return await self._search_outcrawl(
config.outcrawl_api_key, query, max_results
)
return await self._search_jina(config.jina_api_key, query, max_results)
except _QuotaError as e:
await self._set_cooldown(backend)
Expand Down Expand Up @@ -242,6 +251,37 @@ async def _search_jina(
],
)

async def _search_outcrawl(
self, api_key: str | None, query: str, max_results: int
) -> str:
"""Search via Outcrawl."""
async with httpx.AsyncClient(timeout=30.0) as client:
response = await client.post(
_OUTCRAWL_SEARCH_URL,
headers={"Authorization": f"Bearer {api_key}"},
json={"query": query, "limit": max_results},
)

if response.status_code in _QUOTA_STATUS:
raise _QuotaError(f"status {response.status_code}")
if response.status_code != 200:
raise ToolException(
f"Outcrawl error {response.status_code}: {response.text}"
)

hits = response.json().get("hits", [])[:max_results]
return self._format_results(
query,
[
{
"title": hit.get("title"),
"url": hit.get("url"),
"snippet": hit.get("snippet"),
}
for hit in hits
],
)

async def _search_gemini(
self, query: str, max_results: int, tool_call_id: str | None
) -> str:
Expand Down
100 changes: 98 additions & 2 deletions tests/core/test_system_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -932,11 +932,12 @@ async def get(self, *args: object, **kwargs: object) -> _FakeSearchResponse:


def _set_search_keys(
mock_config, *, tavily=None, jina=None, google=None, zai=None
mock_config, *, tavily=None, jina=None, outcrawl=None, google=None, zai=None
) -> None:
"""Set the four web_search backend keys on a mocked config."""
"""Set the five web_search backend keys on a mocked config."""
mock_config.tavily_api_key = tavily
mock_config.jina_api_key = jina
mock_config.outcrawl_api_key = outcrawl
mock_config.google_api_key = google
mock_config.zai_plan_api_key = zai

Expand Down Expand Up @@ -1110,6 +1111,101 @@ async def test_web_search_jina_quota_status_raises_quota_error():
await tool._search_jina("k", "query", 5)


@pytest.mark.asyncio
async def test_web_search_outcrawl_only_success():
"""Only Outcrawl configured → its result is returned with the key."""
tool = WebSearchTool()
search = AsyncMock(return_value="outcrawl result")
with (
patch("intentkit.config.config.config") as mock_config,
patch.object(tool, "_in_cooldown", new=AsyncMock(return_value=False)),
patch.object(tool, "_search_outcrawl", new=search),
):
_set_search_keys(mock_config, outcrawl="oc-key")
result = await tool._arun("query", max_results=3)
assert result == "outcrawl result"
search.assert_awaited_once_with("oc-key", "query", 3)


@pytest.mark.asyncio
async def test_web_search_outcrawl_quota_falls_back_to_jina():
"""Outcrawl out of quota → cooldown recorded and Jina used instead."""
tool = WebSearchTool()
set_cooldown = AsyncMock()
with (
patch("intentkit.config.config.config") as mock_config,
# Pin the random order so Outcrawl is attempted first, deterministically.
patch(
"intentkit.core.system_tools.search_web.random.shuffle",
side_effect=lambda items: items.sort(key=lambda b: b != "outcrawl"),
),
patch.object(tool, "_in_cooldown", new=AsyncMock(return_value=False)),
patch.object(tool, "_set_cooldown", new=set_cooldown),
patch.object(
tool, "_search_outcrawl", new=AsyncMock(side_effect=_QuotaError("429"))
),
patch.object(tool, "_search_jina", new=AsyncMock(return_value="jina result")),
):
_set_search_keys(mock_config, outcrawl="k", jina="k")
result = await tool._arun("query")
assert result == "jina result"
set_cooldown.assert_awaited_once_with("outcrawl")


@pytest.mark.asyncio
async def test_web_search_outcrawl_http_parsing():
"""_search_outcrawl sends a bearer key and parses hits into the uniform format."""
tool = WebSearchTool()
response = _FakeSearchResponse(
200,
{
"hits": [
{
"url": "https://o.com",
"title": "O",
"snippet": "outcrawl snippet",
"rank": 1,
}
]
},
)
client = _FakeAsyncClient(response)
with patch(
"intentkit.core.system_tools.search_web.httpx.AsyncClient",
return_value=client,
):
result = await tool._search_outcrawl("k", "query", 5)
assert "https://o.com" in result
assert "outcrawl snippet" in result
assert "O" in result


@pytest.mark.asyncio
async def test_web_search_outcrawl_quota_status_raises_quota_error():
"""A 429 from Outcrawl becomes a _QuotaError."""
tool = WebSearchTool()
response = _FakeSearchResponse(429, text="rate limited")
with patch(
"intentkit.core.system_tools.search_web.httpx.AsyncClient",
return_value=_FakeAsyncClient(response),
):
with pytest.raises(_QuotaError):
await tool._search_outcrawl("k", "query", 5)


@pytest.mark.asyncio
async def test_web_search_outcrawl_error_status_raises_tool_exception():
"""A non-quota error from Outcrawl becomes a ToolException."""
tool = WebSearchTool()
response = _FakeSearchResponse(500, text="boom")
with patch(
"intentkit.core.system_tools.search_web.httpx.AsyncClient",
return_value=_FakeAsyncClient(response),
):
with pytest.raises(ToolException, match="Outcrawl error 500"):
await tool._search_outcrawl("k", "query", 5)


def test_web_search_format_results_empty():
"""No usable results yields a friendly message."""
tool = WebSearchTool()
Expand Down