anthropic-datacircle 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.
- anthropic_datacircle-0.1.0/.gitignore +4 -0
- anthropic_datacircle-0.1.0/LICENSE +9 -0
- anthropic_datacircle-0.1.0/PKG-INFO +139 -0
- anthropic_datacircle-0.1.0/README.md +121 -0
- anthropic_datacircle-0.1.0/pyproject.toml +32 -0
- anthropic_datacircle-0.1.0/src/anthropic_datacircle/__init__.py +25 -0
- anthropic_datacircle-0.1.0/src/anthropic_datacircle/_api.py +109 -0
- anthropic_datacircle-0.1.0/src/anthropic_datacircle/py.typed +0 -0
- anthropic_datacircle-0.1.0/src/anthropic_datacircle/tools.py +258 -0
- anthropic_datacircle-0.1.0/tests/test_tools.py +363 -0
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Datacircle
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
6
|
+
|
|
7
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: anthropic-datacircle
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Anthropic Python SDK tools for the Datacircle API: find the best GTM APIs
|
|
5
|
+
Project-URL: Homepage, https://datacircle.dev
|
|
6
|
+
Project-URL: Documentation, https://api.datacircle.dev/v1/openapi.json
|
|
7
|
+
Project-URL: Repository, https://github.com/waynehamadi/anthropic-datacircle-py
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: anthropic,api,api-pricing,b2b-data,claude,datacircle,gtm,tool-runner,tool-use,tools
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
14
|
+
Requires-Python: >=3.9
|
|
15
|
+
Requires-Dist: anthropic>=0.68.0
|
|
16
|
+
Requires-Dist: anyio>=3.5.0
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
|
|
19
|
+
# anthropic-datacircle
|
|
20
|
+
|
|
21
|
+
Find the best GTM APIs. We benchmark all the GTM APIs and we put the results on our website.
|
|
22
|
+
|
|
23
|
+
Our website: https://datacircle.dev
|
|
24
|
+
|
|
25
|
+
This package gives the [Anthropic Python SDK](https://github.com/anthropics/anthropic-sdk-python) four tools that call Datacircle's open API, https://api.datacircle.dev/v1. You give them to the SDK's tool runner, which runs each call Claude makes. You need no key and no account for Datacircle.
|
|
26
|
+
|
|
27
|
+
| Tool | What the tool gives | Call |
|
|
28
|
+
| --- | --- | --- |
|
|
29
|
+
| `datacircle_list_apis` | Every GTM API on Datacircle, with the API's slug, number of plans, number of providers and best plan | `GET /apis` |
|
|
30
|
+
| `datacircle_best_plans` | One API's plans, sorted by score out of 100, best first. Each plan comes with a rank and a price per 1,000 calls | `GET /apis/{slug}/best` |
|
|
31
|
+
| `datacircle_search_plans` | Plans that match a provider or plan name, on all APIs or on one API. You can sort them by score, provider or price | `GET /plans` |
|
|
32
|
+
| `datacircle_provider` | The APIs a provider sells, and the provider's rank on each API | `GET /providers/{slug}` |
|
|
33
|
+
|
|
34
|
+
## Install
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
pip install anthropic-datacircle
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
anthropic-datacircle works with `anthropic` 0.68.0 and later, on Python 3.9 and later.
|
|
41
|
+
|
|
42
|
+
## Use the tools
|
|
43
|
+
|
|
44
|
+
Give the tools to the tool runner. The runner runs each call and sends the answer back to Claude:
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
import anthropic
|
|
48
|
+
from anthropic_datacircle import datacircle_tools
|
|
49
|
+
|
|
50
|
+
client = anthropic.Anthropic()
|
|
51
|
+
runner = client.beta.messages.tool_runner(
|
|
52
|
+
model="claude-opus-5-5",
|
|
53
|
+
max_tokens=16000,
|
|
54
|
+
tools=datacircle_tools(),
|
|
55
|
+
messages=[{"role": "user", "content": "Who are the 3 best providers for the email-finder API?"}],
|
|
56
|
+
)
|
|
57
|
+
message = runner.until_done()
|
|
58
|
+
print(next(block.text for block in message.content if block.type == "text"))
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
You can also loop over the runner (`for message in runner:`) to see each message. With `stream=True`, the runner gives you a stream for each message.
|
|
62
|
+
|
|
63
|
+
With `AsyncAnthropic`, use `datacircle_async_tools()`. Each async tool runs its HTTPS request in a worker thread, so your event loop keeps running:
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
import anthropic
|
|
67
|
+
from anthropic_datacircle import datacircle_async_tools
|
|
68
|
+
|
|
69
|
+
client = anthropic.AsyncAnthropic()
|
|
70
|
+
runner = client.beta.messages.tool_runner(
|
|
71
|
+
model="claude-opus-5-5",
|
|
72
|
+
max_tokens=16000,
|
|
73
|
+
tools=datacircle_async_tools(),
|
|
74
|
+
messages=[{"role": "user", "content": "What does Bright Data sell?"}],
|
|
75
|
+
)
|
|
76
|
+
message = await runner.until_done()
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## Use them beside your own tools
|
|
80
|
+
|
|
81
|
+
You can put the Datacircle tools in the same list as yours: `tools=[*datacircle_tools(), get_weather]`. To give Claude only some of the tools, list their names: `datacircle_tools(["datacircle_best_plans"])`.
|
|
82
|
+
|
|
83
|
+
## Run the calls yourself
|
|
84
|
+
|
|
85
|
+
In a loop of your own on `client.messages.create()`, send each tool's definition with `tool.to_dict()`. Then `tool_results()` runs the Datacircle calls in a reply. It gives you one `tool_result` block for each call, with the call's id. Calls of your own tools are left out, for your code to run:
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
import anthropic
|
|
89
|
+
from anthropic_datacircle import datacircle_tools, tool_results
|
|
90
|
+
|
|
91
|
+
client = anthropic.Anthropic()
|
|
92
|
+
tools = [tool.to_dict() for tool in datacircle_tools()]
|
|
93
|
+
messages = [{"role": "user", "content": "What does Bright Data sell?"}]
|
|
94
|
+
reply = client.messages.create(model="claude-opus-5-5", max_tokens=16000, tools=tools, messages=messages)
|
|
95
|
+
|
|
96
|
+
while reply.stop_reason == "tool_use":
|
|
97
|
+
messages.append({"role": "assistant", "content": reply.content})
|
|
98
|
+
messages.append({"role": "user", "content": tool_results(reply)})
|
|
99
|
+
reply = client.messages.create(model="claude-opus-5-5", max_tokens=16000, tools=tools, messages=messages)
|
|
100
|
+
|
|
101
|
+
print(next(block.text for block in reply.content if block.type == "text"))
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
With `AsyncAnthropic`, use `await atool_results(reply)`. It runs the calls at the same time.
|
|
105
|
+
|
|
106
|
+
## Call a tool yourself
|
|
107
|
+
|
|
108
|
+
You can call each tool without Claude. You get the tool's answer as JSON text:
|
|
109
|
+
|
|
110
|
+
```python
|
|
111
|
+
import json
|
|
112
|
+
from anthropic_datacircle import best_plans
|
|
113
|
+
|
|
114
|
+
answer = json.loads(best_plans("email-finder", limit=3))
|
|
115
|
+
print(answer["plans"])
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
The other functions are `list_apis()`, `search_plans()` and `provider()`.
|
|
119
|
+
|
|
120
|
+
## What Claude reads
|
|
121
|
+
|
|
122
|
+
Each tool gives Claude a JSON object, as text. Each plan comes with a rank, provider, plan, score, price per 1,000 (`perThousand`, in dollars) and a page on datacircle.dev. That page lists every field.
|
|
123
|
+
|
|
124
|
+
You can give a provider's name in place of a slug. The tool turns `Bright Data` into `bright-data`.
|
|
125
|
+
|
|
126
|
+
When the API gives no data, such as for an unknown slug, the tool raises `DatacircleError` with the API's message. The runner sends that message to Claude as the call's result, with `is_error`. The error for an unknown API slug lists every valid slug. The tool checks each number first. For a number out of range, the tool raises the error and makes no API call. If the network fails, the error holds the network error's message. Claude can then call the tool again.
|
|
127
|
+
|
|
128
|
+
## Network
|
|
129
|
+
|
|
130
|
+
Each tool call makes one HTTPS GET request to https://api.datacircle.dev/v1 and nothing else. The request holds only the tool's own arguments: no key and nothing from your chats. The API takes up to 60 calls a minute from one IP address. The tool waits once, for a minute at most, when the API asks the tool to wait. Each call uses only Python's standard library. Nothing goes to disk.
|
|
131
|
+
|
|
132
|
+
## Links
|
|
133
|
+
|
|
134
|
+
- Datacircle: https://datacircle.dev
|
|
135
|
+
- The API: https://datacircle.dev/api
|
|
136
|
+
- The API's spec: https://api.datacircle.dev/v1/openapi.json
|
|
137
|
+
- What each key means: https://datacircle.dev/fields
|
|
138
|
+
|
|
139
|
+
MIT license.
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
# anthropic-datacircle
|
|
2
|
+
|
|
3
|
+
Find the best GTM APIs. We benchmark all the GTM APIs and we put the results on our website.
|
|
4
|
+
|
|
5
|
+
Our website: https://datacircle.dev
|
|
6
|
+
|
|
7
|
+
This package gives the [Anthropic Python SDK](https://github.com/anthropics/anthropic-sdk-python) four tools that call Datacircle's open API, https://api.datacircle.dev/v1. You give them to the SDK's tool runner, which runs each call Claude makes. You need no key and no account for Datacircle.
|
|
8
|
+
|
|
9
|
+
| Tool | What the tool gives | Call |
|
|
10
|
+
| --- | --- | --- |
|
|
11
|
+
| `datacircle_list_apis` | Every GTM API on Datacircle, with the API's slug, number of plans, number of providers and best plan | `GET /apis` |
|
|
12
|
+
| `datacircle_best_plans` | One API's plans, sorted by score out of 100, best first. Each plan comes with a rank and a price per 1,000 calls | `GET /apis/{slug}/best` |
|
|
13
|
+
| `datacircle_search_plans` | Plans that match a provider or plan name, on all APIs or on one API. You can sort them by score, provider or price | `GET /plans` |
|
|
14
|
+
| `datacircle_provider` | The APIs a provider sells, and the provider's rank on each API | `GET /providers/{slug}` |
|
|
15
|
+
|
|
16
|
+
## Install
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
pip install anthropic-datacircle
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
anthropic-datacircle works with `anthropic` 0.68.0 and later, on Python 3.9 and later.
|
|
23
|
+
|
|
24
|
+
## Use the tools
|
|
25
|
+
|
|
26
|
+
Give the tools to the tool runner. The runner runs each call and sends the answer back to Claude:
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
import anthropic
|
|
30
|
+
from anthropic_datacircle import datacircle_tools
|
|
31
|
+
|
|
32
|
+
client = anthropic.Anthropic()
|
|
33
|
+
runner = client.beta.messages.tool_runner(
|
|
34
|
+
model="claude-opus-5-5",
|
|
35
|
+
max_tokens=16000,
|
|
36
|
+
tools=datacircle_tools(),
|
|
37
|
+
messages=[{"role": "user", "content": "Who are the 3 best providers for the email-finder API?"}],
|
|
38
|
+
)
|
|
39
|
+
message = runner.until_done()
|
|
40
|
+
print(next(block.text for block in message.content if block.type == "text"))
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
You can also loop over the runner (`for message in runner:`) to see each message. With `stream=True`, the runner gives you a stream for each message.
|
|
44
|
+
|
|
45
|
+
With `AsyncAnthropic`, use `datacircle_async_tools()`. Each async tool runs its HTTPS request in a worker thread, so your event loop keeps running:
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
import anthropic
|
|
49
|
+
from anthropic_datacircle import datacircle_async_tools
|
|
50
|
+
|
|
51
|
+
client = anthropic.AsyncAnthropic()
|
|
52
|
+
runner = client.beta.messages.tool_runner(
|
|
53
|
+
model="claude-opus-5-5",
|
|
54
|
+
max_tokens=16000,
|
|
55
|
+
tools=datacircle_async_tools(),
|
|
56
|
+
messages=[{"role": "user", "content": "What does Bright Data sell?"}],
|
|
57
|
+
)
|
|
58
|
+
message = await runner.until_done()
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Use them beside your own tools
|
|
62
|
+
|
|
63
|
+
You can put the Datacircle tools in the same list as yours: `tools=[*datacircle_tools(), get_weather]`. To give Claude only some of the tools, list their names: `datacircle_tools(["datacircle_best_plans"])`.
|
|
64
|
+
|
|
65
|
+
## Run the calls yourself
|
|
66
|
+
|
|
67
|
+
In a loop of your own on `client.messages.create()`, send each tool's definition with `tool.to_dict()`. Then `tool_results()` runs the Datacircle calls in a reply. It gives you one `tool_result` block for each call, with the call's id. Calls of your own tools are left out, for your code to run:
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
import anthropic
|
|
71
|
+
from anthropic_datacircle import datacircle_tools, tool_results
|
|
72
|
+
|
|
73
|
+
client = anthropic.Anthropic()
|
|
74
|
+
tools = [tool.to_dict() for tool in datacircle_tools()]
|
|
75
|
+
messages = [{"role": "user", "content": "What does Bright Data sell?"}]
|
|
76
|
+
reply = client.messages.create(model="claude-opus-5-5", max_tokens=16000, tools=tools, messages=messages)
|
|
77
|
+
|
|
78
|
+
while reply.stop_reason == "tool_use":
|
|
79
|
+
messages.append({"role": "assistant", "content": reply.content})
|
|
80
|
+
messages.append({"role": "user", "content": tool_results(reply)})
|
|
81
|
+
reply = client.messages.create(model="claude-opus-5-5", max_tokens=16000, tools=tools, messages=messages)
|
|
82
|
+
|
|
83
|
+
print(next(block.text for block in reply.content if block.type == "text"))
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
With `AsyncAnthropic`, use `await atool_results(reply)`. It runs the calls at the same time.
|
|
87
|
+
|
|
88
|
+
## Call a tool yourself
|
|
89
|
+
|
|
90
|
+
You can call each tool without Claude. You get the tool's answer as JSON text:
|
|
91
|
+
|
|
92
|
+
```python
|
|
93
|
+
import json
|
|
94
|
+
from anthropic_datacircle import best_plans
|
|
95
|
+
|
|
96
|
+
answer = json.loads(best_plans("email-finder", limit=3))
|
|
97
|
+
print(answer["plans"])
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
The other functions are `list_apis()`, `search_plans()` and `provider()`.
|
|
101
|
+
|
|
102
|
+
## What Claude reads
|
|
103
|
+
|
|
104
|
+
Each tool gives Claude a JSON object, as text. Each plan comes with a rank, provider, plan, score, price per 1,000 (`perThousand`, in dollars) and a page on datacircle.dev. That page lists every field.
|
|
105
|
+
|
|
106
|
+
You can give a provider's name in place of a slug. The tool turns `Bright Data` into `bright-data`.
|
|
107
|
+
|
|
108
|
+
When the API gives no data, such as for an unknown slug, the tool raises `DatacircleError` with the API's message. The runner sends that message to Claude as the call's result, with `is_error`. The error for an unknown API slug lists every valid slug. The tool checks each number first. For a number out of range, the tool raises the error and makes no API call. If the network fails, the error holds the network error's message. Claude can then call the tool again.
|
|
109
|
+
|
|
110
|
+
## Network
|
|
111
|
+
|
|
112
|
+
Each tool call makes one HTTPS GET request to https://api.datacircle.dev/v1 and nothing else. The request holds only the tool's own arguments: no key and nothing from your chats. The API takes up to 60 calls a minute from one IP address. The tool waits once, for a minute at most, when the API asks the tool to wait. Each call uses only Python's standard library. Nothing goes to disk.
|
|
113
|
+
|
|
114
|
+
## Links
|
|
115
|
+
|
|
116
|
+
- Datacircle: https://datacircle.dev
|
|
117
|
+
- The API: https://datacircle.dev/api
|
|
118
|
+
- The API's spec: https://api.datacircle.dev/v1/openapi.json
|
|
119
|
+
- What each key means: https://datacircle.dev/fields
|
|
120
|
+
|
|
121
|
+
MIT license.
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "anthropic-datacircle"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Anthropic Python SDK tools for the Datacircle API: find the best GTM APIs"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.9"
|
|
12
|
+
dependencies = ["anthropic>=0.68.0", "anyio>=3.5.0"]
|
|
13
|
+
keywords = ["anthropic", "claude", "tool-runner", "tool-use", "tools", "gtm", "api", "api-pricing", "b2b-data", "datacircle"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Operating System :: OS Independent",
|
|
17
|
+
"Topic :: Software Development :: Libraries",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
[project.urls]
|
|
21
|
+
Homepage = "https://datacircle.dev"
|
|
22
|
+
Documentation = "https://api.datacircle.dev/v1/openapi.json"
|
|
23
|
+
Repository = "https://github.com/waynehamadi/anthropic-datacircle-py"
|
|
24
|
+
|
|
25
|
+
[dependency-groups]
|
|
26
|
+
test = ["pytest>=8"]
|
|
27
|
+
|
|
28
|
+
[tool.hatch.build.targets.wheel]
|
|
29
|
+
packages = ["src/anthropic_datacircle"]
|
|
30
|
+
|
|
31
|
+
[tool.hatch.build.targets.sdist]
|
|
32
|
+
include = ["src", "tests", "README.md", "LICENSE", "pyproject.toml"]
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Tools for the Anthropic Python SDK's tool runner on Datacircle's open API (https://api.datacircle.dev/v1): find the best GTM APIs, no key."""
|
|
2
|
+
|
|
3
|
+
from anthropic_datacircle._api import BASE_URL, DatacircleError
|
|
4
|
+
from anthropic_datacircle.tools import (
|
|
5
|
+
ASYNC_TOOLS,
|
|
6
|
+
TOOL_NAMES,
|
|
7
|
+
TOOLS,
|
|
8
|
+
atool_results,
|
|
9
|
+
best_plans,
|
|
10
|
+
datacircle_async_tools,
|
|
11
|
+
datacircle_best_plans,
|
|
12
|
+
datacircle_list_apis,
|
|
13
|
+
datacircle_provider,
|
|
14
|
+
datacircle_search_plans,
|
|
15
|
+
datacircle_tools,
|
|
16
|
+
list_apis,
|
|
17
|
+
provider,
|
|
18
|
+
search_plans,
|
|
19
|
+
tool_results,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
__version__ = "0.1.0"
|
|
23
|
+
__all__ = ["ASYNC_TOOLS", "BASE_URL", "DatacircleError", "TOOLS", "TOOL_NAMES", "atool_results", "best_plans",
|
|
24
|
+
"datacircle_async_tools", "datacircle_best_plans", "datacircle_list_apis", "datacircle_provider",
|
|
25
|
+
"datacircle_search_plans", "datacircle_tools", "list_apis", "provider", "search_plans", "tool_results"]
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""One HTTPS GET to Datacircle's open API (https://api.datacircle.dev/v1), no key, and what its answers are cut to for a model."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import math
|
|
5
|
+
import re
|
|
6
|
+
import time
|
|
7
|
+
import unicodedata
|
|
8
|
+
import urllib.error
|
|
9
|
+
import urllib.parse
|
|
10
|
+
import urllib.request
|
|
11
|
+
from typing import Any, Dict, List, Optional
|
|
12
|
+
|
|
13
|
+
try: # anthropic 0.84.0 and later: the tool runner sends a ToolError's words as the call's result, with is_error
|
|
14
|
+
from anthropic.lib.tools import ToolError as _Refusal
|
|
15
|
+
except ImportError: # before it, the runner sends repr() of any exception, with is_error
|
|
16
|
+
_Refusal = Exception
|
|
17
|
+
|
|
18
|
+
BASE_URL = "https://api.datacircle.dev/v1"
|
|
19
|
+
TIMEOUT = 30.0
|
|
20
|
+
USER_AGENT = "anthropic-datacircle/0.1.0"
|
|
21
|
+
|
|
22
|
+
# A plan holds about 90 keys (its terms of use, its aggregators...): the tools keep the ones that choose a plan, the rest is on its page.
|
|
23
|
+
PLAN_KEYS = ["api", "rank", "provider", "plan", "score", "perThousand", "notFoundPerThousand", "billing", "pay",
|
|
24
|
+
"currency", "units", "unit", "strengths", "latencyMs", "page", "pricingPage", "docs"]
|
|
25
|
+
API_KEYS = ["api", "slug", "plans", "providers", "best", "bestPage", "sheetPage"]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class DatacircleError(_Refusal): # type: ignore[valid-type, misc]
|
|
29
|
+
"""The API's refusal in its own words, why it could not be reached, or an argument it can't take. Raised in a tool,
|
|
30
|
+
the tool runner gives the model its words as the call's result, with is_error. status is the API's HTTP status, None
|
|
31
|
+
when it gave none; retryable, whether the same call may be answered later (the API out of reach, busy or failing)."""
|
|
32
|
+
|
|
33
|
+
def __init__(self, message: str, status: Optional[int] = None, retryable: bool = False):
|
|
34
|
+
super().__init__(message)
|
|
35
|
+
self.status = status
|
|
36
|
+
self.retryable = retryable
|
|
37
|
+
|
|
38
|
+
def __str__(self) -> str:
|
|
39
|
+
return str(self.args[0]) if self.args else ""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def brief(item: Dict[str, Any], keys: List[str] = PLAN_KEYS) -> Dict[str, Any]:
|
|
43
|
+
return {key: item[key] for key in keys if item.get(key) is not None}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def slug(value: Any) -> str:
|
|
47
|
+
"""The API's rule for a slug: the name in lowercase letters and digits, the rest a hyphen."""
|
|
48
|
+
plain = unicodedata.normalize("NFKD", str(value or "").strip().lower())
|
|
49
|
+
plain = "".join(char for char in plain if not unicodedata.combining(char))
|
|
50
|
+
return re.sub(r"[^a-z0-9]+", "-", plain).strip("-")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def whole(name: str, value: Any, low: int, high: Optional[int] = None) -> Optional[int]:
|
|
54
|
+
"""A whole number from low to high, or None when left out: a plain call may send one as text."""
|
|
55
|
+
if value is None or value == "":
|
|
56
|
+
return None
|
|
57
|
+
try:
|
|
58
|
+
number = float(value)
|
|
59
|
+
except (TypeError, ValueError):
|
|
60
|
+
number = float("nan")
|
|
61
|
+
if isinstance(value, bool) or not math.isfinite(number) or number != int(number):
|
|
62
|
+
raise DatacircleError(f"{name} must be a whole number, not {value!r}")
|
|
63
|
+
if number < low or (high is not None and number > high):
|
|
64
|
+
raise DatacircleError(f"{name} must be from {low} to {high}, not {int(number)}" if high is not None
|
|
65
|
+
else f"{name} must be {low} or more, not {int(number)}")
|
|
66
|
+
return int(number)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _words(body: bytes) -> str:
|
|
70
|
+
"""A refusal's words: the API's error, with every slug when the slug was unknown."""
|
|
71
|
+
text = body.decode("utf-8", "replace")
|
|
72
|
+
try:
|
|
73
|
+
parsed = json.loads(text)
|
|
74
|
+
if parsed.get("slugs"):
|
|
75
|
+
return f"{parsed['error']}; the slugs: {', '.join(parsed['slugs'])}"
|
|
76
|
+
return str(parsed.get("error", text))
|
|
77
|
+
except (ValueError, KeyError, TypeError, AttributeError):
|
|
78
|
+
return text
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def get(path: str, params: Optional[Dict[str, Any]] = None) -> Any:
|
|
82
|
+
"""The API's JSON answer, or a DatacircleError with its words: waits once when it answers 429."""
|
|
83
|
+
query = urllib.parse.urlencode({key: value for key, value in (params or {}).items() if value not in (None, "")})
|
|
84
|
+
url = f"{BASE_URL.rstrip('/')}{path}" + (f"?{query}" if query else "")
|
|
85
|
+
request = urllib.request.Request(url, headers={"Accept": "application/json", "User-Agent": USER_AGENT})
|
|
86
|
+
for attempt in range(2):
|
|
87
|
+
try:
|
|
88
|
+
with urllib.request.urlopen(request, timeout=TIMEOUT) as answer:
|
|
89
|
+
body = answer.read()
|
|
90
|
+
except urllib.error.HTTPError as error:
|
|
91
|
+
body = error.read()
|
|
92
|
+
if error.code == 429 and not attempt:
|
|
93
|
+
try:
|
|
94
|
+
wait = int(error.headers.get("Retry-After") or 30)
|
|
95
|
+
except ValueError:
|
|
96
|
+
wait = 30
|
|
97
|
+
time.sleep(min(max(wait, 1), 60))
|
|
98
|
+
continue
|
|
99
|
+
if error.code == 429:
|
|
100
|
+
raise DatacircleError("Datacircle's API answered 429 twice: wait a minute and call again", 429, True) from None
|
|
101
|
+
raise DatacircleError(f"Datacircle's API answered {error.code}: {_words(body)[:3000]}", error.code,
|
|
102
|
+
error.code >= 500) from None
|
|
103
|
+
except (urllib.error.URLError, OSError) as error:
|
|
104
|
+
raise DatacircleError(f"Datacircle's API could not be reached: {getattr(error, 'reason', error)}",
|
|
105
|
+
retryable=True) from None
|
|
106
|
+
try:
|
|
107
|
+
return json.loads(body)
|
|
108
|
+
except ValueError as error:
|
|
109
|
+
raise DatacircleError(f"Datacircle's API gave no JSON: {error}") from None
|
|
File without changes
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
"""Tools for the Anthropic Python SDK on Datacircle's open API, https://api.datacircle.dev/v1: no key, no account.
|
|
2
|
+
|
|
3
|
+
Each tool is a beta_tool, and a beta_async_tool of the same name for an AsyncAnthropic client, with its own JSON schema:
|
|
4
|
+
given to client.beta.messages.tool_runner(), the runner sends its definition and runs the calls the model makes, whole
|
|
5
|
+
or streamed. A tool makes one HTTPS GET and gives the model the API's answer as JSON text. A refusal (an unknown slug,
|
|
6
|
+
an argument out of range, the API out of reach) raises DatacircleError: the runner sends its words as the call's result
|
|
7
|
+
with is_error, so the model can call again and the run goes on. Each tool checks its own arguments before any call, as
|
|
8
|
+
a loop of the app's own may send them unchecked.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import urllib.parse
|
|
13
|
+
from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Sequence
|
|
14
|
+
|
|
15
|
+
import anyio
|
|
16
|
+
import anyio.to_thread
|
|
17
|
+
from anthropic import beta_async_tool, beta_tool
|
|
18
|
+
|
|
19
|
+
from anthropic_datacircle import _api
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _best(plans: Any) -> Optional[Dict[str, Any]]:
|
|
23
|
+
"""A provider's best plan on an API: its lowest rank, a plan with no score having none."""
|
|
24
|
+
ranked = sorted(plans, key=lambda plan: plan.get("rank") if isinstance(plan.get("rank"), (int, float)) else float("inf"))
|
|
25
|
+
return _api.brief(ranked[0], ["plan", "score", "perThousand", "page"]) if ranked else None
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _list_apis(query: Any, limit: Any) -> Dict[str, Any]:
|
|
29
|
+
count = _api.whole("limit", limit, 1, 200) or 20
|
|
30
|
+
apis = _api.get("/apis")
|
|
31
|
+
words = [word for word in str(query or "").lower().replace("-", " ").split() if word]
|
|
32
|
+
held = []
|
|
33
|
+
for index, api in enumerate(apis):
|
|
34
|
+
name = f"{api.get('api', '')} {str(api.get('slug', '')).replace('-', ' ')}".lower()
|
|
35
|
+
matched = sum(word in name for word in words)
|
|
36
|
+
if matched or not words:
|
|
37
|
+
held.append((-matched, index, api))
|
|
38
|
+
found = [_api.brief(api, _api.API_KEYS) for _, _, api in sorted(held, key=lambda h: h[:2])]
|
|
39
|
+
return {"total": len(found), "apis": found[:count]}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _best_plans(slug: Any, limit: Any) -> Dict[str, Any]:
|
|
43
|
+
made = _api.slug(slug)
|
|
44
|
+
if not made:
|
|
45
|
+
raise _api.DatacircleError("Give an API's slug, like 'email-finder': datacircle_list_apis gives every slug")
|
|
46
|
+
answer = _api.get(f"/apis/{urllib.parse.quote(made)}/best", {"limit": _api.whole("limit", limit, 1, 50)})
|
|
47
|
+
return {**answer, "plans": [_api.brief(plan) for plan in answer.get("plans") or []]}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _search_plans(api: Any, query: Any, sort: Any, limit: Any, offset: Any) -> Dict[str, Any]:
|
|
51
|
+
order = str(sort).strip().lower() if sort not in (None, "") else None
|
|
52
|
+
if order is not None and order not in ("score", "provider", "price"):
|
|
53
|
+
raise _api.DatacircleError(f"sort must be score, provider or price, not {sort!r}")
|
|
54
|
+
params = {"api": api, "query": query, "sort": order, "limit": _api.whole("limit", limit, 1, 50),
|
|
55
|
+
"offset": _api.whole("offset", offset, 0)}
|
|
56
|
+
answer = _api.get("/plans", params)
|
|
57
|
+
return {**answer, "plans": [_api.brief(plan) for plan in answer.get("plans") or []]}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _provider(slug: Any) -> Dict[str, Any]:
|
|
61
|
+
made = _api.slug(slug)
|
|
62
|
+
if not made:
|
|
63
|
+
raise _api.DatacircleError("Give a provider's slug or name, like 'bright-data' or 'Bright Data'")
|
|
64
|
+
answer = _api.get(f"/providers/{urllib.parse.quote(made)}")
|
|
65
|
+
apis = [{**_api.brief(entry, ["api", "slug", "rank", "bestPage"]), "plans": len(entry.get("plans") or []),
|
|
66
|
+
"best": _best(entry.get("plans") or [])} for entry in answer.get("apis") or []]
|
|
67
|
+
return {**answer, "apis": apis}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _text(answer: Dict[str, Any]) -> str:
|
|
71
|
+
return json.dumps(answer, ensure_ascii=False)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
# What the model reads of each tool: its description and its input schema, the API's own bounds in it.
|
|
75
|
+
|
|
76
|
+
_SLUG_OF_API = "The API's slug, like 'email-finder' or 'linkedin-profile', as datacircle_list_apis gives it."
|
|
77
|
+
_PRICE = "perThousand is a plan's price of 1,000 items in dollars, pay the plan's whole price in its currency."
|
|
78
|
+
DESCRIPTIONS = {
|
|
79
|
+
"datacircle_list_apis": "Lists the GTM APIs on Datacircle's sheet (https://datacircle.dev), with each API's slug, how "
|
|
80
|
+
"many plans and providers it has and its best plan. Call it to find an API's slug when you "
|
|
81
|
+
"don't know it. Gives total, the APIs found, and apis, up to limit of them.",
|
|
82
|
+
"datacircle_best_plans": "Gives an API's plans best first by their score out of 100 on Datacircle's benchmark "
|
|
83
|
+
"(https://datacircle.dev), each with its rank, provider, plan, $ per 1,000 calls and its "
|
|
84
|
+
"page: the best providers of an API. " + _PRICE,
|
|
85
|
+
"datacircle_search_plans": "Searches every plan on Datacircle's sheet (https://datacircle.dev), or one API's, by "
|
|
86
|
+
"provider or plan name, sorted by score, provider or price. Gives total, offset and up "
|
|
87
|
+
"to limit plans. " + _PRICE,
|
|
88
|
+
"datacircle_provider": "Gives each API one provider sells and its rank on each on Datacircle's benchmark "
|
|
89
|
+
"(https://datacircle.dev), with its best plan there.",
|
|
90
|
+
}
|
|
91
|
+
SCHEMAS: Dict[str, Dict[str, Any]] = {
|
|
92
|
+
"datacircle_list_apis": {"type": "object", "properties": {
|
|
93
|
+
"query": {"type": "string", "description": "Words of the API's name or slug, like 'email' or 'linkedin "
|
|
94
|
+
"profile'. The APIs that hold the most of them come first, in the sheet's order when left out."},
|
|
95
|
+
"limit": {"type": "integer", "minimum": 1, "maximum": 200,
|
|
96
|
+
"description": "How many APIs to give. 20 when left out, of about 160."},
|
|
97
|
+
}, "additionalProperties": False},
|
|
98
|
+
"datacircle_best_plans": {"type": "object", "properties": {
|
|
99
|
+
"slug": {"type": "string", "description": _SLUG_OF_API},
|
|
100
|
+
"limit": {"type": "integer", "minimum": 1, "maximum": 50, "description": "How many plans to give. 10 when left out."},
|
|
101
|
+
}, "required": ["slug"], "additionalProperties": False},
|
|
102
|
+
"datacircle_search_plans": {"type": "object", "properties": {
|
|
103
|
+
"api": {"type": "string", "description": "Only this API's plans, by its name or slug, like 'email-finder'. A "
|
|
104
|
+
"provider's name goes in query, never here. Every API when left out."},
|
|
105
|
+
"query": {"type": "string", "description": "Words that must all appear in the provider's or plan's name, like "
|
|
106
|
+
"'bright data'."},
|
|
107
|
+
"sort": {"type": "string", "enum": ["score", "provider", "price"],
|
|
108
|
+
"description": "score (best first, the default), provider (A to Z) or price ($ per 1,000, lowest first)."},
|
|
109
|
+
"limit": {"type": "integer", "minimum": 1, "maximum": 50, "description": "How many plans to give. 10 when left out."},
|
|
110
|
+
"offset": {"type": "integer", "minimum": 0, "description": "How many found plans to skip first. 0 when left out."},
|
|
111
|
+
}, "additionalProperties": False},
|
|
112
|
+
"datacircle_provider": {"type": "object", "properties": {
|
|
113
|
+
"slug": {"type": "string", "description": "The provider's slug, like 'bright-data', or its name, like 'Bright "
|
|
114
|
+
"Data', which is made a slug."},
|
|
115
|
+
}, "required": ["slug"], "additionalProperties": False},
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
# The functions. Called alone, each gives the API's answer as JSON text, or raises DatacircleError with its words.
|
|
120
|
+
|
|
121
|
+
def list_apis(query: Optional[str] = None, limit: Optional[int] = None) -> str:
|
|
122
|
+
"""The GTM APIs on Datacircle's sheet, those whose name or slug holds the most of query's words first: total and
|
|
123
|
+
up to limit apis (1 to 200, 20 when left out), as JSON text."""
|
|
124
|
+
return _text(_list_apis(query, limit))
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def best_plans(slug: str, limit: Optional[int] = None) -> str:
|
|
128
|
+
"""An API's plans best first by their score out of 100, up to limit (1 to 50, 10 when left out), as JSON text."""
|
|
129
|
+
return _text(_best_plans(slug, limit))
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def search_plans(api: Optional[str] = None, query: Optional[str] = None, sort: Optional[str] = None,
|
|
133
|
+
limit: Optional[int] = None, offset: Optional[int] = None) -> str:
|
|
134
|
+
"""Every plan, or one API's, whose provider or plan name holds query's words, sorted by score, provider or price:
|
|
135
|
+
total, offset and up to limit plans (1 to 50, 10 when left out), as JSON text."""
|
|
136
|
+
return _text(_search_plans(api, query, sort, limit, offset))
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def provider(slug: str) -> str:
|
|
140
|
+
"""Each API one provider sells, its rank on each and its best plan there, as JSON text. slug may be its name."""
|
|
141
|
+
return _text(_provider(slug))
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
async def _list_apis_async(query: Optional[str] = None, limit: Optional[int] = None) -> str:
|
|
145
|
+
return await anyio.to_thread.run_sync(list_apis, query, limit)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
async def _best_plans_async(slug: str, limit: Optional[int] = None) -> str:
|
|
149
|
+
return await anyio.to_thread.run_sync(best_plans, slug, limit)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
async def _search_plans_async(api: Optional[str] = None, query: Optional[str] = None, sort: Optional[str] = None,
|
|
153
|
+
limit: Optional[int] = None, offset: Optional[int] = None) -> str:
|
|
154
|
+
return await anyio.to_thread.run_sync(search_plans, api, query, sort, limit, offset)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
async def _provider_async(slug: str) -> str:
|
|
158
|
+
return await anyio.to_thread.run_sync(provider, slug)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _made(make: Callable[..., Any], name: str, function: Callable[..., Any]) -> Any:
|
|
162
|
+
return make(function, name=name, description=DESCRIPTIONS[name], input_schema=SCHEMAS[name])
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
datacircle_list_apis = _made(beta_tool, "datacircle_list_apis", list_apis)
|
|
166
|
+
datacircle_best_plans = _made(beta_tool, "datacircle_best_plans", best_plans)
|
|
167
|
+
datacircle_search_plans = _made(beta_tool, "datacircle_search_plans", search_plans)
|
|
168
|
+
datacircle_provider = _made(beta_tool, "datacircle_provider", provider)
|
|
169
|
+
|
|
170
|
+
TOOLS = {tool.name: tool for tool in (datacircle_list_apis, datacircle_best_plans, datacircle_search_plans,
|
|
171
|
+
datacircle_provider)}
|
|
172
|
+
ASYNC_TOOLS = {name: _made(beta_async_tool, name, function) for name, function in (
|
|
173
|
+
("datacircle_list_apis", _list_apis_async), ("datacircle_best_plans", _best_plans_async),
|
|
174
|
+
("datacircle_search_plans", _search_plans_async), ("datacircle_provider", _provider_async))}
|
|
175
|
+
TOOL_NAMES = list(TOOLS)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _chosen(tools: Mapping[str, Any], tool_names: Optional[Sequence[str]]) -> List[Any]:
|
|
179
|
+
if isinstance(tool_names, str):
|
|
180
|
+
raise TypeError("tool_names is a list of names, like ['datacircle_best_plans']")
|
|
181
|
+
for name in tool_names or []:
|
|
182
|
+
if name not in tools:
|
|
183
|
+
raise ValueError(f"Datacircle has no tool {name!r}: its tools are {', '.join(TOOL_NAMES)}")
|
|
184
|
+
return [tools[name] for name in (TOOL_NAMES if tool_names is None else tool_names)]
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def datacircle_tools(tool_names: Optional[Sequence[str]] = None) -> List[Any]:
|
|
188
|
+
"""The tools, for client.beta.messages.tool_runner(tools=datacircle_tools()) or beside one's own:
|
|
189
|
+
tools=[*datacircle_tools(), my_tool]. tool_names keeps some of them only, in their order here; all four when left out."""
|
|
190
|
+
return _chosen(TOOLS, tool_names)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def datacircle_async_tools(tool_names: Optional[Sequence[str]] = None) -> List[Any]:
|
|
194
|
+
"""The same tools for an AsyncAnthropic client's tool runner: each runs its HTTPS GET in a worker thread."""
|
|
195
|
+
return _chosen(ASYNC_TOOLS, tool_names)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _field(item: Any, key: str) -> Any:
|
|
199
|
+
return item.get(key) if isinstance(item, Mapping) else getattr(item, key, None)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _calls(source: Any) -> List[Any]:
|
|
203
|
+
"""The calls of these tools in a reply: a Message or BetaMessage, its content, or a list of its blocks or their dicts."""
|
|
204
|
+
if source is None:
|
|
205
|
+
return []
|
|
206
|
+
if _field(source, "content") is not None and not isinstance(source, (list, tuple)):
|
|
207
|
+
source = _field(source, "content")
|
|
208
|
+
blocks = source if isinstance(source, Iterable) and not isinstance(source, (str, bytes, Mapping)) else [source]
|
|
209
|
+
return [block for block in blocks if _field(block, "type") == "tool_use" and _field(block, "name") in TOOLS]
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _why(error: Exception) -> str:
|
|
213
|
+
"""A failed call's words for the model: the API's or the check's, or which argument the SDK's validation refused."""
|
|
214
|
+
cause = error.__cause__
|
|
215
|
+
if cause is not None and hasattr(cause, "errors"):
|
|
216
|
+
try:
|
|
217
|
+
return f"{error}: " + "; ".join(f"{'.'.join(map(str, item['loc'])) or 'input'}: {item['msg']}"
|
|
218
|
+
for item in cause.errors())
|
|
219
|
+
except Exception: # noqa: BLE001 - its plain words then
|
|
220
|
+
pass
|
|
221
|
+
return str(error) if isinstance(error, _api.DatacircleError) else f"{type(error).__name__}: {error}"
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _result(block: Any) -> Dict[str, Any]:
|
|
225
|
+
result: Dict[str, Any] = {"type": "tool_result", "tool_use_id": _field(block, "id")}
|
|
226
|
+
try:
|
|
227
|
+
result["content"] = TOOLS[_field(block, "name")].call(_field(block, "input"))
|
|
228
|
+
except Exception as error: # noqa: BLE001 - every failure is the call's result, as the tool runner gives it
|
|
229
|
+
result.update(content=_why(error), is_error=True)
|
|
230
|
+
return result
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def tool_results(message: Any) -> List[Dict[str, Any]]:
|
|
234
|
+
"""For a loop of the app's own on client.messages.create(): the tool_result block of each call of these tools in
|
|
235
|
+
a reply (a Message, its content, or a list of its blocks or their dicts), in their order, with its call's id. A
|
|
236
|
+
refused call's block holds the refusal's words and is_error. Calls of other tools are left out, for the app to run."""
|
|
237
|
+
return [_result(block) for block in _calls(message)]
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
async def atool_results(message: Any) -> List[Dict[str, Any]]:
|
|
241
|
+
"""tool_results() for an AsyncAnthropic client: the calls run at once, each in a worker thread, their blocks in the
|
|
242
|
+
calls' order."""
|
|
243
|
+
calls = _calls(message)
|
|
244
|
+
results: List[Dict[str, Any]] = [{} for _ in calls]
|
|
245
|
+
|
|
246
|
+
async def one(index: int, block: Any) -> None:
|
|
247
|
+
results[index] = await anyio.to_thread.run_sync(_result, block)
|
|
248
|
+
|
|
249
|
+
async with anyio.create_task_group() as group:
|
|
250
|
+
for index, block in enumerate(calls):
|
|
251
|
+
group.start_soon(one, index, block)
|
|
252
|
+
return results
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
__all__: List[str] = ["ASYNC_TOOLS", "DESCRIPTIONS", "SCHEMAS", "TOOLS", "TOOL_NAMES", "atool_results", "best_plans",
|
|
256
|
+
"datacircle_async_tools", "datacircle_best_plans", "datacircle_list_apis", "datacircle_provider",
|
|
257
|
+
"datacircle_search_plans", "datacircle_tools", "list_apis", "provider", "search_plans",
|
|
258
|
+
"tool_results"]
|
|
@@ -0,0 +1,363 @@
|
|
|
1
|
+
"""Offline tests: the tools against a local stand-in for the API on 127.0.0.1, by their own call, by tool_results() on the
|
|
2
|
+
SDK's own types, and run by the SDK's tool runner (sync and async, whole and streamed) and by a loop of the app's own on
|
|
3
|
+
client.messages.create, all sent to a stand-in of the Messages API on the same server."""
|
|
4
|
+
|
|
5
|
+
import inspect
|
|
6
|
+
import json
|
|
7
|
+
import threading
|
|
8
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
9
|
+
from urllib.parse import parse_qs, urlparse
|
|
10
|
+
|
|
11
|
+
import anthropic
|
|
12
|
+
import anyio
|
|
13
|
+
import pytest
|
|
14
|
+
from anthropic import Anthropic, AsyncAnthropic, beta_async_tool, beta_tool
|
|
15
|
+
from anthropic.resources.beta.messages import Messages
|
|
16
|
+
|
|
17
|
+
from anthropic_datacircle import (
|
|
18
|
+
ASYNC_TOOLS,
|
|
19
|
+
TOOL_NAMES,
|
|
20
|
+
TOOLS,
|
|
21
|
+
DatacircleError,
|
|
22
|
+
atool_results,
|
|
23
|
+
best_plans,
|
|
24
|
+
datacircle_async_tools,
|
|
25
|
+
datacircle_best_plans,
|
|
26
|
+
datacircle_provider,
|
|
27
|
+
datacircle_tools,
|
|
28
|
+
list_apis,
|
|
29
|
+
provider,
|
|
30
|
+
search_plans,
|
|
31
|
+
tool_results,
|
|
32
|
+
)
|
|
33
|
+
from anthropic_datacircle import _api, tools as tools_module
|
|
34
|
+
|
|
35
|
+
PLAN = {"api": "Employee email", "rank": 1, "provider": "Hunter", "plan": "Starter", "score": 80.1, "perThousand": 4.9,
|
|
36
|
+
"page": "https://datacircle.dev/x", "terms": "long", "aggregators": ["a"]}
|
|
37
|
+
SEEN = []
|
|
38
|
+
BUSY = []
|
|
39
|
+
ASKED = []
|
|
40
|
+
# The calls the stand-in model makes on its first turn: each tool, a refused one and the app's own tool.
|
|
41
|
+
CALLS = [("t1", "datacircle_list_apis", {"query": "profile", "limit": 1}),
|
|
42
|
+
("t2", "datacircle_best_plans", {"slug": "email-finder", "limit": 1}),
|
|
43
|
+
("t3", "datacircle_search_plans", {"api": "email-finder", "query": "hunter", "sort": "price", "limit": 5}),
|
|
44
|
+
("t4", "datacircle_provider", {"slug": "Bright Data"}),
|
|
45
|
+
("t5", "datacircle_best_plans", {"slug": "nope"}),
|
|
46
|
+
("t6", "add_two_numbers", {"a": 1, "b": 2})]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def message(content, stop_reason):
|
|
50
|
+
return {"id": f"msg_{len(ASKED)}", "type": "message", "role": "assistant", "model": "stand-in", "content": content,
|
|
51
|
+
"stop_reason": stop_reason, "stop_sequence": None, "usage": {"input_tokens": 1, "output_tokens": 1}}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def events(reply):
|
|
55
|
+
"""The reply as the Messages API streams it."""
|
|
56
|
+
start = dict(reply, content=[], stop_reason=None)
|
|
57
|
+
out = [("message_start", {"type": "message_start", "message": start})]
|
|
58
|
+
for index, block in enumerate(reply["content"]):
|
|
59
|
+
if block["type"] == "text":
|
|
60
|
+
out.append(("content_block_start", {"type": "content_block_start", "index": index,
|
|
61
|
+
"content_block": {"type": "text", "text": ""}}))
|
|
62
|
+
out.append(("content_block_delta", {"type": "content_block_delta", "index": index,
|
|
63
|
+
"delta": {"type": "text_delta", "text": block["text"]}}))
|
|
64
|
+
else:
|
|
65
|
+
out.append(("content_block_start", {"type": "content_block_start", "index": index,
|
|
66
|
+
"content_block": dict(block, input={})}))
|
|
67
|
+
text = json.dumps(block["input"])
|
|
68
|
+
for piece in (text[:5], text[5:]):
|
|
69
|
+
out.append(("content_block_delta", {"type": "content_block_delta", "index": index,
|
|
70
|
+
"delta": {"type": "input_json_delta", "partial_json": piece}}))
|
|
71
|
+
out.append(("content_block_stop", {"type": "content_block_stop", "index": index}))
|
|
72
|
+
out.append(("message_delta", {"type": "message_delta", "delta": {"stop_reason": reply["stop_reason"],
|
|
73
|
+
"stop_sequence": None},
|
|
74
|
+
"usage": {"output_tokens": 1}}))
|
|
75
|
+
out.append(("message_stop", {"type": "message_stop"}))
|
|
76
|
+
return "".join(f"event: {name}\ndata: {json.dumps(data)}\n\n" for name, data in out).encode()
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class Handler(BaseHTTPRequestHandler):
|
|
80
|
+
protocol_version = "HTTP/1.1"
|
|
81
|
+
|
|
82
|
+
def log_message(self, *args):
|
|
83
|
+
pass
|
|
84
|
+
|
|
85
|
+
def send(self, status, body, headers=None, kind="application/json"):
|
|
86
|
+
data = body if isinstance(body, bytes) else json.dumps(body).encode()
|
|
87
|
+
self.send_response(status)
|
|
88
|
+
for key, value in {"Content-Type": kind, "Content-Length": str(len(data)), **(headers or {})}.items():
|
|
89
|
+
self.send_header(key, value)
|
|
90
|
+
self.end_headers()
|
|
91
|
+
self.wfile.write(data)
|
|
92
|
+
|
|
93
|
+
def do_POST(self): # the Messages API: calls each tool and the app's own on the first turn, then gives back the results
|
|
94
|
+
body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))))
|
|
95
|
+
ASKED.append(body)
|
|
96
|
+
last = body["messages"][-1]["content"]
|
|
97
|
+
results = [block for block in last if isinstance(block, dict) and block.get("type") == "tool_result"] \
|
|
98
|
+
if isinstance(last, list) else []
|
|
99
|
+
if results:
|
|
100
|
+
got = [{"id": block["tool_use_id"], "is_error": bool(block.get("is_error")), "content": block.get("content")}
|
|
101
|
+
for block in results]
|
|
102
|
+
reply = message([{"type": "text", "text": "done " + json.dumps(got)}], "end_turn")
|
|
103
|
+
else:
|
|
104
|
+
reply = message([{"type": "text", "text": "Let me look."}] +
|
|
105
|
+
[{"type": "tool_use", "id": id_, "name": name, "input": args} for id_, name, args in CALLS],
|
|
106
|
+
"tool_use")
|
|
107
|
+
if body.get("stream"):
|
|
108
|
+
self.send(200, events(reply), kind="text/event-stream")
|
|
109
|
+
else:
|
|
110
|
+
self.send(200, reply)
|
|
111
|
+
|
|
112
|
+
def do_GET(self):
|
|
113
|
+
url = urlparse(self.path)
|
|
114
|
+
query = {key: values[0] for key, values in parse_qs(url.query).items()}
|
|
115
|
+
SEEN.append((url.path, query, self.headers.get("User-Agent")))
|
|
116
|
+
headers = {}
|
|
117
|
+
if url.path == "/v1/plans" and query.get("query") == "busy" and not BUSY:
|
|
118
|
+
BUSY.append(1)
|
|
119
|
+
status, body, headers = 429, {"error": "slow down"}, {"Retry-After": "1"}
|
|
120
|
+
elif url.path == "/v1/apis":
|
|
121
|
+
status, body = 200, [{"api": "Employee email", "slug": "email-finder", "plans": 9, "providers": 3, "extra": 1},
|
|
122
|
+
{"api": "Employee profile", "slug": "linkedin-profile", "plans": 4, "providers": 2}]
|
|
123
|
+
elif url.path == "/v1/apis/email-finder/best":
|
|
124
|
+
status, body = 200, {"api": "Employee email", "slug": "email-finder", "total": 1, "plans": [PLAN]}
|
|
125
|
+
elif url.path.startswith("/v1/apis/"):
|
|
126
|
+
status, body = 404, {"error": "no API has the slug nope", "slugs": ["email-finder", "linkedin-profile"]}
|
|
127
|
+
elif url.path == "/v1/plans" and query.get("query") == "down":
|
|
128
|
+
status, body = 503, {"error": "down for a minute"}
|
|
129
|
+
elif url.path == "/v1/plans":
|
|
130
|
+
status, body = 200, {"total": 1, "offset": 0, "plans": [PLAN]}
|
|
131
|
+
elif url.path == "/v1/providers/bright-data":
|
|
132
|
+
status, body = 200, {"provider": "Bright Data", "slug": "bright-data", "website": "https://brightdata.com",
|
|
133
|
+
"apis": [{"api": "Employee email", "slug": "email-finder", "rank": 7, "sheetPage": "s",
|
|
134
|
+
"plans": [dict(PLAN, rank=9, plan="B"), dict(PLAN, rank=7, plan="A")]}]}
|
|
135
|
+
else:
|
|
136
|
+
status, body = 404, {"error": "no provider has this slug"}
|
|
137
|
+
self.send(status, body, headers)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
@pytest.fixture(scope="module", autouse=True)
|
|
141
|
+
def stand_in():
|
|
142
|
+
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
|
143
|
+
threading.Thread(target=server.serve_forever, daemon=True).start()
|
|
144
|
+
before = _api.BASE_URL
|
|
145
|
+
_api.BASE_URL = f"http://127.0.0.1:{server.server_address[1]}/v1"
|
|
146
|
+
yield server.server_address[1]
|
|
147
|
+
_api.BASE_URL = before
|
|
148
|
+
server.shutdown()
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def calls_made(action):
|
|
152
|
+
SEEN.clear()
|
|
153
|
+
result = action()
|
|
154
|
+
return result, list(SEEN)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
@beta_tool
|
|
158
|
+
def add_two_numbers(a: int, b: int) -> str:
|
|
159
|
+
"""Adds two numbers.
|
|
160
|
+
|
|
161
|
+
Args:
|
|
162
|
+
a: The first number.
|
|
163
|
+
b: The second number.
|
|
164
|
+
"""
|
|
165
|
+
return str(a + b)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
@beta_async_tool
|
|
169
|
+
async def add_two_numbers_async(a: int, b: int) -> str:
|
|
170
|
+
"""Adds two numbers."""
|
|
171
|
+
return str(a + b)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
add_two_numbers_async.name = "add_two_numbers"
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def test_definitions_as_the_sdk_sends_them():
|
|
178
|
+
sent = {tool.to_dict()["name"]: tool.to_dict() for tool in datacircle_tools()}
|
|
179
|
+
assert list(sent) == TOOL_NAMES == ["datacircle_list_apis", "datacircle_best_plans", "datacircle_search_plans",
|
|
180
|
+
"datacircle_provider"]
|
|
181
|
+
kinds = {"datacircle_list_apis": {"query": "string", "limit": "integer"},
|
|
182
|
+
"datacircle_best_plans": {"slug": "string", "limit": "integer"},
|
|
183
|
+
"datacircle_search_plans": {"api": "string", "query": "string", "sort": "string", "limit": "integer",
|
|
184
|
+
"offset": "integer"},
|
|
185
|
+
"datacircle_provider": {"slug": "string"}}
|
|
186
|
+
for name, wanted in kinds.items():
|
|
187
|
+
definition = sent[name]
|
|
188
|
+
assert "https://datacircle.dev" in definition["description"], name
|
|
189
|
+
schema = definition["input_schema"]
|
|
190
|
+
assert {key: value["type"] for key, value in schema["properties"].items()} == wanted, name
|
|
191
|
+
assert schema.get("required", []) == (["slug"] if "slug" in wanted else []), name
|
|
192
|
+
assert all(value["description"] for value in schema["properties"].values()), name
|
|
193
|
+
assert sent["datacircle_best_plans"]["input_schema"]["properties"]["limit"]["maximum"] == 50
|
|
194
|
+
assert sent["datacircle_search_plans"]["input_schema"]["properties"]["sort"]["enum"] == ["score", "provider", "price"]
|
|
195
|
+
assert [tool.to_dict() for tool in datacircle_async_tools()] == list(sent.values())
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def test_some_tools_by_name():
|
|
199
|
+
assert datacircle_tools(["datacircle_provider", "datacircle_best_plans"]) == [datacircle_provider, datacircle_best_plans]
|
|
200
|
+
assert datacircle_tools() == list(TOOLS.values())
|
|
201
|
+
assert datacircle_async_tools(["datacircle_provider"]) == [ASYNC_TOOLS["datacircle_provider"]]
|
|
202
|
+
with pytest.raises(ValueError):
|
|
203
|
+
datacircle_tools(["nope"])
|
|
204
|
+
with pytest.raises(TypeError):
|
|
205
|
+
datacircle_tools("datacircle_provider")
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def test_each_function_and_the_calls_it_makes():
|
|
209
|
+
listed, seen = calls_made(lambda: json.loads(list_apis("profile", 1)))
|
|
210
|
+
assert listed == {"total": 1, "apis": [{"api": "Employee profile", "slug": "linkedin-profile", "plans": 4, "providers": 2}]}
|
|
211
|
+
assert seen == [("/v1/apis", {}, _api.USER_AGENT)]
|
|
212
|
+
assert json.loads(list_apis())["total"] == 2
|
|
213
|
+
|
|
214
|
+
best, seen = calls_made(lambda: json.loads(best_plans("Email Finder", 1)))
|
|
215
|
+
assert best["plans"] == [{key: PLAN[key] for key in ("api", "rank", "provider", "plan", "score", "perThousand", "page")}]
|
|
216
|
+
assert seen[0][:2] == ("/v1/apis/email-finder/best", {"limit": "1"})
|
|
217
|
+
|
|
218
|
+
found, seen = calls_made(lambda: json.loads(search_plans(api="email-finder", query="hunter", sort="Price", limit=5)))
|
|
219
|
+
assert found["total"] == 1 and "terms" not in found["plans"][0]
|
|
220
|
+
assert seen[0][:2] == ("/v1/plans", {"api": "email-finder", "query": "hunter", "sort": "price", "limit": "5"})
|
|
221
|
+
|
|
222
|
+
seller, seen = calls_made(lambda: json.loads(provider("Bright Data")))
|
|
223
|
+
assert seen[0][0] == "/v1/providers/bright-data"
|
|
224
|
+
assert seller["apis"] == [{"api": "Employee email", "slug": "email-finder", "rank": 7, "plans": 2,
|
|
225
|
+
"best": {"plan": "A", "score": 80.1, "perThousand": 4.9, "page": "https://datacircle.dev/x"}}]
|
|
226
|
+
# A tool's own call: the SDK's validation, then the function.
|
|
227
|
+
assert json.loads(datacircle_best_plans.call({"slug": "email-finder", "limit": "1"}))["plans"][0]["rank"] == 1
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def test_refusals_in_the_apis_words():
|
|
231
|
+
with pytest.raises(DatacircleError) as unknown:
|
|
232
|
+
best_plans("nope")
|
|
233
|
+
assert str(unknown.value) == ("Datacircle's API answered 404: no API has the slug nope; the slugs: email-finder, "
|
|
234
|
+
"linkedin-profile")
|
|
235
|
+
assert unknown.value.status == 404 and not unknown.value.retryable
|
|
236
|
+
with pytest.raises(DatacircleError, match="503: down for a minute") as down:
|
|
237
|
+
search_plans(query="down")
|
|
238
|
+
assert down.value.retryable
|
|
239
|
+
with pytest.raises(DatacircleError, match="no provider"):
|
|
240
|
+
provider("nobody")
|
|
241
|
+
for refused in (lambda: best_plans("email-finder", 51), lambda: search_plans(sort="cheap"),
|
|
242
|
+
lambda: search_plans(offset=-1), lambda: list_apis(limit="many"),
|
|
243
|
+
lambda: best_plans(""), lambda: provider(None), lambda: search_plans(limit=True)):
|
|
244
|
+
SEEN.clear()
|
|
245
|
+
with pytest.raises(DatacircleError):
|
|
246
|
+
refused()
|
|
247
|
+
assert SEEN == []
|
|
248
|
+
if hasattr(anthropic.lib.tools, "ToolError"):
|
|
249
|
+
assert issubclass(DatacircleError, anthropic.lib.tools.ToolError)
|
|
250
|
+
with pytest.raises(DatacircleError) as made:
|
|
251
|
+
best_plans("email-finder", 0)
|
|
252
|
+
assert made.value.content == "limit must be from 1 to 50, not 0"
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def test_a_429_is_waited_once():
|
|
256
|
+
answer, seen = calls_made(lambda: json.loads(search_plans(query="busy")))
|
|
257
|
+
assert answer["total"] == 1 and len(seen) == 2
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def first_turn():
|
|
261
|
+
blocks = [{"type": "text", "text": "Let me look."}] + \
|
|
262
|
+
[{"type": "tool_use", "id": id_, "name": name, "input": args} for id_, name, args in CALLS]
|
|
263
|
+
return anthropic.types.Message.model_validate(dict(message(blocks, "tool_use"), model="claude-haiku-5-5"))
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def check_results(results):
|
|
267
|
+
"""The tool_result blocks of the stand-in's calls of the four tools, in order, the app's own left out."""
|
|
268
|
+
assert [block["tool_use_id"] for block in results] == ["t1", "t2", "t3", "t4", "t5"]
|
|
269
|
+
assert json.loads(results[0]["content"])["apis"][0]["slug"] == "linkedin-profile"
|
|
270
|
+
assert json.loads(results[1]["content"])["plans"][0]["provider"] == "Hunter"
|
|
271
|
+
assert json.loads(results[2]["content"])["total"] == 1
|
|
272
|
+
assert json.loads(results[3]["content"])["slug"] == "bright-data"
|
|
273
|
+
assert results[4]["is_error"] is True and "404: no API has the slug nope" in results[4]["content"]
|
|
274
|
+
assert not any(block.get("is_error") for block in results[:4])
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def test_tool_results_on_the_sdks_types():
|
|
278
|
+
reply = first_turn()
|
|
279
|
+
check_results(tool_results(reply))
|
|
280
|
+
check_results(tool_results(reply.content))
|
|
281
|
+
check_results(tool_results(reply.model_dump()))
|
|
282
|
+
check_results(tool_results([block.model_dump() for block in reply.content]))
|
|
283
|
+
assert tool_results(None) == [] and tool_results([]) == []
|
|
284
|
+
bad = tool_results([{"type": "tool_use", "id": "x", "name": "datacircle_best_plans", "input": {"slug": "a", "limit": 2.5}},
|
|
285
|
+
{"type": "tool_use", "id": "y", "name": "datacircle_provider", "input": {"slug": "a", "nope": 1}},
|
|
286
|
+
{"type": "tool_use", "id": "z", "name": "datacircle_provider", "input": "bright-data"}])
|
|
287
|
+
assert [block["is_error"] for block in bad] == [True, True, True]
|
|
288
|
+
assert "limit" in bad[0]["content"] and "nope" in bad[1]["content"] and "dictionary" in bad[2]["content"]
|
|
289
|
+
check_results(anyio.run(atool_results, reply))
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def client_of(port, kind=Anthropic):
|
|
293
|
+
return kind(api_key="test", base_url=f"http://127.0.0.1:{port}", max_retries=0)
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def check_run(final, first_request):
|
|
297
|
+
"""The run's last message holds what the stand-in got back: each tool's answer, the refusal with is_error, the app's own."""
|
|
298
|
+
text = "".join(block.text for block in final.content if block.type == "text")
|
|
299
|
+
got = json.loads(text[len("done "):])
|
|
300
|
+
check_results([{"tool_use_id": item["id"], "content": item["content"],
|
|
301
|
+
**({"is_error": True} if item["is_error"] else {})} for item in got[:5]])
|
|
302
|
+
assert got[5] == {"id": "t6", "is_error": False, "content": "3"}
|
|
303
|
+
assert [tool["name"] for tool in first_request["tools"]] == TOOL_NAMES + ["add_two_numbers"]
|
|
304
|
+
assert first_request["tools"][1]["input_schema"] == tools_module.SCHEMAS["datacircle_best_plans"]
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def test_the_tool_runner_runs_them(stand_in):
|
|
308
|
+
client = client_of(stand_in)
|
|
309
|
+
for stream in (False, True):
|
|
310
|
+
ASKED.clear()
|
|
311
|
+
runner = client.beta.messages.tool_runner(model="claude-haiku-5-5", max_tokens=1000, stream=stream,
|
|
312
|
+
tools=[*datacircle_tools(), add_two_numbers],
|
|
313
|
+
messages=[{"role": "user", "content": "best email finder?"}])
|
|
314
|
+
if stream:
|
|
315
|
+
final = None
|
|
316
|
+
for each in runner:
|
|
317
|
+
final = each.get_final_message()
|
|
318
|
+
else:
|
|
319
|
+
final = list(runner)[-1]
|
|
320
|
+
check_run(final, ASKED[0])
|
|
321
|
+
assert len(ASKED) == 2 and runner.until_done() == final
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def test_the_async_tool_runner_runs_them(stand_in):
|
|
325
|
+
async def run(stream):
|
|
326
|
+
client = client_of(stand_in, AsyncAnthropic)
|
|
327
|
+
runner = client.beta.messages.tool_runner(model="claude-haiku-5-5", max_tokens=1000, stream=stream,
|
|
328
|
+
tools=[*datacircle_async_tools(), add_two_numbers_async],
|
|
329
|
+
messages=[{"role": "user", "content": "best email finder?"}])
|
|
330
|
+
final = None
|
|
331
|
+
async for each in runner:
|
|
332
|
+
final = await each.get_final_message() if stream else each
|
|
333
|
+
await client.close()
|
|
334
|
+
return final
|
|
335
|
+
|
|
336
|
+
for stream in (False, True):
|
|
337
|
+
ASKED.clear()
|
|
338
|
+
check_run(anyio.run(run, stream), ASKED[0])
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
@pytest.mark.skipif("run_tools_eagerly" not in inspect.signature(Messages.tool_runner).parameters,
|
|
342
|
+
reason="run_tools_eagerly came in a later anthropic")
|
|
343
|
+
def test_run_eagerly_while_the_reply_streams(stand_in):
|
|
344
|
+
ASKED.clear()
|
|
345
|
+
runner = client_of(stand_in).beta.messages.tool_runner(
|
|
346
|
+
model="claude-haiku-5-5", max_tokens=1000, stream=True, run_tools_eagerly=True,
|
|
347
|
+
tools=[*datacircle_tools(), add_two_numbers], messages=[{"role": "user", "content": "best email finder?"}])
|
|
348
|
+
check_run(runner.until_done(), ASKED[0])
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def test_a_loop_of_the_apps_own(stand_in):
|
|
352
|
+
ASKED.clear()
|
|
353
|
+
client = client_of(stand_in)
|
|
354
|
+
definitions = [tool.to_dict() for tool in datacircle_tools()] + [add_two_numbers.to_dict()]
|
|
355
|
+
messages = [{"role": "user", "content": "best email finder?"}]
|
|
356
|
+
reply = client.messages.create(model="claude-haiku-5-5", max_tokens=1000, tools=definitions, messages=messages)
|
|
357
|
+
results = tool_results(reply)
|
|
358
|
+
check_results(results)
|
|
359
|
+
own = [{"type": "tool_result", "tool_use_id": block.id, "content": add_two_numbers.call(block.input)}
|
|
360
|
+
for block in reply.content if block.type == "tool_use" and block.name == "add_two_numbers"]
|
|
361
|
+
messages += [{"role": "assistant", "content": reply.content}, {"role": "user", "content": results + own}]
|
|
362
|
+
final = client.messages.create(model="claude-haiku-5-5", max_tokens=1000, tools=definitions, messages=messages)
|
|
363
|
+
check_run(final, ASKED[0])
|