llama-index-tools-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.
- llama_index_tools_specstream-0.1.0/.gitignore +14 -0
- llama_index_tools_specstream-0.1.0/LICENSE +21 -0
- llama_index_tools_specstream-0.1.0/PKG-INFO +134 -0
- llama_index_tools_specstream-0.1.0/README.md +102 -0
- llama_index_tools_specstream-0.1.0/llama_index/tools/specstream/__init__.py +8 -0
- llama_index_tools_specstream-0.1.0/llama_index/tools/specstream/_api.py +206 -0
- llama_index_tools_specstream-0.1.0/llama_index/tools/specstream/base.py +116 -0
- llama_index_tools_specstream-0.1.0/llama_index/tools/specstream/py.typed +0 -0
- llama_index_tools_specstream-0.1.0/llama_index/tools/specstream/retriever.py +79 -0
- llama_index_tools_specstream-0.1.0/pyproject.toml +49 -0
- llama_index_tools_specstream-0.1.0/tests/test_specstream.py +214 -0
|
@@ -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,134 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: llama-index-tools-specstream
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Give a LlamaIndex 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/llamaindex
|
|
7
|
+
Project-URL: Repository, https://github.com/Specstreamai/specstream-tools/tree/main/packages/llama-index-tools-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,lead-lists,live-web,llama-index,llamaindex,research,retriever,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: <4.0,>=3.10
|
|
28
|
+
Requires-Dist: llama-index-core<0.15,>=0.13.0
|
|
29
|
+
Provides-Extra: test
|
|
30
|
+
Requires-Dist: pytest>=8; extra == 'test'
|
|
31
|
+
Description-Content-Type: text/markdown
|
|
32
|
+
|
|
33
|
+
# llama-index-tools-specstream
|
|
34
|
+
|
|
35
|
+
Give your LlamaIndex agent any list from the live web. Search tools hand an agent pages to read; SpecStream hands it the finished list. It asks in plain words – "dental clinics in Lisbon with online booking", "US startups that filed a $5M+ Form D this week" – 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 llama-index-tools-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).
|
|
43
|
+
|
|
44
|
+
## An agent that can find lists
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
from llama_index.core.agent.workflow import FunctionAgent
|
|
48
|
+
from llama_index.llms.anthropic import Anthropic
|
|
49
|
+
from llama_index.tools.specstream import SpecStreamToolSpec
|
|
50
|
+
|
|
51
|
+
agent = FunctionAgent(
|
|
52
|
+
tools=SpecStreamToolSpec(max_price_usd=5).to_tool_list(),
|
|
53
|
+
llm=Anthropic(model="claude-sonnet-5-5"),
|
|
54
|
+
)
|
|
55
|
+
response = await agent.run(
|
|
56
|
+
"Find US startups that raised $5M or more in a Form D filed after October 8, 2026. Which industries lead?"
|
|
57
|
+
)
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
The agent writes the request and picks how many rows. You decide what one list may cost.
|
|
61
|
+
|
|
62
|
+
## What comes back
|
|
63
|
+
|
|
64
|
+
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.
|
|
65
|
+
|
|
66
|
+
```json
|
|
67
|
+
{
|
|
68
|
+
"list_id": "fnd_gk5y3d0r97bvyz0t08zzh75kr6",
|
|
69
|
+
"position": 26,
|
|
70
|
+
"Organization": "RapidCanvas Inc",
|
|
71
|
+
"Published address": "801 BARTON SPRINGS RD, AUSTIN, TEXAS, 78704",
|
|
72
|
+
"Source industry classification": "Other Technology",
|
|
73
|
+
"Amount sold (USD)": "28999988",
|
|
74
|
+
"Funding filing date": "2026-10-14",
|
|
75
|
+
"source_url": "https://www.sec.gov/Archives/edgar/data/2052031/000205203126000006/primary_doc.xml",
|
|
76
|
+
"checked_at": "2026-10-14T19:56:02.016693Z",
|
|
77
|
+
"list_link": "https://specstream.ai/workspace/collections/fnd_gk5y3d0r97bvyz0t08zzh75kr6"
|
|
78
|
+
}
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
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.
|
|
82
|
+
|
|
83
|
+
## The two tools
|
|
84
|
+
|
|
85
|
+
| Tool | The model gives | What happens | Cost |
|
|
86
|
+
| --- | --- | --- | --- |
|
|
87
|
+
| `specstream_find_list` | `request`, `max_results` | 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 |
|
|
88
|
+
| `specstream_get_list_results` | `list_id` | Every row found so far, for a list that was still running | Free |
|
|
89
|
+
|
|
90
|
+
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.
|
|
91
|
+
|
|
92
|
+
Settings live on the spec, never in the tool schema:
|
|
93
|
+
|
|
94
|
+
```python
|
|
95
|
+
spec = SpecStreamToolSpec(
|
|
96
|
+
max_price_usd=20, # the most one list may cost
|
|
97
|
+
wait_seconds=600, # how long find_list waits before handing back what it has
|
|
98
|
+
locale="en-GB", # the language the requests are written in
|
|
99
|
+
)
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
## As a retriever
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
from llama_index.tools.specstream import SpecStreamRetriever
|
|
106
|
+
|
|
107
|
+
retriever = SpecStreamRetriever(max_price_usd=3, max_results=25)
|
|
108
|
+
nodes = retriever.retrieve("Breweries in Portland, Oregon that host events, with their website")
|
|
109
|
+
|
|
110
|
+
nodes[0].text # "Business location: Occidental Brewing Company\nPublished business website: http://occidentalbeers.com ..."
|
|
111
|
+
nodes[0].metadata["source_url"] # the page that row was read from
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
One node per row, its facts as text and its source in the metadata. The model sees each row with the page behind it, so a query engine can cite every claim; the list's bookkeeping stays out of the prompt and out of embeddings. Above the maximum, the retriever raises `SpecStreamError` and nothing runs.
|
|
115
|
+
|
|
116
|
+
## Money, plainly
|
|
117
|
+
|
|
118
|
+
- `max_price_usd` lives on the spec, in your code. The model never sees it and can't change it.
|
|
119
|
+
- You pay for rows that match. Candidates SpecStream couldn't confirm are left out and aren't billed.
|
|
120
|
+
- A retried step asking for the same list within the hour gets the list it already started, not a second bill.
|
|
121
|
+
- Rates and plans: [specstream.ai/pricing](https://specstream.ai/pricing).
|
|
122
|
+
|
|
123
|
+
## When to reach for it
|
|
124
|
+
|
|
125
|
+
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.
|
|
126
|
+
|
|
127
|
+
## More
|
|
128
|
+
|
|
129
|
+
- [SpecStream docs](https://specstream.ai/docs) and the [LlamaIndex page](https://specstream.ai/docs/llamaindex)
|
|
130
|
+
- Agents outside LlamaIndex: the [MCP server](https://specstream.ai/docs/mcp) at `https://api.specstream.ai/mcp`
|
|
131
|
+
- The [Python SDK](https://pypi.org/project/specstream-client/) for everything else in the API
|
|
132
|
+
- Questions: support@specstream.ai
|
|
133
|
+
|
|
134
|
+
MIT licensed. Made by [SpecStream](https://specstream.ai), the live web data engine for teams and agents.
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
# llama-index-tools-specstream
|
|
2
|
+
|
|
3
|
+
Give your LlamaIndex agent any list from the live web. Search tools hand an agent pages to read; SpecStream hands it the finished list. It asks in plain words – "dental clinics in Lisbon with online booking", "US startups that filed a $5M+ Form D this week" – 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 llama-index-tools-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).
|
|
11
|
+
|
|
12
|
+
## An agent that can find lists
|
|
13
|
+
|
|
14
|
+
```python
|
|
15
|
+
from llama_index.core.agent.workflow import FunctionAgent
|
|
16
|
+
from llama_index.llms.anthropic import Anthropic
|
|
17
|
+
from llama_index.tools.specstream import SpecStreamToolSpec
|
|
18
|
+
|
|
19
|
+
agent = FunctionAgent(
|
|
20
|
+
tools=SpecStreamToolSpec(max_price_usd=5).to_tool_list(),
|
|
21
|
+
llm=Anthropic(model="claude-sonnet-5-5"),
|
|
22
|
+
)
|
|
23
|
+
response = await agent.run(
|
|
24
|
+
"Find US startups that raised $5M or more in a Form D filed after October 8, 2026. Which industries lead?"
|
|
25
|
+
)
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
The agent writes the request and picks how many rows. You decide what one list may cost.
|
|
29
|
+
|
|
30
|
+
## What comes back
|
|
31
|
+
|
|
32
|
+
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.
|
|
33
|
+
|
|
34
|
+
```json
|
|
35
|
+
{
|
|
36
|
+
"list_id": "fnd_gk5y3d0r97bvyz0t08zzh75kr6",
|
|
37
|
+
"position": 26,
|
|
38
|
+
"Organization": "RapidCanvas Inc",
|
|
39
|
+
"Published address": "801 BARTON SPRINGS RD, AUSTIN, TEXAS, 78704",
|
|
40
|
+
"Source industry classification": "Other Technology",
|
|
41
|
+
"Amount sold (USD)": "28999988",
|
|
42
|
+
"Funding filing date": "2026-10-14",
|
|
43
|
+
"source_url": "https://www.sec.gov/Archives/edgar/data/2052031/000205203126000006/primary_doc.xml",
|
|
44
|
+
"checked_at": "2026-10-14T19:56:02.016693Z",
|
|
45
|
+
"list_link": "https://specstream.ai/workspace/collections/fnd_gk5y3d0r97bvyz0t08zzh75kr6"
|
|
46
|
+
}
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
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.
|
|
50
|
+
|
|
51
|
+
## The two tools
|
|
52
|
+
|
|
53
|
+
| Tool | The model gives | What happens | Cost |
|
|
54
|
+
| --- | --- | --- | --- |
|
|
55
|
+
| `specstream_find_list` | `request`, `max_results` | 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 |
|
|
56
|
+
| `specstream_get_list_results` | `list_id` | Every row found so far, for a list that was still running | Free |
|
|
57
|
+
|
|
58
|
+
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.
|
|
59
|
+
|
|
60
|
+
Settings live on the spec, never in the tool schema:
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
spec = SpecStreamToolSpec(
|
|
64
|
+
max_price_usd=20, # the most one list may cost
|
|
65
|
+
wait_seconds=600, # how long find_list waits before handing back what it has
|
|
66
|
+
locale="en-GB", # the language the requests are written in
|
|
67
|
+
)
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## As a retriever
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
from llama_index.tools.specstream import SpecStreamRetriever
|
|
74
|
+
|
|
75
|
+
retriever = SpecStreamRetriever(max_price_usd=3, max_results=25)
|
|
76
|
+
nodes = retriever.retrieve("Breweries in Portland, Oregon that host events, with their website")
|
|
77
|
+
|
|
78
|
+
nodes[0].text # "Business location: Occidental Brewing Company\nPublished business website: http://occidentalbeers.com ..."
|
|
79
|
+
nodes[0].metadata["source_url"] # the page that row was read from
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
One node per row, its facts as text and its source in the metadata. The model sees each row with the page behind it, so a query engine can cite every claim; the list's bookkeeping stays out of the prompt and out of embeddings. Above the maximum, the retriever raises `SpecStreamError` and nothing runs.
|
|
83
|
+
|
|
84
|
+
## Money, plainly
|
|
85
|
+
|
|
86
|
+
- `max_price_usd` lives on the spec, in your code. The model never sees it and can't change it.
|
|
87
|
+
- You pay for rows that match. Candidates SpecStream couldn't confirm are left out and aren't billed.
|
|
88
|
+
- A retried step asking for the same list within the hour gets the list it already started, not a second bill.
|
|
89
|
+
- Rates and plans: [specstream.ai/pricing](https://specstream.ai/pricing).
|
|
90
|
+
|
|
91
|
+
## When to reach for it
|
|
92
|
+
|
|
93
|
+
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.
|
|
94
|
+
|
|
95
|
+
## More
|
|
96
|
+
|
|
97
|
+
- [SpecStream docs](https://specstream.ai/docs) and the [LlamaIndex page](https://specstream.ai/docs/llamaindex)
|
|
98
|
+
- Agents outside LlamaIndex: the [MCP server](https://specstream.ai/docs/mcp) at `https://api.specstream.ai/mcp`
|
|
99
|
+
- The [Python SDK](https://pypi.org/project/specstream-client/) for everything else in the API
|
|
100
|
+
- Questions: support@specstream.ai
|
|
101
|
+
|
|
102
|
+
MIT licensed. Made by [SpecStream](https://specstream.ai), the live web data engine for teams and agents.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""SpecStream for LlamaIndex: any list from the live web, every row with its source, within a price set in code."""
|
|
2
|
+
|
|
3
|
+
from llama_index.tools.specstream._api import SpecStreamError
|
|
4
|
+
from llama_index.tools.specstream.base import SpecStreamToolSpec
|
|
5
|
+
from llama_index.tools.specstream.retriever import SpecStreamRetriever
|
|
6
|
+
|
|
7
|
+
__all__ = ["SpecStreamError", "SpecStreamRetriever", "SpecStreamToolSpec"]
|
|
8
|
+
__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 = "llama-index-tools-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 = "llamaindex",
|
|
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}"
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""The SpecStream tool spec: any list from the live web for a LlamaIndex agent, within a price set in code."""
|
|
2
|
+
|
|
3
|
+
# No `from __future__ import annotations`: LlamaIndex reads these signatures at runtime to build the tool schema.
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
from typing import Annotated, Optional
|
|
7
|
+
|
|
8
|
+
from llama_index.core.tools.tool_spec.base import BaseToolSpec
|
|
9
|
+
from pydantic import Field
|
|
10
|
+
|
|
11
|
+
from llama_index.tools.specstream._api import DEFAULT_BASE_URL, DEFAULT_WAIT_SECONDS, SpecStreamAPI
|
|
12
|
+
|
|
13
|
+
MAX_RESULTS = 1000
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _api(api_key: Optional[str], base_url: str) -> SpecStreamAPI:
|
|
17
|
+
return SpecStreamAPI(api_key=api_key or os.environ.get("SPECSTREAM_API_KEY", ""), base_url=base_url)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class SpecStreamToolSpec(BaseToolSpec):
|
|
21
|
+
"""Two tools that let an agent find a list on the live web and read its rows.
|
|
22
|
+
|
|
23
|
+
The price cap is set here, in code, and is not a tool argument, so the model can't raise it.
|
|
24
|
+
|
|
25
|
+
Example:
|
|
26
|
+
.. code-block:: python
|
|
27
|
+
|
|
28
|
+
from llama_index.core.agent.workflow import FunctionAgent
|
|
29
|
+
from llama_index.tools.specstream import SpecStreamToolSpec
|
|
30
|
+
|
|
31
|
+
tools = SpecStreamToolSpec(max_price_usd=5).to_tool_list()
|
|
32
|
+
agent = FunctionAgent(tools=tools, llm=llm)
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
spec_functions = ["specstream_find_list", "specstream_get_list_results"]
|
|
36
|
+
|
|
37
|
+
def __init__(
|
|
38
|
+
self,
|
|
39
|
+
*,
|
|
40
|
+
max_price_usd: float,
|
|
41
|
+
api_key: Optional[str] = None,
|
|
42
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
43
|
+
wait_seconds: float = DEFAULT_WAIT_SECONDS,
|
|
44
|
+
poll_interval: float = 3.0,
|
|
45
|
+
locale: str = "en-US",
|
|
46
|
+
) -> None:
|
|
47
|
+
"""
|
|
48
|
+
Args:
|
|
49
|
+
max_price_usd: The most one list may cost, in US dollars. Above it, nothing runs and the tool returns the price.
|
|
50
|
+
api_key: A SpecStream API key. Defaults to the SPECSTREAM_API_KEY environment variable.
|
|
51
|
+
base_url: The SpecStream API address.
|
|
52
|
+
wait_seconds: How long find_list waits for the list before returning the rows found so far.
|
|
53
|
+
poll_interval: Seconds between checks while a list is running.
|
|
54
|
+
locale: The language and region the request is written in.
|
|
55
|
+
"""
|
|
56
|
+
if not max_price_usd or float(max_price_usd) <= 0:
|
|
57
|
+
raise ValueError("max_price_usd must be greater than 0.")
|
|
58
|
+
self.max_price_usd = float(max_price_usd)
|
|
59
|
+
self.wait_seconds = wait_seconds
|
|
60
|
+
self.poll_interval = poll_interval
|
|
61
|
+
self.locale = locale
|
|
62
|
+
self._client = _api(api_key, base_url)
|
|
63
|
+
if not self._client.api_key.strip():
|
|
64
|
+
raise ValueError("Set SPECSTREAM_API_KEY or pass api_key. Create a key under Agents & API in your SpecStream workspace.")
|
|
65
|
+
|
|
66
|
+
def specstream_find_list(
|
|
67
|
+
self,
|
|
68
|
+
request: Annotated[
|
|
69
|
+
str,
|
|
70
|
+
Field(
|
|
71
|
+
description=(
|
|
72
|
+
"The list in plain words: what to find, where, what every row must meet, and the facts to bring back. "
|
|
73
|
+
'Example: "Dental clinics in Lisbon with online booking, with their website and phone".'
|
|
74
|
+
)
|
|
75
|
+
),
|
|
76
|
+
],
|
|
77
|
+
max_results: Annotated[
|
|
78
|
+
int,
|
|
79
|
+
Field(description="How many rows to find, from 1 to 1000. Ask for what the task needs; the price grows with the matches."),
|
|
80
|
+
] = 25,
|
|
81
|
+
) -> str:
|
|
82
|
+
"""Find a list of real things on the live web and return every matching row, each with the page it was read from.
|
|
83
|
+
|
|
84
|
+
Use it when the answer is many things that meet conditions: companies in a city, local businesses with a service,
|
|
85
|
+
funding filings, open grants, tenders, clinical trials, repositories, people in a role. For one fact or a summary
|
|
86
|
+
of one page, use a search tool instead. Rows that couldn't be confirmed are left out and aren't charged.
|
|
87
|
+
|
|
88
|
+
Returns JSON with status, list_id, list_link and rows (one object per match: its columns, source_url and
|
|
89
|
+
checked_at). status "over_maximum" means nothing ran because the price was above the cap: ask for fewer rows or
|
|
90
|
+
tell the user. status "needs_edit" means the request was too vague to price: add the place or the conditions.
|
|
91
|
+
If the list is still running, call specstream_get_list_results with its list_id for the rest.
|
|
92
|
+
"""
|
|
93
|
+
count = max(1, min(int(max_results), MAX_RESULTS))
|
|
94
|
+
result = self._client.find_list(
|
|
95
|
+
request,
|
|
96
|
+
max_results=count,
|
|
97
|
+
max_price_usd=self.max_price_usd,
|
|
98
|
+
wait_seconds=self.wait_seconds,
|
|
99
|
+
poll_interval=self.poll_interval,
|
|
100
|
+
locale=self.locale,
|
|
101
|
+
key_prefix="llamaindex",
|
|
102
|
+
)
|
|
103
|
+
return json.dumps(result, ensure_ascii=False)
|
|
104
|
+
|
|
105
|
+
def specstream_get_list_results(
|
|
106
|
+
self,
|
|
107
|
+
list_id: Annotated[
|
|
108
|
+
str,
|
|
109
|
+
Field(description='The list_id that specstream_find_list returned, like "fnd_gk5y3d0r97bvyz0t08zzh75kr6".'),
|
|
110
|
+
],
|
|
111
|
+
) -> str:
|
|
112
|
+
"""Read every row found so far for a SpecStream list, such as one that was still running. Reading is free.
|
|
113
|
+
|
|
114
|
+
Returns JSON with status, list_id, list_link and rows, each with its columns, source_url and checked_at.
|
|
115
|
+
"""
|
|
116
|
+
return json.dumps(self._client.results(list_id.strip()), ensure_ascii=False)
|
|
File without changes
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""A retriever whose nodes are the rows of a SpecStream list."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, List, Optional
|
|
6
|
+
|
|
7
|
+
from llama_index.core.retrievers import BaseRetriever
|
|
8
|
+
from llama_index.core.schema import NodeWithScore, QueryBundle, TextNode
|
|
9
|
+
|
|
10
|
+
from llama_index.tools.specstream._api import DEFAULT_BASE_URL, DEFAULT_WAIT_SECONDS, SpecStreamError
|
|
11
|
+
from llama_index.tools.specstream.base import MAX_RESULTS, _api
|
|
12
|
+
|
|
13
|
+
# Row fields that say where the row came from rather than what it says.
|
|
14
|
+
_META = ("list_id", "list_link", "position", "source_url", "checked_at")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class SpecStreamRetriever(BaseRetriever):
|
|
18
|
+
"""Turn a plain-English request into nodes, one per matching row, with its source in the metadata.
|
|
19
|
+
|
|
20
|
+
Example:
|
|
21
|
+
.. code-block:: python
|
|
22
|
+
|
|
23
|
+
from llama_index.tools.specstream import SpecStreamRetriever
|
|
24
|
+
|
|
25
|
+
retriever = SpecStreamRetriever(max_price_usd=3, max_results=25)
|
|
26
|
+
nodes = retriever.retrieve("Breweries in Portland, Oregon that host events, with their website")
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
def __init__(
|
|
30
|
+
self,
|
|
31
|
+
*,
|
|
32
|
+
max_price_usd: float,
|
|
33
|
+
max_results: int = 25,
|
|
34
|
+
api_key: Optional[str] = None,
|
|
35
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
36
|
+
wait_seconds: float = DEFAULT_WAIT_SECONDS,
|
|
37
|
+
poll_interval: float = 3.0,
|
|
38
|
+
locale: str = "en-US",
|
|
39
|
+
**kwargs: Any,
|
|
40
|
+
) -> None:
|
|
41
|
+
if not max_price_usd or float(max_price_usd) <= 0:
|
|
42
|
+
raise ValueError("max_price_usd must be greater than 0.")
|
|
43
|
+
if not 1 <= int(max_results) <= MAX_RESULTS:
|
|
44
|
+
raise ValueError(f"max_results must be from 1 to {MAX_RESULTS}.")
|
|
45
|
+
self.max_price_usd = float(max_price_usd)
|
|
46
|
+
self.max_results = int(max_results)
|
|
47
|
+
self.wait_seconds = wait_seconds
|
|
48
|
+
self.poll_interval = poll_interval
|
|
49
|
+
self.locale = locale
|
|
50
|
+
self._client = _api(api_key, base_url)
|
|
51
|
+
if not self._client.api_key.strip():
|
|
52
|
+
raise ValueError("Set SPECSTREAM_API_KEY or pass api_key. Create a key under Agents & API in your SpecStream workspace.")
|
|
53
|
+
super().__init__(**kwargs)
|
|
54
|
+
|
|
55
|
+
def _retrieve(self, query_bundle: QueryBundle) -> List[NodeWithScore]:
|
|
56
|
+
result = self._client.find_list(
|
|
57
|
+
query_bundle.query_str,
|
|
58
|
+
max_results=self.max_results,
|
|
59
|
+
max_price_usd=self.max_price_usd,
|
|
60
|
+
wait_seconds=self.wait_seconds,
|
|
61
|
+
poll_interval=self.poll_interval,
|
|
62
|
+
locale=self.locale,
|
|
63
|
+
key_prefix="llamaindex-retriever",
|
|
64
|
+
)
|
|
65
|
+
if result["status"] in ("needs_edit", "over_maximum"):
|
|
66
|
+
raise SpecStreamError(result["message"])
|
|
67
|
+
nodes = []
|
|
68
|
+
for row in result["rows"]:
|
|
69
|
+
facts = "\n".join(f"{label}: {value}" for label, value in row.items() if label not in _META and value not in ("", None))
|
|
70
|
+
node = TextNode(
|
|
71
|
+
id_=f"{row['list_id']}:{row['position']}",
|
|
72
|
+
text=facts,
|
|
73
|
+
metadata={key: row.get(key) for key in _META} | {"request": result.get("request")},
|
|
74
|
+
# The model sees each row's facts and the page behind them; the bookkeeping stays out of its prompt.
|
|
75
|
+
excluded_llm_metadata_keys=["list_id", "list_link", "position", "request"],
|
|
76
|
+
excluded_embed_metadata_keys=list(_META) + ["request"],
|
|
77
|
+
)
|
|
78
|
+
nodes.append(NodeWithScore(node=node, score=None))
|
|
79
|
+
return nodes
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "llama-index-tools-specstream"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Give a LlamaIndex 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,<4.0"
|
|
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 = ["llama-index", "llamaindex", "specstream", "agents", "tools", "retriever", "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 = ["llama-index-core>=0.13.0,<0.15"]
|
|
27
|
+
|
|
28
|
+
[project.optional-dependencies]
|
|
29
|
+
test = ["pytest>=8"]
|
|
30
|
+
|
|
31
|
+
[project.urls]
|
|
32
|
+
Homepage = "https://specstream.ai"
|
|
33
|
+
Documentation = "https://specstream.ai/docs/llamaindex"
|
|
34
|
+
Repository = "https://github.com/Specstreamai/specstream-tools/tree/main/packages/llama-index-tools-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 = ["llama_index"]
|
|
44
|
+
|
|
45
|
+
[tool.hatch.build.targets.sdist]
|
|
46
|
+
include = ["llama_index", "tests", "README.md", "LICENSE"]
|
|
47
|
+
|
|
48
|
+
[tool.pytest.ini_options]
|
|
49
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
import io
|
|
2
|
+
import json
|
|
3
|
+
import urllib.error
|
|
4
|
+
import urllib.parse
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
|
|
8
|
+
from llama_index.tools.specstream import SpecStreamError, SpecStreamRetriever, SpecStreamToolSpec
|
|
9
|
+
|
|
10
|
+
KEY = "ss_live_test_key"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def cell(label, value, source=None):
|
|
14
|
+
provenance = {"source_url": source, "observed_at": "2026-10-14T08:00:00Z"} if source else None
|
|
15
|
+
return {"label": label, "value": value, "display": value, "absence": None, "provenance": provenance}
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
ROWS = [
|
|
19
|
+
{"ordinal": 1, "cells": [cell("Organization", "Clínica Sorriso", "https://sorriso.pt/marcacoes"), cell("Website", "https://sorriso.pt")]},
|
|
20
|
+
{"ordinal": 2, "cells": [cell("Organization", "Dentes de Lisboa", "https://dentesdelisboa.pt"), cell("Website", None) | {"absence": "Not published"}]},
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class FakeSpecStream:
|
|
25
|
+
"""Answers like the SpecStream API: the request, its quote, the run, then rows over two polls and two pages."""
|
|
26
|
+
|
|
27
|
+
def __init__(self, maximum_cents=250, runnable=True, existing=None):
|
|
28
|
+
self.maximum_cents = maximum_cents
|
|
29
|
+
self.runnable = runnable
|
|
30
|
+
self.existing = existing
|
|
31
|
+
self.calls = []
|
|
32
|
+
self.polls = 0
|
|
33
|
+
self.misses = 0
|
|
34
|
+
|
|
35
|
+
def __call__(self, request, timeout=None):
|
|
36
|
+
url = urllib.parse.urlsplit(request.full_url)
|
|
37
|
+
body = json.loads(request.data) if request.data else None
|
|
38
|
+
self.calls.append((request.get_method(), url.path, body, dict(request.header_items())))
|
|
39
|
+
query = dict(urllib.parse.parse_qsl(url.query))
|
|
40
|
+
if url.path.startswith("/v1/capacity/requests/"):
|
|
41
|
+
if self.misses:
|
|
42
|
+
self.misses -= 1
|
|
43
|
+
raise urllib.error.HTTPError(request.full_url, 404, "Not Found", {}, io.BytesIO(b"{}"))
|
|
44
|
+
if self.existing:
|
|
45
|
+
return self.reply(self.existing)
|
|
46
|
+
raise urllib.error.HTTPError(request.full_url, 404, "Not Found", {}, io.BytesIO(b"{}"))
|
|
47
|
+
if url.path == "/v1/parse":
|
|
48
|
+
return self.reply({"status": "runnable" if self.runnable else "needs_input", "ast_hash": "a" * 64, "canonical_sentence": "25 dental clinics in Lisbon"})
|
|
49
|
+
if url.path == "/v1/capacity/quotes":
|
|
50
|
+
return self.reply({"quote_id": "cqt_1", "quote_hash": "b" * 64, "maximum_cents": self.maximum_cents})
|
|
51
|
+
if url.path == "/v1/capacity/executions":
|
|
52
|
+
return self.reply({"find_id": "fnd_1", "state": "running"})
|
|
53
|
+
if url.path == "/v1/finds/fnd_1/rows":
|
|
54
|
+
if query.get("cursor") == "page-2":
|
|
55
|
+
return self.reply({"status": "completed", "rows": ROWS[1:], "next_cursor": None})
|
|
56
|
+
self.polls += 1
|
|
57
|
+
if self.polls == 1:
|
|
58
|
+
return self.reply({"status": "running", "rows": [], "next_cursor": None})
|
|
59
|
+
return self.reply({"status": "completed", "rows": ROWS[:1], "next_cursor": "page-2"})
|
|
60
|
+
raise AssertionError(f"unexpected call {request.get_method()} {url.path}")
|
|
61
|
+
|
|
62
|
+
@staticmethod
|
|
63
|
+
def reply(data):
|
|
64
|
+
return io.BytesIO(json.dumps({"data": data}).encode())
|
|
65
|
+
|
|
66
|
+
def paths(self):
|
|
67
|
+
return [path for _, path, _, _ in self.calls]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@pytest.fixture
|
|
71
|
+
def api(monkeypatch):
|
|
72
|
+
def install(**kwargs):
|
|
73
|
+
fake = FakeSpecStream(**kwargs)
|
|
74
|
+
monkeypatch.setattr("urllib.request.urlopen", fake)
|
|
75
|
+
return fake
|
|
76
|
+
|
|
77
|
+
return install
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def tools(**kwargs):
|
|
81
|
+
spec = SpecStreamToolSpec(api_key=KEY, max_price_usd=kwargs.pop("max_price_usd", 5), poll_interval=0, **kwargs)
|
|
82
|
+
return {tool.metadata.name: tool for tool in spec.to_tool_list()}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def test_finds_a_list_within_the_maximum_and_returns_every_row(api):
|
|
86
|
+
fake = api()
|
|
87
|
+
output = tools()["specstream_find_list"](request="Dental clinics in Lisbon with online booking", max_results=25)
|
|
88
|
+
result = json.loads(output.content)
|
|
89
|
+
|
|
90
|
+
assert result["status"] == "completed"
|
|
91
|
+
assert result["row_count"] == 2
|
|
92
|
+
assert result["list_link"] == "https://specstream.ai/workspace/collections/fnd_1"
|
|
93
|
+
first, second = result["rows"]
|
|
94
|
+
assert first["Organization"] == "Clínica Sorriso"
|
|
95
|
+
assert first["source_url"] == "https://sorriso.pt/marcacoes"
|
|
96
|
+
assert second["Website"] == ""
|
|
97
|
+
run = next(body for method, path, body, _ in fake.calls if path == "/v1/capacity/executions")
|
|
98
|
+
assert run["confirm_max_cents"] == 250
|
|
99
|
+
assert run["idempotency_key"].startswith("llamaindex-")
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def test_nothing_runs_when_the_price_is_above_the_maximum(api):
|
|
103
|
+
fake = api(maximum_cents=900)
|
|
104
|
+
result = json.loads(tools()["specstream_find_list"](request="Dental clinics in Lisbon").content)
|
|
105
|
+
|
|
106
|
+
assert result["status"] == "over_maximum"
|
|
107
|
+
assert "$9.00" in result["message"] and "$5.00" in result["message"]
|
|
108
|
+
assert "/v1/capacity/executions" not in fake.paths()
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def test_an_unclear_request_comes_back_with_how_it_was_read(api):
|
|
112
|
+
fake = api(runnable=False)
|
|
113
|
+
result = json.loads(tools()["specstream_find_list"](request="clinics").content)
|
|
114
|
+
|
|
115
|
+
assert result["status"] == "needs_edit"
|
|
116
|
+
assert "25 dental clinics in Lisbon" in result["message"]
|
|
117
|
+
assert "/v1/capacity/quotes" not in fake.paths()
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def test_the_model_sees_two_tools_and_cannot_set_the_price():
|
|
121
|
+
found = tools()
|
|
122
|
+
assert set(found) == {"specstream_find_list", "specstream_get_list_results"}
|
|
123
|
+
schema = found["specstream_find_list"].metadata.get_parameters_dict()
|
|
124
|
+
assert set(schema["properties"]) == {"request", "max_results"}
|
|
125
|
+
assert schema["required"] == ["request"]
|
|
126
|
+
assert "live web" in found["specstream_find_list"].metadata.description
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def test_max_results_is_held_to_what_one_list_can_hold(api):
|
|
130
|
+
fake = api()
|
|
131
|
+
tools()["specstream_find_list"](request="Dental clinics in Lisbon", max_results=50000)
|
|
132
|
+
quote = next(body for method, path, body, _ in fake.calls if path == "/v1/capacity/quotes")
|
|
133
|
+
assert quote["requested_units"] == 1000
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def test_a_retried_step_reuses_the_run_it_already_started(api):
|
|
137
|
+
fake = api(existing={"find_id": "fnd_1", "maximum_cents": 250})
|
|
138
|
+
result = json.loads(tools()["specstream_find_list"](request="Dental clinics in Lisbon").content)
|
|
139
|
+
|
|
140
|
+
assert result["row_count"] == 2
|
|
141
|
+
assert "/v1/parse" not in fake.paths() and "/v1/capacity/executions" not in fake.paths()
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def test_reading_results_follows_every_page(api):
|
|
145
|
+
fake = api()
|
|
146
|
+
fake.polls = 1
|
|
147
|
+
result = json.loads(tools()["specstream_get_list_results"](list_id="fnd_1").content)
|
|
148
|
+
|
|
149
|
+
assert [row["position"] for row in result["rows"]] == [1, 2]
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def test_the_key_goes_in_the_authorization_header_and_never_in_the_result(api):
|
|
153
|
+
fake = api()
|
|
154
|
+
output = tools()["specstream_find_list"](request="Dental clinics in Lisbon").content
|
|
155
|
+
|
|
156
|
+
headers = fake.calls[0][3]
|
|
157
|
+
assert headers["Authorization"] == f"Bearer {KEY}"
|
|
158
|
+
assert headers["User-agent"].startswith("llama-index-tools-specstream/")
|
|
159
|
+
assert KEY not in output
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def test_the_tools_work_from_an_async_agent(api):
|
|
163
|
+
import asyncio
|
|
164
|
+
|
|
165
|
+
api()
|
|
166
|
+
output = asyncio.run(tools()["specstream_find_list"].acall(request="Dental clinics in Lisbon"))
|
|
167
|
+
assert json.loads(output.content)["row_count"] == 2
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def test_the_retriever_returns_one_node_per_row_with_its_source(api):
|
|
171
|
+
api()
|
|
172
|
+
nodes = SpecStreamRetriever(api_key=KEY, max_price_usd=5, poll_interval=0).retrieve("Dental clinics in Lisbon")
|
|
173
|
+
|
|
174
|
+
assert len(nodes) == 2
|
|
175
|
+
first = nodes[0].node
|
|
176
|
+
assert first.text == "Organization: Clínica Sorriso\nWebsite: https://sorriso.pt"
|
|
177
|
+
assert first.metadata["source_url"] == "https://sorriso.pt/marcacoes"
|
|
178
|
+
assert first.node_id == "fnd_1:1"
|
|
179
|
+
assert "source_url" in first.get_content(metadata_mode="llm")
|
|
180
|
+
assert "list_link" not in first.get_content(metadata_mode="llm")
|
|
181
|
+
assert nodes[1].node.text == "Organization: Dentes de Lisboa"
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def test_the_retriever_raises_instead_of_spending_above_the_maximum(api):
|
|
185
|
+
api(maximum_cents=900)
|
|
186
|
+
with pytest.raises(SpecStreamError, match="above the maximum"):
|
|
187
|
+
SpecStreamRetriever(api_key=KEY, max_price_usd=5).retrieve("Dental clinics in Lisbon")
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def test_a_missing_key_says_where_to_get_one(monkeypatch):
|
|
191
|
+
monkeypatch.delenv("SPECSTREAM_API_KEY", raising=False)
|
|
192
|
+
with pytest.raises(ValueError, match="SPECSTREAM_API_KEY"):
|
|
193
|
+
SpecStreamToolSpec(max_price_usd=5)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def test_the_key_can_come_from_the_environment(monkeypatch):
|
|
197
|
+
monkeypatch.setenv("SPECSTREAM_API_KEY", KEY)
|
|
198
|
+
assert SpecStreamToolSpec(max_price_usd=5)._client.api_key == KEY
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def test_a_price_cap_is_required():
|
|
202
|
+
with pytest.raises(ValueError, match="max_price_usd"):
|
|
203
|
+
SpecStreamToolSpec(api_key=KEY, max_price_usd=0)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def test_a_retry_after_the_turn_of_the_hour_reuses_the_run_from_the_hour_before(api):
|
|
207
|
+
fake = api(existing={"find_id": "fnd_1", "maximum_cents": 250})
|
|
208
|
+
fake.misses = 1
|
|
209
|
+
result = json.loads(tools()["specstream_find_list"](request="Dental clinics in Lisbon").content)
|
|
210
|
+
|
|
211
|
+
lookups = [path for path in fake.paths() if path.startswith("/v1/capacity/requests/")]
|
|
212
|
+
assert len(lookups) == 2 and lookups[0] != lookups[1]
|
|
213
|
+
assert result["row_count"] == 2
|
|
214
|
+
assert "/v1/capacity/executions" not in fake.paths()
|