openai-agents-contextfetch 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ __pycache__/
2
+ .venv/
3
+ dist/
4
+ .mypy_cache/
5
+ .ruff_cache/
6
+ .pytest_cache/
7
+ .benchmarks/
@@ -0,0 +1,21 @@
1
+ The MIT License
2
+
3
+ Copyright (c) 2026 ContextFetch
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1,69 @@
1
+ Metadata-Version: 2.5
2
+ Name: openai-agents-contextfetch
3
+ Version: 0.1.0
4
+ Summary: ContextFetch web search and page reading tools for the OpenAI Agents SDK
5
+ Project-URL: Homepage, https://contextfetch.dev
6
+ Project-URL: Documentation, https://contextfetch.dev/docs/reference
7
+ Project-URL: Repository, https://github.com/lachy3433/openai-agents-contextfetch
8
+ Author: ContextFetch
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
14
+ Requires-Python: >=3.10
15
+ Requires-Dist: contextfetch<1.0.0,>=0.1.0
16
+ Requires-Dist: openai-agents>=0.20.0
17
+ Description-Content-Type: text/markdown
18
+
19
+ # openai-agents-contextfetch
20
+
21
+ [ContextFetch](https://contextfetch.dev) web search and page reading as function tools for the
22
+ [OpenAI Agents SDK](https://openai.github.io/openai-agents-python/).
23
+
24
+ ```bash
25
+ pip install openai-agents-contextfetch
26
+ export CONTEXTFETCH_API_KEY="your-api-key" # optional: without a key, requests use the keyless tier
27
+ ```
28
+
29
+ ```python
30
+ from agents import Agent, Runner
31
+
32
+ from openai_agents_contextfetch import contextfetch_tools
33
+
34
+ agent = Agent(name="Researcher", instructions="Answer with sources.", tools=contextfetch_tools())
35
+ result = Runner.run_sync(agent, "What changed in the latest Python release?")
36
+ print(result.final_output)
37
+ ```
38
+
39
+ ## Tools
40
+
41
+ - `contextfetch_search(query, include_domains?, exclude_domains?, start_published_date?)`: web search. Returns a list
42
+ of `{title, url, published_date, content}`, where `content` is the page as Markdown: by default only the parts
43
+ relevant to the query.
44
+ - `contextfetch_read(url, query?)`: one page as Markdown. With `query`, only the parts relevant to it.
45
+
46
+ API errors (bad URL, no credits, rate limit) go back to the model as the tool output, with the API's message.
47
+
48
+ ## Options
49
+
50
+ ```python
51
+ contextfetch_tools(
52
+ api_key=None, # defaults to CONTEXTFETCH_API_KEY
53
+ num_results=5, # results per search, 1 to 25
54
+ content="pruned_context", # or "text" for whole pages
55
+ )
56
+ ```
57
+
58
+ ## Without this package
59
+
60
+ The same tools are available over MCP: `npx -y @contextfetch/mcp` with the SDK's `MCPServerStdio`.
61
+
62
+ ## Tests
63
+
64
+ ```bash
65
+ uv run --group test pytest tests # unit tests, no network
66
+ CONTEXTFETCH_API_KEY=... uv run --group test pytest tests/test_live.py # live, 2 credits
67
+ ```
68
+
69
+ Tested with openai-agents 0.20.0, 0.22.0 and 0.24.0. MIT licensed.
@@ -0,0 +1,51 @@
1
+ # openai-agents-contextfetch
2
+
3
+ [ContextFetch](https://contextfetch.dev) web search and page reading as function tools for the
4
+ [OpenAI Agents SDK](https://openai.github.io/openai-agents-python/).
5
+
6
+ ```bash
7
+ pip install openai-agents-contextfetch
8
+ export CONTEXTFETCH_API_KEY="your-api-key" # optional: without a key, requests use the keyless tier
9
+ ```
10
+
11
+ ```python
12
+ from agents import Agent, Runner
13
+
14
+ from openai_agents_contextfetch import contextfetch_tools
15
+
16
+ agent = Agent(name="Researcher", instructions="Answer with sources.", tools=contextfetch_tools())
17
+ result = Runner.run_sync(agent, "What changed in the latest Python release?")
18
+ print(result.final_output)
19
+ ```
20
+
21
+ ## Tools
22
+
23
+ - `contextfetch_search(query, include_domains?, exclude_domains?, start_published_date?)`: web search. Returns a list
24
+ of `{title, url, published_date, content}`, where `content` is the page as Markdown: by default only the parts
25
+ relevant to the query.
26
+ - `contextfetch_read(url, query?)`: one page as Markdown. With `query`, only the parts relevant to it.
27
+
28
+ API errors (bad URL, no credits, rate limit) go back to the model as the tool output, with the API's message.
29
+
30
+ ## Options
31
+
32
+ ```python
33
+ contextfetch_tools(
34
+ api_key=None, # defaults to CONTEXTFETCH_API_KEY
35
+ num_results=5, # results per search, 1 to 25
36
+ content="pruned_context", # or "text" for whole pages
37
+ )
38
+ ```
39
+
40
+ ## Without this package
41
+
42
+ The same tools are available over MCP: `npx -y @contextfetch/mcp` with the SDK's `MCPServerStdio`.
43
+
44
+ ## Tests
45
+
46
+ ```bash
47
+ uv run --group test pytest tests # unit tests, no network
48
+ CONTEXTFETCH_API_KEY=... uv run --group test pytest tests/test_live.py # live, 2 credits
49
+ ```
50
+
51
+ Tested with openai-agents 0.20.0, 0.22.0 and 0.24.0. MIT licensed.
@@ -0,0 +1,87 @@
1
+ """ContextFetch web search and page reading tools for the OpenAI Agents SDK."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Literal
6
+
7
+ from agents import FunctionTool, RunContextWrapper, function_tool
8
+ from contextfetch import ContextFetch
9
+
10
+ __all__ = ("contextfetch_tools",)
11
+
12
+ Content = Literal["pruned_context", "text"]
13
+ """`"pruned_context"`: only the parts of each page relevant to the query. `"text"`: the whole page as Markdown."""
14
+
15
+ _RESULT_KEY = {"pruned_context": "prunedContext", "text": "text"}
16
+
17
+
18
+ def _error_message(ctx: RunContextWrapper[Any], error: Exception) -> str:
19
+ # The SDK's default hides the message; the API's error text tells the model what to fix.
20
+ return f"ContextFetch error: {error}"
21
+
22
+
23
+ def contextfetch_tools(
24
+ api_key: str | None = None,
25
+ *,
26
+ num_results: int = 5,
27
+ content: Content = "pruned_context",
28
+ ) -> list[FunctionTool]:
29
+ """Returns the `contextfetch_search` and `contextfetch_read` function tools, sharing one client.
30
+
31
+ Args:
32
+ api_key: The ContextFetch API key. Defaults to the `CONTEXTFETCH_API_KEY` environment variable;
33
+ without either, requests use the keyless tier.
34
+ num_results: Results per search (1 to 25). Defaults to 5.
35
+ content: Which page content search results carry. Defaults to `"pruned_context"`.
36
+
37
+ API errors (bad URL, no credits, rate limit) are returned to the model as the tool output, with the API's message.
38
+ """
39
+ client = ContextFetch(api_key)
40
+ key = _RESULT_KEY[content]
41
+
42
+ # Sync functions: the SDK runs them in a worker thread (the contextfetch client is stdlib urllib).
43
+ @function_tool(failure_error_function=_error_message)
44
+ def contextfetch_search(
45
+ query: str,
46
+ include_domains: list[str] | None = None,
47
+ exclude_domains: list[str] | None = None,
48
+ start_published_date: str | None = None,
49
+ ) -> list[dict[str, Any]]:
50
+ """Searches the web and returns the top results with their page content as Markdown.
51
+
52
+ Args:
53
+ query: The web search query.
54
+ include_domains: Only return results from these domains.
55
+ exclude_domains: Never return results from these domains.
56
+ start_published_date: Only return pages published on or after this date (YYYY-MM-DD).
57
+ """
58
+ response = client.search(
59
+ query,
60
+ num_results=num_results,
61
+ include_domains=include_domains,
62
+ exclude_domains=exclude_domains,
63
+ start_published_date=start_published_date,
64
+ text=content == "text",
65
+ pruned_context=content == "pruned_context",
66
+ )
67
+ return [
68
+ {
69
+ "title": r.get("title"),
70
+ "url": r.get("url"),
71
+ "published_date": r.get("publishedDate"),
72
+ "content": r.get(key) or "",
73
+ }
74
+ for r in response.get("results", [])
75
+ ]
76
+
77
+ @function_tool(failure_error_function=_error_message)
78
+ def contextfetch_read(url: str, query: str | None = None) -> str:
79
+ """Reads a web page and returns it as Markdown.
80
+
81
+ Args:
82
+ url: The URL of the page.
83
+ query: If set, only the parts of the page relevant to this question are returned.
84
+ """
85
+ return client.read(url, query=query).markdown
86
+
87
+ return [contextfetch_search, contextfetch_read]
@@ -0,0 +1,35 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "openai-agents-contextfetch"
7
+ version = "0.1.0"
8
+ description = "ContextFetch web search and page reading tools for the OpenAI Agents SDK"
9
+ authors = [{ name = "ContextFetch" }]
10
+ license = "MIT"
11
+ readme = "README.md"
12
+ requires-python = ">=3.10"
13
+ classifiers = [
14
+ "Intended Audience :: Developers",
15
+ "Programming Language :: Python :: 3",
16
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
17
+ ]
18
+ dependencies = [
19
+ "openai-agents>=0.20.0",
20
+ "contextfetch>=0.1.0,<1.0.0",
21
+ ]
22
+
23
+ [project.urls]
24
+ Homepage = "https://contextfetch.dev"
25
+ Documentation = "https://contextfetch.dev/docs/reference"
26
+ Repository = "https://github.com/lachy3433/openai-agents-contextfetch"
27
+
28
+ [dependency-groups]
29
+ test = ["pytest>=8", "pytest-asyncio>=0.23"]
30
+
31
+ [tool.pytest.ini_options]
32
+ asyncio_mode = "auto"
33
+
34
+ [tool.hatch.build.targets.sdist]
35
+ only-include = ["openai_agents_contextfetch", "tests", "README.md", "LICENSE"]
@@ -0,0 +1,26 @@
1
+ """Live check against the real API (2 credits). Skipped unless CONTEXTFETCH_API_KEY is set."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+
8
+ import pytest
9
+ from agents.tool_context import ToolContext
10
+
11
+ from openai_agents_contextfetch import contextfetch_tools
12
+
13
+ pytestmark = pytest.mark.skipif(not os.environ.get("CONTEXTFETCH_API_KEY"), reason="needs CONTEXTFETCH_API_KEY")
14
+
15
+
16
+ async def test_live() -> None:
17
+ search, read = contextfetch_tools(num_results=2)
18
+
19
+ async def invoke(tool, args):
20
+ raw = json.dumps(args)
21
+ return await tool.on_invoke_tool(ToolContext(None, tool_name=tool.name, tool_call_id="1", tool_arguments=raw), raw)
22
+
23
+ results = await invoke(search, {"query": "python asyncio TaskGroup"})
24
+ assert results and results[0]["url"].startswith("http") and results[0]["content"]
25
+ page = await invoke(read, {"url": "https://docs.python.org/3/library/asyncio-task.html", "query": "TaskGroup"})
26
+ assert "TaskGroup" in page
@@ -0,0 +1,88 @@
1
+ """Unit tests: the SDK's HTTP call is patched, so nothing touches the network."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any
7
+
8
+ import pytest
9
+ from agents import FunctionTool
10
+ from agents.tool_context import ToolContext
11
+ from contextfetch import ContextFetch, ContextFetchError
12
+
13
+ from openai_agents_contextfetch import contextfetch_tools
14
+
15
+ RESULTS = [
16
+ {"url": "https://example.com/a", "title": "A", "publishedDate": "2026-01-02", "text": "# A", "prunedContext": "chunk A"},
17
+ {"url": "https://example.com/b", "title": None, "text": "# B", "prunedContext": "chunk B"},
18
+ ]
19
+
20
+
21
+ @pytest.fixture
22
+ def calls(monkeypatch: pytest.MonkeyPatch) -> list[dict[str, Any]]:
23
+ calls: list[dict[str, Any]] = []
24
+ monkeypatch.delenv("CONTEXTFETCH_API_KEY", raising=False)
25
+
26
+ def request(self: ContextFetch, method: str, path: str, body: Any = None, **_: Any) -> tuple[bytes, dict]:
27
+ calls.append({"method": method, "path": path, "body": body, "api_key": self.api_key})
28
+ if path.startswith("/r/https://missing"):
29
+ raise ContextFetchError("not found", status=404)
30
+ if path.startswith("/r/"):
31
+ return b"# Page", {}
32
+ return json.dumps({"results": RESULTS[: body["numResults"]]}).encode(), {}
33
+
34
+ monkeypatch.setattr(ContextFetch, "_request", request)
35
+ return calls
36
+
37
+
38
+ def _tools(**kwargs: Any) -> dict[str, FunctionTool]:
39
+ return {t.name: t for t in contextfetch_tools(**kwargs)}
40
+
41
+
42
+ async def _invoke(tool: FunctionTool, args: dict[str, Any]) -> Any:
43
+ raw = json.dumps(args)
44
+ return await tool.on_invoke_tool(ToolContext(None, tool_name=tool.name, tool_call_id="1", tool_arguments=raw), raw)
45
+
46
+
47
+ def test_schemas() -> None:
48
+ tools = _tools(api_key="k")
49
+ assert set(tools) == {"contextfetch_search", "contextfetch_read"}
50
+ search = tools["contextfetch_search"].params_json_schema
51
+ assert "query" in search["required"]
52
+ assert "YYYY-MM-DD" in search["properties"]["start_published_date"]["description"]
53
+ assert "page" in tools["contextfetch_read"].description
54
+
55
+
56
+ async def test_search(calls: list[dict[str, Any]]) -> None:
57
+ out = await _invoke(_tools(api_key="k", num_results=2)["contextfetch_search"], {"query": "q", "include_domains": ["example.com"]})
58
+ assert out == [
59
+ {"title": "A", "url": "https://example.com/a", "published_date": "2026-01-02", "content": "chunk A"},
60
+ {"title": None, "url": "https://example.com/b", "published_date": None, "content": "chunk B"},
61
+ ]
62
+ assert calls == [
63
+ {
64
+ "method": "POST",
65
+ "path": "/v1/search",
66
+ "body": {"query": "q", "numResults": 2, "includeDomains": ["example.com"], "contents": {"pruned_context": True}},
67
+ "api_key": "k",
68
+ }
69
+ ]
70
+
71
+
72
+ async def test_search_text_content_and_env_key(calls: list[dict[str, Any]], monkeypatch: pytest.MonkeyPatch) -> None:
73
+ monkeypatch.setenv("CONTEXTFETCH_API_KEY", "env-key")
74
+ out = await _invoke(_tools(num_results=1, content="text")["contextfetch_search"], {"query": "q"})
75
+ assert out[0]["content"] == "# A"
76
+ assert calls[0]["body"]["contents"] == {"text": True}
77
+ assert calls[0]["api_key"] == "env-key"
78
+
79
+
80
+ async def test_read(calls: list[dict[str, Any]]) -> None:
81
+ out = await _invoke(_tools(api_key="k")["contextfetch_read"], {"url": "https://example.com/x", "query": "pricing"})
82
+ assert out == "# Page"
83
+ assert calls[0]["path"] == "/r/https://example.com/x?q=pricing"
84
+
85
+
86
+ async def test_error_goes_to_model(calls: list[dict[str, Any]]) -> None:
87
+ out = await _invoke(_tools(api_key="k")["contextfetch_read"], {"url": "https://missing.example"})
88
+ assert "not found" in out