crewai-specstream 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,14 @@
1
+ node_modules/
2
+ dist/
3
+ build/
4
+ *.egg-info/
5
+ __pycache__/
6
+ .venv/
7
+ .pytest_cache/
8
+ *.tsbuildinfo
9
+ *.tgz
10
+ *.whl
11
+ .env
12
+ .env.*
13
+ !.env.example
14
+ .DS_Store
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 SpecStream SAS
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 all
13
+ 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 THE
21
+ SOFTWARE.
@@ -0,0 +1,149 @@
1
+ Metadata-Version: 2.5
2
+ Name: crewai-specstream
3
+ Version: 0.1.0
4
+ Summary: Give a CrewAI agent any list from the live web: ask in plain words, get every matching row with the page it came from, within a price you set in code.
5
+ Project-URL: Homepage, https://specstream.ai
6
+ Project-URL: Documentation, https://specstream.ai/docs/crewai
7
+ Project-URL: Repository, https://github.com/Specstreamai/specstream-tools/tree/main/packages/crewai-specstream
8
+ Project-URL: Issues, https://github.com/Specstreamai/specstream-tools/issues
9
+ Project-URL: Pricing, https://specstream.ai/pricing
10
+ Author-email: SpecStream <support@specstream.ai>
11
+ Maintainer-email: SpecStream <support@specstream.ai>
12
+ License-Expression: MIT
13
+ License-File: LICENSE
14
+ Keywords: agents,crewai,crewai-tools,lead-lists,live-web,research,specstream,tools,web-data
15
+ Classifier: Development Status :: 4 - Beta
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3 :: Only
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Classifier: Topic :: Internet :: WWW/HTTP
25
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
26
+ Classifier: Typing :: Typed
27
+ Requires-Python: <3.14,>=3.10
28
+ Requires-Dist: crewai<2.0.0,>=1.0.0
29
+ Provides-Extra: test
30
+ Requires-Dist: pytest>=8; extra == 'test'
31
+ Description-Content-Type: text/markdown
32
+
33
+ # crewai-specstream
34
+
35
+ Most web tools for CrewAI hand your agent pages to read, and the agent builds the list itself, one search and one scrape at a time. This one hands it the finished list. The agent asks in plain words – "dental clinics in Lisbon with online booking", "US startups that filed a $5M+ Form D after October 8, 2026" – and gets back every matching row, each with the page it was read from. The list starts only within a price you set in code, and the model can't raise it.
36
+
37
+ ```bash
38
+ pip install -U crewai-specstream
39
+ export SPECSTREAM_API_KEY=ss_live_... # Agents & API in your SpecStream workspace
40
+ ```
41
+
42
+ A free account comes with $10 of work to use within 30 days and needs no card: [specstream.ai](https://specstream.ai/signup). Works with CrewAI 1.x on Python 3.10 – 3.13.
43
+
44
+ ## A crew that can find lists
45
+
46
+ ```python
47
+ from crewai import Agent, Crew, Task
48
+ from crewai_specstream import specstream_tools
49
+
50
+ analyst = Agent(
51
+ role="Funding analyst",
52
+ goal="Answer questions about who is raising money, with a source for every claim",
53
+ backstory="You work from lists, not from memory. You cite the page each row came from.",
54
+ tools=specstream_tools(max_price_usd=5),
55
+ )
56
+
57
+ task = Task(
58
+ description=(
59
+ "Find US startups that raised $5M or more in a Form D filed after October 8, 2026. "
60
+ "Which industries lead? Link the filing for each company you name."
61
+ ),
62
+ expected_output="The three leading industries, with the companies and their filing links.",
63
+ agent=analyst,
64
+ )
65
+
66
+ print(Crew(agents=[analyst], tasks=[task]).kickoff().raw)
67
+ ```
68
+
69
+ The agent writes the request and picks how many rows. You decide what one list may cost. The agent uses your default model; pass `llm="..."` to `Agent` to choose another.
70
+
71
+ ## What comes back
72
+
73
+ One flat row per match: the list's own columns, then where the row was read. This is a real row from the request above.
74
+
75
+ ```json
76
+ {
77
+ "list_id": "fnd_gk5y3d0r97bvyz0t08zzh75kr6",
78
+ "position": 26,
79
+ "Organization": "RapidCanvas Inc",
80
+ "Published address": "801 BARTON SPRINGS RD, AUSTIN, TEXAS, 78704",
81
+ "Source industry classification": "Other Technology",
82
+ "Amount sold (USD)": "28999988",
83
+ "Funding filing date": "2026-10-14",
84
+ "source_url": "https://www.sec.gov/Archives/edgar/data/2052031/000205203126000006/primary_doc.xml",
85
+ "checked_at": "2026-10-14T19:56:02.016693Z",
86
+ "list_link": "https://specstream.ai/workspace/collections/fnd_gk5y3d0r97bvyz0t08zzh75kr6"
87
+ }
88
+ ```
89
+
90
+ Columns follow the request. Ask for "breweries in Portland, Oregon that host events, with their website" and the rows carry the brewery and its website instead. A fact a source doesn't publish comes back empty, never guessed.
91
+
92
+ ## The two tools
93
+
94
+ | Tool | The model gives | What happens | Cost |
95
+ | --- | --- | --- | --- |
96
+ | `specstream_find_list` | `request`, `max_results` (1 – 1000, default 25) | Reads the request, prices it, starts it only within `max_price_usd`, waits up to `wait_seconds` (7 minutes by default) and returns every row | Only the rows that match |
97
+ | `specstream_get_list_results` | `list_id` | Every row found so far, for a list that was still running | Free |
98
+
99
+ When the price is above your maximum, nothing runs: the tool returns the price, so the agent can ask for fewer rows or tell the user. When a request is too vague to price ("clinics"), it returns how SpecStream read it, so the agent can add the place or the conditions.
100
+
101
+ Use the classes directly when you want different settings per tool:
102
+
103
+ ```python
104
+ from crewai_specstream import SpecStreamFindListTool, SpecStreamGetListResultsTool
105
+
106
+ find = SpecStreamFindListTool(max_price_usd=20, wait_seconds=600)
107
+ results = SpecStreamGetListResultsTool()
108
+ ```
109
+
110
+ Both read `SPECSTREAM_API_KEY`; pass `api_key="..."` to use another. The key is stored as a secret, so it stays out of reprs and dumps, and it is sent only in the `Authorization` header.
111
+
112
+ ## In a crew project
113
+
114
+ Give the tools to an agent in your `@CrewBase` class the way you would any other:
115
+
116
+ ```python
117
+ from crewai import Agent
118
+ from crewai.project import CrewBase, agent
119
+ from crewai_specstream import specstream_tools
120
+
121
+ @CrewBase
122
+ class LeadCrew:
123
+ @agent
124
+ def researcher(self) -> Agent:
125
+ return Agent(config=self.agents_config["researcher"], tools=specstream_tools(max_price_usd=5))
126
+ ```
127
+
128
+ The tools also implement CrewAI's async hook (`_arun`) and run their requests in a worker thread, so an async crew's event loop isn't blocked while a list runs.
129
+
130
+ ## Money, plainly
131
+
132
+ - `max_price_usd` lives on the tool, in your code. The model never sees it and can't change it.
133
+ - You pay for rows that match. Candidates SpecStream couldn't confirm are left out and aren't billed.
134
+ - A retried step asking for the same list within the hour gets the list it already started, not a second bill. That covers CrewAI retrying a failed tool call.
135
+ - CrewAI caches tool calls by their arguments. These tools cache a list only once it has finished, so a list that was still running is read again instead of replayed.
136
+ - Rates and plans: [specstream.ai/pricing](https://specstream.ai/pricing).
137
+
138
+ ## When to reach for it
139
+
140
+ When the answer is many things that meet conditions: companies in a city, clinics with a service, funding filings, open grants, tenders, repositories, people in a role. For a single fact or a summary of one page, a search tool fits better.
141
+
142
+ ## More
143
+
144
+ - [SpecStream docs](https://specstream.ai/docs) and the [CrewAI page](https://specstream.ai/docs/crewai)
145
+ - Agents outside CrewAI: the [MCP server](https://specstream.ai/docs/mcp) at `https://api.specstream.ai/mcp`
146
+ - The [Python SDK](https://pypi.org/project/specstream-client/) for everything else in the API
147
+ - Questions: support@specstream.ai
148
+
149
+ MIT licensed. Made by [SpecStream](https://specstream.ai), the live web data engine for teams and agents.
@@ -0,0 +1,117 @@
1
+ # crewai-specstream
2
+
3
+ Most web tools for CrewAI hand your agent pages to read, and the agent builds the list itself, one search and one scrape at a time. This one hands it the finished list. The agent asks in plain words – "dental clinics in Lisbon with online booking", "US startups that filed a $5M+ Form D after October 8, 2026" – and gets back every matching row, each with the page it was read from. The list starts only within a price you set in code, and the model can't raise it.
4
+
5
+ ```bash
6
+ pip install -U crewai-specstream
7
+ export SPECSTREAM_API_KEY=ss_live_... # Agents & API in your SpecStream workspace
8
+ ```
9
+
10
+ A free account comes with $10 of work to use within 30 days and needs no card: [specstream.ai](https://specstream.ai/signup). Works with CrewAI 1.x on Python 3.10 – 3.13.
11
+
12
+ ## A crew that can find lists
13
+
14
+ ```python
15
+ from crewai import Agent, Crew, Task
16
+ from crewai_specstream import specstream_tools
17
+
18
+ analyst = Agent(
19
+ role="Funding analyst",
20
+ goal="Answer questions about who is raising money, with a source for every claim",
21
+ backstory="You work from lists, not from memory. You cite the page each row came from.",
22
+ tools=specstream_tools(max_price_usd=5),
23
+ )
24
+
25
+ task = Task(
26
+ description=(
27
+ "Find US startups that raised $5M or more in a Form D filed after October 8, 2026. "
28
+ "Which industries lead? Link the filing for each company you name."
29
+ ),
30
+ expected_output="The three leading industries, with the companies and their filing links.",
31
+ agent=analyst,
32
+ )
33
+
34
+ print(Crew(agents=[analyst], tasks=[task]).kickoff().raw)
35
+ ```
36
+
37
+ The agent writes the request and picks how many rows. You decide what one list may cost. The agent uses your default model; pass `llm="..."` to `Agent` to choose another.
38
+
39
+ ## What comes back
40
+
41
+ One flat row per match: the list's own columns, then where the row was read. This is a real row from the request above.
42
+
43
+ ```json
44
+ {
45
+ "list_id": "fnd_gk5y3d0r97bvyz0t08zzh75kr6",
46
+ "position": 26,
47
+ "Organization": "RapidCanvas Inc",
48
+ "Published address": "801 BARTON SPRINGS RD, AUSTIN, TEXAS, 78704",
49
+ "Source industry classification": "Other Technology",
50
+ "Amount sold (USD)": "28999988",
51
+ "Funding filing date": "2026-10-14",
52
+ "source_url": "https://www.sec.gov/Archives/edgar/data/2052031/000205203126000006/primary_doc.xml",
53
+ "checked_at": "2026-10-14T19:56:02.016693Z",
54
+ "list_link": "https://specstream.ai/workspace/collections/fnd_gk5y3d0r97bvyz0t08zzh75kr6"
55
+ }
56
+ ```
57
+
58
+ Columns follow the request. Ask for "breweries in Portland, Oregon that host events, with their website" and the rows carry the brewery and its website instead. A fact a source doesn't publish comes back empty, never guessed.
59
+
60
+ ## The two tools
61
+
62
+ | Tool | The model gives | What happens | Cost |
63
+ | --- | --- | --- | --- |
64
+ | `specstream_find_list` | `request`, `max_results` (1 – 1000, default 25) | Reads the request, prices it, starts it only within `max_price_usd`, waits up to `wait_seconds` (7 minutes by default) and returns every row | Only the rows that match |
65
+ | `specstream_get_list_results` | `list_id` | Every row found so far, for a list that was still running | Free |
66
+
67
+ When the price is above your maximum, nothing runs: the tool returns the price, so the agent can ask for fewer rows or tell the user. When a request is too vague to price ("clinics"), it returns how SpecStream read it, so the agent can add the place or the conditions.
68
+
69
+ Use the classes directly when you want different settings per tool:
70
+
71
+ ```python
72
+ from crewai_specstream import SpecStreamFindListTool, SpecStreamGetListResultsTool
73
+
74
+ find = SpecStreamFindListTool(max_price_usd=20, wait_seconds=600)
75
+ results = SpecStreamGetListResultsTool()
76
+ ```
77
+
78
+ Both read `SPECSTREAM_API_KEY`; pass `api_key="..."` to use another. The key is stored as a secret, so it stays out of reprs and dumps, and it is sent only in the `Authorization` header.
79
+
80
+ ## In a crew project
81
+
82
+ Give the tools to an agent in your `@CrewBase` class the way you would any other:
83
+
84
+ ```python
85
+ from crewai import Agent
86
+ from crewai.project import CrewBase, agent
87
+ from crewai_specstream import specstream_tools
88
+
89
+ @CrewBase
90
+ class LeadCrew:
91
+ @agent
92
+ def researcher(self) -> Agent:
93
+ return Agent(config=self.agents_config["researcher"], tools=specstream_tools(max_price_usd=5))
94
+ ```
95
+
96
+ The tools also implement CrewAI's async hook (`_arun`) and run their requests in a worker thread, so an async crew's event loop isn't blocked while a list runs.
97
+
98
+ ## Money, plainly
99
+
100
+ - `max_price_usd` lives on the tool, in your code. The model never sees it and can't change it.
101
+ - You pay for rows that match. Candidates SpecStream couldn't confirm are left out and aren't billed.
102
+ - A retried step asking for the same list within the hour gets the list it already started, not a second bill. That covers CrewAI retrying a failed tool call.
103
+ - CrewAI caches tool calls by their arguments. These tools cache a list only once it has finished, so a list that was still running is read again instead of replayed.
104
+ - Rates and plans: [specstream.ai/pricing](https://specstream.ai/pricing).
105
+
106
+ ## When to reach for it
107
+
108
+ When the answer is many things that meet conditions: companies in a city, clinics with a service, funding filings, open grants, tenders, repositories, people in a role. For a single fact or a summary of one page, a search tool fits better.
109
+
110
+ ## More
111
+
112
+ - [SpecStream docs](https://specstream.ai/docs) and the [CrewAI page](https://specstream.ai/docs/crewai)
113
+ - Agents outside CrewAI: the [MCP server](https://specstream.ai/docs/mcp) at `https://api.specstream.ai/mcp`
114
+ - The [Python SDK](https://pypi.org/project/specstream-client/) for everything else in the API
115
+ - Questions: support@specstream.ai
116
+
117
+ MIT licensed. Made by [SpecStream](https://specstream.ai), the live web data engine for teams and agents.
@@ -0,0 +1,7 @@
1
+ """SpecStream for CrewAI: ask for any list on the live web in plain words, within a price you set."""
2
+
3
+ from crewai_specstream._api import SpecStreamError
4
+ from crewai_specstream.tools import SpecStreamFindListTool, SpecStreamGetListResultsTool, specstream_tools
5
+
6
+ __all__ = ["SpecStreamError", "SpecStreamFindListTool", "SpecStreamGetListResultsTool", "specstream_tools"]
7
+ __version__ = "0.1.0"
@@ -0,0 +1,206 @@
1
+ """The SpecStream REST calls the tools share: read a request, price it, start it within a maximum, read its rows."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import time
8
+ import urllib.error
9
+ import urllib.parse
10
+ import urllib.request
11
+ from dataclasses import dataclass
12
+ from typing import Any, Callable
13
+
14
+ DEFAULT_BASE_URL = "https://api.specstream.ai"
15
+ USER_AGENT = "crewai-specstream/0.1.0"
16
+ # A list runs for up to about five minutes, so the tools wait a little longer than that by default.
17
+ DEFAULT_WAIT_SECONDS = 420.0
18
+ FINISHED = {"completed", "partial"}
19
+ STOPPED = {"failed", "cancelled", "canceled", "expired"}
20
+ # Fields every row carries; a column with the same name is renamed so it can't overwrite them.
21
+ RESERVED = {"list_id", "list_link", "position", "source_url", "checked_at"}
22
+
23
+ Opener = Callable[[urllib.request.Request, float], Any]
24
+
25
+
26
+ class SpecStreamError(RuntimeError):
27
+ """SpecStream refused a call or answered with something this package can't read."""
28
+
29
+
30
+ def _dollars(cents: int) -> str:
31
+ return f"${cents / 100:.2f}"
32
+
33
+
34
+ def list_link(find_id: str) -> str:
35
+ return f"https://specstream.ai/workspace/collections/{urllib.parse.quote(find_id, safe='')}"
36
+
37
+
38
+ def flatten_row(find_id: str, record: dict[str, Any]) -> dict[str, Any]:
39
+ """One row as flat fields: each column's label holds what the list shows, plus where the row was read."""
40
+ row: dict[str, Any] = {"list_id": find_id, "position": record.get("ordinal")}
41
+ source: dict[str, Any] | None = None
42
+ for cell in record.get("details") or record.get("cells") or []:
43
+ label = str(cell.get("label") or cell.get("column_id") or "").strip()
44
+ if not label:
45
+ continue
46
+ if label in RESERVED:
47
+ label = f"{label} (column)"
48
+ if cell.get("absence"):
49
+ value: Any = ""
50
+ elif cell.get("display") is not None:
51
+ value = cell["display"]
52
+ else:
53
+ value = cell.get("value") if cell.get("value") is not None else ""
54
+ row[label] = value
55
+ provenance = cell.get("provenance") or {}
56
+ if source is None and str(provenance.get("source_url") or "").startswith("http"):
57
+ source = provenance
58
+ row["source_url"] = source.get("source_url", "") if source else ""
59
+ row["checked_at"] = source.get("observed_at", "") if source else ""
60
+ row["list_link"] = list_link(find_id)
61
+ return row
62
+
63
+
64
+ @dataclass
65
+ class SpecStreamAPI:
66
+ api_key: str
67
+ base_url: str = DEFAULT_BASE_URL
68
+ timeout: float = 30.0
69
+ opener: Opener | None = None
70
+ sleep: Callable[[float], None] = time.sleep
71
+ clock: Callable[[], float] = time.monotonic
72
+
73
+ def request(self, method: str, path: str, body: dict[str, Any] | None = None, *, allow_404: bool = False) -> dict[str, Any] | None:
74
+ key = (self.api_key or "").strip()
75
+ if not key:
76
+ raise SpecStreamError("Set SPECSTREAM_API_KEY or pass api_key. Create a key under Agents & API in your SpecStream workspace.")
77
+ request = urllib.request.Request(
78
+ self.base_url.rstrip("/") + path,
79
+ data=None if body is None else json.dumps(body).encode(),
80
+ method=method,
81
+ headers={
82
+ "Authorization": key if key.lower().startswith("bearer ") else f"Bearer {key}",
83
+ "Accept": "application/json",
84
+ "Content-Type": "application/json",
85
+ "User-Agent": USER_AGENT,
86
+ },
87
+ )
88
+ open_ = self.opener or (lambda req, timeout: urllib.request.urlopen(req, timeout=timeout))
89
+ try:
90
+ response = open_(request, self.timeout)
91
+ try:
92
+ raw = response.read()
93
+ finally:
94
+ response.close()
95
+ except urllib.error.HTTPError as error:
96
+ if allow_404 and error.code == 404:
97
+ return None
98
+ raise SpecStreamError(_error_message(error)) from None
99
+ except urllib.error.URLError as error:
100
+ raise SpecStreamError(f"Couldn't reach SpecStream: {error.reason}") from None
101
+ try:
102
+ payload = json.loads(raw or b"{}")
103
+ except ValueError:
104
+ payload = None
105
+ if not isinstance(payload, dict) or not isinstance(payload.get("data"), dict):
106
+ raise SpecStreamError("SpecStream returned a response this package couldn't read.")
107
+ return payload["data"]
108
+
109
+ def results(self, find_id: str) -> dict[str, Any]:
110
+ """Every row found so far for a list, following the pages."""
111
+ rows: list[dict[str, Any]] = []
112
+ cursor: str | None = None
113
+ status = "running"
114
+ while True:
115
+ query = {"limit": "100", **({"cursor": cursor} if cursor else {})}
116
+ page = self.request("GET", f"/v1/finds/{urllib.parse.quote(find_id, safe='')}/rows?{urllib.parse.urlencode(query)}") or {}
117
+ status = page.get("status") or status
118
+ rows.extend(flatten_row(find_id, record) for record in page.get("rows") or [])
119
+ cursor = page.get("next_cursor")
120
+ if not cursor:
121
+ break
122
+ return {"list_id": find_id, "status": status, "list_link": list_link(find_id), "row_count": len(rows), "rows": rows}
123
+
124
+ def find_list(
125
+ self,
126
+ request: str,
127
+ *,
128
+ max_results: int,
129
+ max_price_usd: float,
130
+ wait_seconds: float = DEFAULT_WAIT_SECONDS,
131
+ poll_interval: float = 3.0,
132
+ locale: str = "en-US",
133
+ key_prefix: str = "crewai",
134
+ ) -> dict[str, Any]:
135
+ q = (request or "").strip()
136
+ if not q:
137
+ raise ValueError("Describe the list to find.")
138
+ if not isinstance(max_results, int) or max_results < 1:
139
+ raise ValueError("max_results must be 1 or more.")
140
+ max_cents = round(float(max_price_usd) * 100)
141
+ if max_cents <= 0:
142
+ raise ValueError("max_price_usd must be greater than 0.")
143
+
144
+ # The same request with the same limits gets the run it already started in this hour or the one before,
145
+ # so a retried agent step never buys the list twice, even across the turn of the hour.
146
+ def key_for(at: float) -> str:
147
+ hour = time.strftime("%Y-%m-%dT%H", time.gmtime(at))
148
+ return f"{key_prefix}-" + hashlib.sha256(f"{q}|{max_results}|{max_cents}|{hour}".encode()).hexdigest()[:32]
149
+
150
+ now = time.time()
151
+ request_key = key_for(now)
152
+ existing = None
153
+ for candidate in (request_key, key_for(now - 3600)):
154
+ existing = self.request("GET", f"/v1/capacity/requests/{urllib.parse.quote(candidate, safe='')}", allow_404=True)
155
+ if existing and existing.get("find_id"):
156
+ break
157
+ if existing and existing.get("find_id"):
158
+ find_id = existing["find_id"]
159
+ maximum_cents = int(existing.get("maximum_cents") or max_cents)
160
+ else:
161
+ reading = self.request("POST", "/v1/parse", {"q": q, "locale": locale}) or {}
162
+ if reading.get("status") != "runnable":
163
+ read_as = reading.get("canonical_sentence") or q
164
+ return {
165
+ "status": "needs_edit",
166
+ "request": q,
167
+ "message": f'SpecStream needs a clearer request before it can price it. It read: "{read_as}". Add the place or what every row must meet.',
168
+ }
169
+ quote = self.request(
170
+ "POST", "/v1/capacity/quotes", {"ast_hash": reading["ast_hash"], "operation": "find", "requested_units": max_results}
171
+ ) or {}
172
+ maximum_cents = int(quote.get("maximum_cents") or 0)
173
+ if maximum_cents > max_cents:
174
+ return {
175
+ "status": "over_maximum",
176
+ "request": q,
177
+ "maximum_price_usd": maximum_cents / 100,
178
+ "message": f"Nothing ran: this list can cost up to {_dollars(maximum_cents)}, above the maximum of {_dollars(max_cents)}. Ask for fewer results or raise max_price_usd.",
179
+ }
180
+ run = self.request(
181
+ "POST",
182
+ "/v1/capacity/executions",
183
+ {"quote_id": quote["quote_id"], "quote_hash": quote["quote_hash"], "confirm_max_cents": maximum_cents, "idempotency_key": request_key},
184
+ ) or {}
185
+ find_id = run["find_id"]
186
+
187
+ deadline = self.clock() + max(0.0, wait_seconds)
188
+ while True:
189
+ result = self.results(find_id)
190
+ if result["status"] in FINISHED | STOPPED or self.clock() >= deadline:
191
+ break
192
+ self.sleep(poll_interval)
193
+ result.update({"request": q, "maximum_price_usd": maximum_cents / 100})
194
+ if result["status"] not in FINISHED | STOPPED:
195
+ result["message"] = "Still running. Call specstream_get_list_results with this list_id for the rest."
196
+ return result
197
+
198
+
199
+ def _error_message(error: urllib.error.HTTPError) -> str:
200
+ try:
201
+ payload = json.loads(error.read() or b"{}")
202
+ except ValueError:
203
+ payload = {}
204
+ detail = payload.get("error") if isinstance(payload, dict) else None
205
+ message = detail.get("message") if isinstance(detail, dict) else detail if isinstance(detail, str) else None
206
+ return f"SpecStream answered {error.code}: {message or error.reason}"
File without changes
@@ -0,0 +1,162 @@
1
+ """CrewAI tools that ask SpecStream for a list on the live web and read its rows."""
2
+
3
+ import asyncio
4
+ import json
5
+ import os
6
+ from typing import Any
7
+
8
+ from crewai.tools import BaseTool, EnvVar
9
+ from pydantic import BaseModel, Field, SecretStr, field_validator
10
+
11
+ from crewai_specstream._api import DEFAULT_BASE_URL, DEFAULT_WAIT_SECONDS, FINISHED, STOPPED, SpecStreamAPI
12
+
13
+ KEY_HELP = "Set SPECSTREAM_API_KEY or pass api_key. Create a key under Agents & API in your SpecStream workspace."
14
+ MAX_RESULTS = 1000
15
+
16
+
17
+ class FindListInput(BaseModel):
18
+ """What the model fills in. The price ceiling is not here: the developer sets it on the tool."""
19
+
20
+ request: str = Field(
21
+ ...,
22
+ description=(
23
+ "The list in plain words: what to find, where, what every row must meet, and the facts to bring back. "
24
+ 'Example: "Dental clinics in Lisbon with online booking, with their website and phone".'
25
+ ),
26
+ )
27
+ max_results: int = Field(
28
+ default=25,
29
+ ge=1,
30
+ le=MAX_RESULTS,
31
+ description="How many rows to find, from 1 to 1000. Ask for what the task needs; the price grows with the matches.",
32
+ )
33
+
34
+
35
+ class GetListResultsInput(BaseModel):
36
+ list_id: str = Field(
37
+ ...,
38
+ description='The list_id that specstream_find_list returned, like "fnd_gk5y3d0r97bvyz0t08zzh75kr6".',
39
+ )
40
+
41
+
42
+ def _key_from_env() -> SecretStr:
43
+ key = os.environ.get("SPECSTREAM_API_KEY", "").strip()
44
+ if not key:
45
+ raise ValueError(KEY_HELP)
46
+ return SecretStr(key)
47
+
48
+
49
+ def _cache_finished(_args: Any = None, result: Any = None) -> bool:
50
+ """Cache a list only once it is done; a running, vague or over-the-maximum answer should be asked again."""
51
+ try:
52
+ return json.loads(result).get("status") in FINISHED | STOPPED
53
+ except (TypeError, ValueError, AttributeError):
54
+ return False
55
+
56
+
57
+ def _never_cache(_args: Any = None, _result: Any = None) -> bool:
58
+ return False
59
+
60
+
61
+ class _SpecStreamTool(BaseTool):
62
+ api_key: SecretStr = Field(default_factory=_key_from_env, repr=False)
63
+ """A SpecStream API key. Read from SPECSTREAM_API_KEY when not passed."""
64
+ base_url: str = DEFAULT_BASE_URL
65
+ env_vars: list[EnvVar] = Field(
66
+ default_factory=lambda: [
67
+ EnvVar(name="SPECSTREAM_API_KEY", description="SpecStream API key (Agents & API in your workspace)", required=True)
68
+ ]
69
+ )
70
+
71
+ @field_validator("api_key", mode="after")
72
+ @classmethod
73
+ def _key_is_not_empty(cls, value: SecretStr) -> SecretStr:
74
+ if not value.get_secret_value().strip():
75
+ raise ValueError(KEY_HELP)
76
+ return value
77
+
78
+ def _api(self) -> SpecStreamAPI:
79
+ return SpecStreamAPI(self.api_key.get_secret_value(), self.base_url)
80
+
81
+
82
+ class SpecStreamFindListTool(_SpecStreamTool):
83
+ """Ask for a list in plain words and get every matching row, each with the page it was read from.
84
+
85
+ The list starts only if its price is within ``max_price_usd``, which you set here, in code. The model
86
+ chooses the request and how many rows; it can't raise the price ceiling.
87
+
88
+ Example:
89
+ .. code-block:: python
90
+
91
+ from crewai_specstream import SpecStreamFindListTool
92
+
93
+ tool = SpecStreamFindListTool(max_price_usd=5)
94
+ """
95
+
96
+ name: str = "specstream_find_list"
97
+ description: str = (
98
+ "Find a list of real things on the live web from a plain-English request and get back every matching row, "
99
+ "each with the page it was read from. Use it when the answer is many things that meet conditions: companies "
100
+ "in a city, local businesses with a service, funding filings, open grants, tenders, clinical trials, "
101
+ "repositories, people in a role. For one fact or a summary of one page, use a search tool instead. Rows that "
102
+ "couldn't be confirmed are left out and aren't charged. "
103
+ "Returns JSON with status, list_id, list_link and rows (one object per match: its columns, source_url and "
104
+ 'checked_at). status "over_maximum" means nothing ran because the price was above the cap: ask for fewer rows '
105
+ 'or tell the user. status "needs_edit" means the request was too vague to price: add the place or the '
106
+ "conditions and call again. If the list is still running, call specstream_get_list_results with its list_id "
107
+ "for the rest."
108
+ )
109
+ args_schema: type[BaseModel] = FindListInput
110
+
111
+ max_price_usd: float = Field(gt=0)
112
+ """The most one list may cost, in US dollars. If the price is higher, nothing runs."""
113
+ wait_seconds: float = DEFAULT_WAIT_SECONDS
114
+ """How long to wait for the list to finish before returning the rows found so far."""
115
+ poll_interval: float = 3.0
116
+ locale: str = "en-US"
117
+
118
+ def __init__(self, **kwargs: Any) -> None:
119
+ kwargs.setdefault("cache_function", _cache_finished)
120
+ super().__init__(**kwargs)
121
+
122
+ def _run(self, request: str, max_results: int = 25) -> str:
123
+ result = self._api().find_list(
124
+ request,
125
+ max_results=max(1, min(int(max_results), MAX_RESULTS)),
126
+ max_price_usd=self.max_price_usd,
127
+ wait_seconds=self.wait_seconds,
128
+ poll_interval=self.poll_interval,
129
+ locale=self.locale,
130
+ )
131
+ return json.dumps(result, ensure_ascii=False, default=str)
132
+
133
+ async def _arun(self, request: str, max_results: int = 25) -> str:
134
+ return await asyncio.to_thread(self._run, request, max_results)
135
+
136
+
137
+ class SpecStreamGetListResultsTool(_SpecStreamTool):
138
+ """Read every row found so far for a list. Reading a list you already have costs nothing."""
139
+
140
+ name: str = "specstream_get_list_results"
141
+ description: str = (
142
+ "Read every row found so far for a SpecStream list, such as one that was still running. Use it with the "
143
+ "list_id from specstream_find_list. Reading is free. Returns JSON with status, list_id, list_link and rows, "
144
+ "each with its columns, source_url and checked_at."
145
+ )
146
+ args_schema: type[BaseModel] = GetListResultsInput
147
+
148
+ def __init__(self, **kwargs: Any) -> None:
149
+ kwargs.setdefault("cache_function", _never_cache)
150
+ super().__init__(**kwargs)
151
+
152
+ def _run(self, list_id: str) -> str:
153
+ return json.dumps(self._api().results(list_id.strip()), ensure_ascii=False, default=str)
154
+
155
+ async def _arun(self, list_id: str) -> str:
156
+ return await asyncio.to_thread(self._run, list_id)
157
+
158
+
159
+ def specstream_tools(max_price_usd: float, **kwargs: Any) -> list[BaseTool]:
160
+ """Both tools, sharing one key and base URL: the usual way to give an agent SpecStream."""
161
+ shared = {key: kwargs.pop(key) for key in ("api_key", "base_url") if key in kwargs}
162
+ return [SpecStreamFindListTool(max_price_usd=max_price_usd, **shared, **kwargs), SpecStreamGetListResultsTool(**shared)]
@@ -0,0 +1,49 @@
1
+ [project]
2
+ name = "crewai-specstream"
3
+ version = "0.1.0"
4
+ description = "Give a CrewAI agent any list from the live web: ask in plain words, get every matching row with the page it came from, within a price you set in code."
5
+ readme = "README.md"
6
+ requires-python = ">=3.10,<3.14"
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ authors = [{ name = "SpecStream", email = "support@specstream.ai" }]
10
+ maintainers = [{ name = "SpecStream", email = "support@specstream.ai" }]
11
+ keywords = ["crewai", "crewai-tools", "specstream", "agents", "tools", "web-data", "live-web", "lead-lists", "research"]
12
+ classifiers = [
13
+ "Development Status :: 4 - Beta",
14
+ "Intended Audience :: Developers",
15
+ "Operating System :: OS Independent",
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3 :: Only",
18
+ "Programming Language :: Python :: 3.10",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
23
+ "Topic :: Internet :: WWW/HTTP",
24
+ "Typing :: Typed",
25
+ ]
26
+ dependencies = ["crewai>=1.0.0,<2.0.0"]
27
+
28
+ [project.optional-dependencies]
29
+ test = ["pytest>=8"]
30
+
31
+ [project.urls]
32
+ Homepage = "https://specstream.ai"
33
+ Documentation = "https://specstream.ai/docs/crewai"
34
+ Repository = "https://github.com/Specstreamai/specstream-tools/tree/main/packages/crewai-specstream"
35
+ Issues = "https://github.com/Specstreamai/specstream-tools/issues"
36
+ Pricing = "https://specstream.ai/pricing"
37
+
38
+ [build-system]
39
+ requires = ["hatchling>=1.27,<2"]
40
+ build-backend = "hatchling.build"
41
+
42
+ [tool.hatch.build.targets.wheel]
43
+ packages = ["crewai_specstream"]
44
+
45
+ [tool.hatch.build.targets.sdist]
46
+ include = ["crewai_specstream", "tests", "README.md", "LICENSE"]
47
+
48
+ [tool.pytest.ini_options]
49
+ testpaths = ["tests"]
@@ -0,0 +1,342 @@
1
+ import asyncio
2
+ import io
3
+ import json
4
+ import urllib.error
5
+ import urllib.parse
6
+
7
+ import pytest
8
+ from pydantic import ValidationError
9
+
10
+ from crewai_specstream import (
11
+ SpecStreamError,
12
+ SpecStreamFindListTool,
13
+ SpecStreamGetListResultsTool,
14
+ specstream_tools,
15
+ )
16
+
17
+ KEY = "ss_live_test_key"
18
+
19
+
20
+ def cell(label, value, source=None):
21
+ provenance = {"source_url": source, "observed_at": "2026-10-14T08:00:00Z"} if source else None
22
+ return {"label": label, "value": value, "display": value, "absence": None, "provenance": provenance}
23
+
24
+
25
+ ROWS = [
26
+ {"ordinal": 1, "cells": [cell("Organization", "Clínica Sorriso", "https://sorriso.pt/marcacoes"), cell("Website", "https://sorriso.pt")]},
27
+ {"ordinal": 2, "cells": [cell("Organization", "Dentes de Lisboa", "https://dentesdelisboa.pt"), cell("Website", None) | {"absence": "Not published"}]},
28
+ ]
29
+
30
+
31
+ class FakeSpecStream:
32
+ """Answers like the SpecStream API: the request, its quote, the run, then rows over two polls and two pages."""
33
+
34
+ def __init__(self, maximum_cents=250, runnable=True, existing=None):
35
+ self.maximum_cents = maximum_cents
36
+ self.runnable = runnable
37
+ self.existing = existing
38
+ self.calls = []
39
+ self.polls = 0
40
+ self.misses = 0
41
+
42
+ def __call__(self, request, timeout=None):
43
+ url = urllib.parse.urlsplit(request.full_url)
44
+ body = json.loads(request.data) if request.data else None
45
+ self.calls.append((request.get_method(), url.path, body, dict(request.header_items())))
46
+ query = dict(urllib.parse.parse_qsl(url.query))
47
+ if url.path.startswith("/v1/capacity/requests/"):
48
+ if self.misses:
49
+ self.misses -= 1
50
+ raise urllib.error.HTTPError(request.full_url, 404, "Not Found", {}, io.BytesIO(b"{}"))
51
+ if self.existing:
52
+ return self.reply(self.existing)
53
+ raise urllib.error.HTTPError(request.full_url, 404, "Not Found", {}, io.BytesIO(b"{}"))
54
+ if url.path == "/v1/parse":
55
+ return self.reply({"status": "runnable" if self.runnable else "needs_input", "ast_hash": "a" * 64, "canonical_sentence": "25 dental clinics in Lisbon"})
56
+ if url.path == "/v1/capacity/quotes":
57
+ return self.reply({"quote_id": "cqt_1", "quote_hash": "b" * 64, "maximum_cents": self.maximum_cents})
58
+ if url.path == "/v1/capacity/executions":
59
+ return self.reply({"find_id": "fnd_1", "state": "running"})
60
+ if url.path == "/v1/finds/fnd_1/rows":
61
+ if query.get("cursor") == "page-2":
62
+ return self.reply({"status": "completed", "rows": ROWS[1:], "next_cursor": None})
63
+ self.polls += 1
64
+ if self.polls == 1:
65
+ return self.reply({"status": "running", "rows": [], "next_cursor": None})
66
+ return self.reply({"status": "completed", "rows": ROWS[:1], "next_cursor": "page-2"})
67
+ raise AssertionError(f"unexpected call {request.get_method()} {url.path}")
68
+
69
+ @staticmethod
70
+ def reply(data):
71
+ return io.BytesIO(json.dumps({"data": data}).encode())
72
+
73
+ def paths(self):
74
+ return [path for _, path, _, _ in self.calls]
75
+
76
+
77
+ @pytest.fixture
78
+ def api(monkeypatch):
79
+ def install(**kwargs):
80
+ fake = FakeSpecStream(**kwargs)
81
+ monkeypatch.setattr("urllib.request.urlopen", fake)
82
+ return fake
83
+
84
+ return install
85
+
86
+
87
+ def test_finds_a_list_within_the_maximum_and_returns_every_row(api):
88
+ fake = api()
89
+ tool = SpecStreamFindListTool(api_key=KEY, max_price_usd=5, poll_interval=0)
90
+ result = json.loads(tool.run(request="Dental clinics in Lisbon with online booking", max_results=25))
91
+
92
+ assert result["status"] == "completed"
93
+ assert result["row_count"] == 2
94
+ assert result["list_link"] == "https://specstream.ai/workspace/collections/fnd_1"
95
+ first, second = result["rows"]
96
+ assert first["Organization"] == "Clínica Sorriso"
97
+ assert first["source_url"] == "https://sorriso.pt/marcacoes"
98
+ assert first["checked_at"] == "2026-10-14T08:00:00Z"
99
+ assert second["Website"] == ""
100
+ run = next(body for method, path, body, _ in fake.calls if path == "/v1/capacity/executions")
101
+ assert run["confirm_max_cents"] == 250
102
+ assert run["idempotency_key"].startswith("crewai-")
103
+
104
+
105
+ def test_the_result_is_a_json_string_the_agent_can_read(api):
106
+ api()
107
+ output = SpecStreamFindListTool(api_key=KEY, max_price_usd=5, poll_interval=0).run(request="Dental clinics in Lisbon")
108
+
109
+ assert isinstance(output, str)
110
+ assert "Clínica Sorriso" in output
111
+
112
+
113
+ def test_nothing_runs_when_the_price_is_above_the_maximum(api):
114
+ fake = api(maximum_cents=900)
115
+ result = json.loads(SpecStreamFindListTool(api_key=KEY, max_price_usd=5).run(request="Dental clinics in Lisbon"))
116
+
117
+ assert result["status"] == "over_maximum"
118
+ assert "$9.00" in result["message"] and "$5.00" in result["message"]
119
+ assert "/v1/capacity/executions" not in fake.paths()
120
+
121
+
122
+ def test_an_unclear_request_comes_back_with_how_it_was_read(api):
123
+ fake = api(runnable=False)
124
+ result = json.loads(SpecStreamFindListTool(api_key=KEY, max_price_usd=5).run(request="clinics"))
125
+
126
+ assert result["status"] == "needs_edit"
127
+ assert "25 dental clinics in Lisbon" in result["message"]
128
+ assert "/v1/capacity/quotes" not in fake.paths()
129
+
130
+
131
+ def test_the_model_cannot_set_the_price():
132
+ tool = SpecStreamFindListTool(api_key=KEY, max_price_usd=2)
133
+ assert set(tool.args_schema.model_fields) == {"request", "max_results"}
134
+ assert "max_price_usd" not in json.dumps(tool.args_schema.model_json_schema())
135
+ assert "max_price_usd" not in tool.description
136
+
137
+
138
+ def test_the_price_cap_is_required_and_must_be_positive():
139
+ with pytest.raises(ValidationError):
140
+ SpecStreamFindListTool(api_key=KEY)
141
+ with pytest.raises(ValidationError):
142
+ SpecStreamFindListTool(api_key=KEY, max_price_usd=0)
143
+
144
+
145
+ def test_max_results_is_clamped_to_1_through_1000(api):
146
+ fake = api()
147
+ tool = SpecStreamFindListTool(api_key=KEY, max_price_usd=5, poll_interval=0)
148
+ units = []
149
+ for asked in (5000, 0, -3):
150
+ tool._run("Dental clinics in Lisbon", asked)
151
+ quote = [body for _, path, body, _ in fake.calls if path == "/v1/capacity/quotes"][-1]
152
+ units.append(quote["requested_units"])
153
+ fake.polls = 0
154
+
155
+ assert units == [1000, 1, 1]
156
+
157
+
158
+ def test_the_schema_shows_the_model_the_same_bounds():
159
+ field = SpecStreamFindListTool(api_key=KEY, max_price_usd=5).args_schema.model_json_schema()["properties"]["max_results"]
160
+ assert field["minimum"] == 1 and field["maximum"] == 1000 and field["default"] == 25
161
+
162
+
163
+ def test_a_retried_step_reuses_the_run_it_already_started(api):
164
+ fake = api(existing={"find_id": "fnd_1", "maximum_cents": 250})
165
+ result = json.loads(SpecStreamFindListTool(api_key=KEY, max_price_usd=5, poll_interval=0).run(request="Dental clinics in Lisbon"))
166
+
167
+ assert result["row_count"] == 2
168
+ assert "/v1/parse" not in fake.paths() and "/v1/capacity/executions" not in fake.paths()
169
+
170
+
171
+ def test_a_retry_after_the_turn_of_the_hour_reuses_the_run_from_the_hour_before(api):
172
+ fake = api(existing={"find_id": "fnd_1", "maximum_cents": 250})
173
+ fake.misses = 1
174
+ result = json.loads(SpecStreamFindListTool(api_key=KEY, max_price_usd=5, poll_interval=0).run(request="Dental clinics in Lisbon"))
175
+
176
+ lookups = [path for path in fake.paths() if path.startswith("/v1/capacity/requests/")]
177
+ assert len(lookups) == 2 and lookups[0] != lookups[1]
178
+ assert result["row_count"] == 2
179
+ assert "/v1/capacity/executions" not in fake.paths()
180
+
181
+
182
+ def test_a_list_still_running_points_to_the_free_read(api):
183
+ api()
184
+ result = json.loads(SpecStreamFindListTool(api_key=KEY, max_price_usd=5, wait_seconds=0).run(request="Dental clinics in Lisbon"))
185
+
186
+ assert result["status"] == "running"
187
+ assert "specstream_get_list_results" in result["message"]
188
+
189
+
190
+ def test_reading_results_follows_every_page(api):
191
+ fake = api()
192
+ fake.polls = 1
193
+ result = json.loads(SpecStreamGetListResultsTool(api_key=KEY).run(list_id="fnd_1"))
194
+
195
+ assert [row["position"] for row in result["rows"]] == [1, 2]
196
+ assert result["row_count"] == 2
197
+ pages = [path for path in fake.paths() if path == "/v1/finds/fnd_1/rows"]
198
+ assert len(pages) == 2
199
+
200
+
201
+ def test_reading_results_costs_nothing(api):
202
+ fake = api()
203
+ fake.polls = 1
204
+ SpecStreamGetListResultsTool(api_key=KEY).run(list_id="fnd_1")
205
+
206
+ assert all(method == "GET" for method, _, _, _ in fake.calls)
207
+
208
+
209
+ def test_the_key_goes_in_the_authorization_header_and_never_in_the_result(api):
210
+ fake = api()
211
+ tool = SpecStreamFindListTool(api_key=KEY, max_price_usd=5, poll_interval=0)
212
+ output = tool.run(request="Dental clinics in Lisbon")
213
+
214
+ headers = fake.calls[0][3]
215
+ assert headers["Authorization"] == f"Bearer {KEY}"
216
+ assert headers["User-agent"].startswith("crewai-specstream/")
217
+ assert KEY not in output
218
+ assert KEY not in repr(tool) and KEY not in str(tool)
219
+ assert KEY not in str(tool.model_dump(exclude={"args_schema", "cache_function"}))
220
+
221
+
222
+ def test_the_key_is_read_from_the_environment(api, monkeypatch):
223
+ fake = api()
224
+ monkeypatch.setenv("SPECSTREAM_API_KEY", "ss_live_from_env")
225
+ SpecStreamGetListResultsTool().run(list_id="fnd_1")
226
+
227
+ assert fake.calls[0][3]["Authorization"] == "Bearer ss_live_from_env"
228
+
229
+
230
+ def test_a_missing_key_says_where_to_get_one(monkeypatch):
231
+ monkeypatch.delenv("SPECSTREAM_API_KEY", raising=False)
232
+ with pytest.raises(ValueError, match="SPECSTREAM_API_KEY"):
233
+ SpecStreamFindListTool(max_price_usd=5)
234
+ with pytest.raises(ValueError, match="Agents & API"):
235
+ SpecStreamGetListResultsTool()
236
+ with pytest.raises(ValueError, match="SPECSTREAM_API_KEY"):
237
+ SpecStreamGetListResultsTool(api_key=" ")
238
+
239
+
240
+ def test_a_refused_call_raises_with_the_reason(api, monkeypatch):
241
+ def refuse(request, timeout=None):
242
+ raise urllib.error.HTTPError(request.full_url, 401, "Unauthorized", {}, io.BytesIO(b'{"error": {"message": "Bad key"}}'))
243
+
244
+ monkeypatch.setattr("urllib.request.urlopen", refuse)
245
+ with pytest.raises(SpecStreamError, match="401: Bad key"):
246
+ SpecStreamGetListResultsTool(api_key=KEY).run(list_id="fnd_1")
247
+
248
+
249
+ def test_both_tools_share_the_key_and_the_cap(api):
250
+ find, results = specstream_tools(max_price_usd=5, api_key=KEY, wait_seconds=60)
251
+ assert find.name == "specstream_find_list" and results.name == "specstream_get_list_results"
252
+ assert find.max_price_usd == 5 and find.wait_seconds == 60
253
+ assert results.api_key.get_secret_value() == KEY
254
+
255
+
256
+ def test_the_tools_declare_their_environment_variable():
257
+ for tool in specstream_tools(max_price_usd=5, api_key=KEY):
258
+ assert [(var.name, var.required) for var in tool.env_vars] == [("SPECSTREAM_API_KEY", True)]
259
+
260
+
261
+ def test_an_agent_calls_the_tool_through_its_structured_form(api):
262
+ api()
263
+ find, _ = specstream_tools(max_price_usd=5, api_key=KEY, poll_interval=0)
264
+ structured = find.to_structured_tool()
265
+ result = json.loads(structured.invoke({"request": "Dental clinics in Lisbon", "max_results": 10}))
266
+
267
+ assert structured.name == "specstream_find_list"
268
+ assert result["row_count"] == 2
269
+
270
+
271
+ def test_the_tools_run_without_blocking_an_event_loop(api):
272
+ api()
273
+ find, results = specstream_tools(max_price_usd=5, api_key=KEY, poll_interval=0)
274
+
275
+ async def go():
276
+ found = json.loads(await find._arun("Dental clinics in Lisbon", 25))
277
+ again = json.loads(await results._arun("fnd_1"))
278
+ return found, again
279
+
280
+ found, again = asyncio.run(go())
281
+ assert found["row_count"] == 2 and again["row_count"] == 2
282
+
283
+
284
+ def test_only_a_finished_list_is_cached():
285
+ find = SpecStreamFindListTool(api_key=KEY, max_price_usd=5)
286
+ done = json.dumps({"status": "completed"})
287
+ for waiting in (json.dumps({"status": "running"}), json.dumps({"status": "over_maximum"}), json.dumps({"status": "needs_edit"}), "not json"):
288
+ assert find.cache_function({}, waiting) is False
289
+ assert find.cache_function({}, done) is True
290
+ assert SpecStreamGetListResultsTool(api_key=KEY).cache_function({}, done) is False
291
+
292
+
293
+ def test_an_agent_accepts_both_tools():
294
+ from crewai import LLM, Agent
295
+
296
+ agent = Agent(
297
+ role="Researcher",
298
+ goal="Find lists",
299
+ backstory="Finds lists.",
300
+ tools=specstream_tools(max_price_usd=5, api_key=KEY),
301
+ llm=LLM(model="gpt-4o-mini", api_key="sk-test"),
302
+ )
303
+ assert [tool.name for tool in agent.tools] == ["specstream_find_list", "specstream_get_list_results"]
304
+
305
+
306
+ SCRIPTED = []
307
+ SEEN = []
308
+
309
+
310
+ def test_a_crew_finds_a_list_end_to_end_with_a_scripted_model(api):
311
+ """A real Agent, Task and Crew run the agent loop; only the model's replies are scripted."""
312
+ from crewai import Agent, BaseLLM, Crew, Task
313
+
314
+ class Scripted(BaseLLM):
315
+ def call(self, messages, tools=None, callbacks=None, available_functions=None, **kwargs):
316
+ SEEN.append(messages)
317
+ return SCRIPTED.pop(0)
318
+
319
+ def supports_function_calling(self):
320
+ return False
321
+
322
+ def supports_stop_words(self):
323
+ return True
324
+
325
+ def get_context_window_size(self):
326
+ return 8000
327
+
328
+ fake = api()
329
+ SEEN.clear()
330
+ SCRIPTED[:] = [
331
+ 'Thought: I need the list.\nAction: specstream_find_list\nAction Input: {"request": "Dental clinics in Lisbon", "max_results": 10}',
332
+ "Thought: I have the rows.\nFinal Answer: Found 2 clinics.",
333
+ ]
334
+ find, results = specstream_tools(max_price_usd=5, api_key=KEY, poll_interval=0)
335
+ agent = Agent(role="Researcher", goal="Find lists", backstory="Finds lists.", tools=[find, results], llm=Scripted(model="scripted"))
336
+ task = Task(description="Find dental clinics in Lisbon.", expected_output="A short answer.", agent=agent)
337
+ output = Crew(agents=[agent], tasks=[task], verbose=False).kickoff()
338
+
339
+ assert output.raw == "Found 2 clinics."
340
+ assert "Clínica Sorriso" in json.dumps(SEEN[-1], ensure_ascii=False)
341
+ assert KEY not in json.dumps(SEEN, ensure_ascii=False)
342
+ assert "/v1/capacity/executions" in fake.paths()