agentscope-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.
- agentscope_datacircle-0.1.0/.gitignore +4 -0
- agentscope_datacircle-0.1.0/LICENSE +9 -0
- agentscope_datacircle-0.1.0/PKG-INFO +141 -0
- agentscope_datacircle-0.1.0/README.md +124 -0
- agentscope_datacircle-0.1.0/pyproject.toml +32 -0
- agentscope_datacircle-0.1.0/src/agentscope_datacircle/__init__.py +22 -0
- agentscope_datacircle-0.1.0/src/agentscope_datacircle/_api.py +101 -0
- agentscope_datacircle-0.1.0/src/agentscope_datacircle/_plain.py +137 -0
- agentscope_datacircle-0.1.0/src/agentscope_datacircle/_v1.py +68 -0
- agentscope_datacircle-0.1.0/src/agentscope_datacircle/_v2.py +66 -0
- agentscope_datacircle-0.1.0/src/agentscope_datacircle/py.typed +0 -0
- agentscope_datacircle-0.1.0/tests/test_tools.py +454 -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,141 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: agentscope-datacircle
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: AgentScope 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/agentscope-datacircle
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: agents,agentscope,api,api-pricing,b2b-data,datacircle,function-calling,gtm,react,tools
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
14
|
+
Requires-Python: >=3.10
|
|
15
|
+
Requires-Dist: agentscope>=1.0.0
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
|
|
18
|
+
# agentscope-datacircle
|
|
19
|
+
|
|
20
|
+
Find the best GTM APIs. We benchmark all the GTM APIs and we put the results on our website.
|
|
21
|
+
|
|
22
|
+
Our website: https://datacircle.dev
|
|
23
|
+
|
|
24
|
+
This package gives [AgentScope](https://github.com/agentscope-ai/agentscope) four tools that call Datacircle's public API, https://api.datacircle.dev/v1. You need no key and no account.
|
|
25
|
+
|
|
26
|
+
| Tool | Gives | Call |
|
|
27
|
+
| --- | --- | --- |
|
|
28
|
+
| `datacircle_list_apis` | Every GTM API on Datacircle, with the API's slug, number of plans, number of providers and best plan | `GET /apis` |
|
|
29
|
+
| `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` |
|
|
30
|
+
| `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` |
|
|
31
|
+
| `datacircle_provider` | The APIs a provider sells, and the provider's rank on each API | `GET /providers/{slug}` |
|
|
32
|
+
|
|
33
|
+
## Install
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
pip install agentscope-datacircle
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
The package works with AgentScope 2 on Python 3.11 or later, and with AgentScope 1.0 on Python 3.10 or later.
|
|
40
|
+
|
|
41
|
+
## Give the tools to an agent
|
|
42
|
+
|
|
43
|
+
On AgentScope 2, put the tools in the agent's `Toolkit`:
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
import asyncio
|
|
47
|
+
import os
|
|
48
|
+
|
|
49
|
+
import agentscope_datacircle
|
|
50
|
+
from agentscope.agent import Agent
|
|
51
|
+
from agentscope.credential import OpenAICredential
|
|
52
|
+
from agentscope.message import UserMsg
|
|
53
|
+
from agentscope.model import OpenAIChatModel
|
|
54
|
+
from agentscope.tool import Toolkit
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
async def main():
|
|
58
|
+
agent = Agent(
|
|
59
|
+
name="Friday",
|
|
60
|
+
system_prompt="You help people choose an API.",
|
|
61
|
+
model=OpenAIChatModel(
|
|
62
|
+
credential=OpenAICredential(api_key=os.environ["OPENAI_API_KEY"]),
|
|
63
|
+
model="gpt-4.1",
|
|
64
|
+
),
|
|
65
|
+
toolkit=Toolkit(tools=agentscope_datacircle.tools()),
|
|
66
|
+
)
|
|
67
|
+
reply = await agent.reply(UserMsg(name="user", content="Which email finder API is best for under $5 per 1,000?"))
|
|
68
|
+
print(reply.get_text_content())
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
asyncio.run(main())
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
The model picks a tool. The agent runs the tool and gives the model the result. Each tool only reads data, so AgentScope runs it without asking you first, in every permission mode. That includes explore mode.
|
|
75
|
+
|
|
76
|
+
To add the Datacircle tools to your own tools, list them together: `Toolkit(tools=[Bash(), Read(), *agentscope_datacircle.tools()])`. On AgentScope 2.0.5 or later, you can add them to a toolkit you already have: `await toolkit.add_tool(agentscope_datacircle.tools())`. To give an agent only a few Datacircle tools, list only those: `Toolkit(tools=[agentscope_datacircle.DatacircleBestPlans()])`.
|
|
77
|
+
|
|
78
|
+
## AgentScope 1.0
|
|
79
|
+
|
|
80
|
+
On AgentScope 1.0, `register` adds the four tools to a `Toolkit` with `register_tool_function`. A new install of AgentScope 1.0 also needs older mcp and openai packages, and two packages it leaves out, greenlet and tqdm:
|
|
81
|
+
|
|
82
|
+
```bash
|
|
83
|
+
pip install agentscope-datacircle "agentscope<2" "mcp<2" "openai<3.25" greenlet tqdm
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Then:
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
import os
|
|
90
|
+
|
|
91
|
+
import agentscope_datacircle
|
|
92
|
+
from agentscope.agent import ReActAgent
|
|
93
|
+
from agentscope.formatter import OpenAIChatFormatter
|
|
94
|
+
from agentscope.model import OpenAIChatModel
|
|
95
|
+
from agentscope.tool import Toolkit
|
|
96
|
+
|
|
97
|
+
toolkit = Toolkit()
|
|
98
|
+
agentscope_datacircle.register(toolkit)
|
|
99
|
+
|
|
100
|
+
agent = ReActAgent(
|
|
101
|
+
name="Friday",
|
|
102
|
+
sys_prompt="You help people choose an API.",
|
|
103
|
+
model=OpenAIChatModel(model_name="gpt-4.1", api_key=os.environ["OPENAI_API_KEY"]),
|
|
104
|
+
formatter=OpenAIChatFormatter(),
|
|
105
|
+
toolkit=toolkit,
|
|
106
|
+
)
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
To put the tools in a tool group of your own, create the group first and give its name: `agentscope_datacircle.register(toolkit, group_name="datacircle")`. Each tool is also an async function that returns a `ToolResponse`, like `agentscope_datacircle.datacircle_best_plans`.
|
|
110
|
+
|
|
111
|
+
## Call a tool yourself
|
|
112
|
+
|
|
113
|
+
The functions `list_apis`, `best_plans`, `search_plans` and `provider` return each tool's output as Python dicts:
|
|
114
|
+
|
|
115
|
+
```python
|
|
116
|
+
import agentscope_datacircle
|
|
117
|
+
|
|
118
|
+
result = agentscope_datacircle.best_plans("email-finder", limit=3)
|
|
119
|
+
print(result["plans"][0])
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
## Tool output for the model
|
|
123
|
+
|
|
124
|
+
Each result is our API's answer as JSON 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.
|
|
125
|
+
|
|
126
|
+
You can give a provider's name in place of a slug. The tool turns `Bright Data` into `bright-data`.
|
|
127
|
+
|
|
128
|
+
For an unknown slug, the model gets `{"error": ...}` with a list of every valid slug. The model can then pick a valid slug and call the tool again. The tool checks each value from the model before the API call. For a number out of range, the tool makes no API call. The model gets `{"error": ...}` instead. On AgentScope 2, the tool result's state is then `error`.
|
|
129
|
+
|
|
130
|
+
## Network
|
|
131
|
+
|
|
132
|
+
Each tool call makes one HTTPS GET request to https://api.datacircle.dev/v1 and no other network calls. The request holds only the tool's input. The API takes up to 60 calls a minute from one IP address. If the API says to wait, the tool waits up to a minute. The tool waits at most once per call. All plans are in one file at https://datacircle.dev/datacircle.json.
|
|
133
|
+
|
|
134
|
+
## Links
|
|
135
|
+
|
|
136
|
+
- Datacircle: https://datacircle.dev
|
|
137
|
+
- The API: https://datacircle.dev/api
|
|
138
|
+
- The API's spec: https://api.datacircle.dev/v1/openapi.json
|
|
139
|
+
- The meaning of each key: https://datacircle.dev/fields
|
|
140
|
+
|
|
141
|
+
MIT license.
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
# agentscope-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 [AgentScope](https://github.com/agentscope-ai/agentscope) four tools that call Datacircle's public API, https://api.datacircle.dev/v1. You need no key and no account.
|
|
8
|
+
|
|
9
|
+
| 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 agentscope-datacircle
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
The package works with AgentScope 2 on Python 3.11 or later, and with AgentScope 1.0 on Python 3.10 or later.
|
|
23
|
+
|
|
24
|
+
## Give the tools to an agent
|
|
25
|
+
|
|
26
|
+
On AgentScope 2, put the tools in the agent's `Toolkit`:
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
import asyncio
|
|
30
|
+
import os
|
|
31
|
+
|
|
32
|
+
import agentscope_datacircle
|
|
33
|
+
from agentscope.agent import Agent
|
|
34
|
+
from agentscope.credential import OpenAICredential
|
|
35
|
+
from agentscope.message import UserMsg
|
|
36
|
+
from agentscope.model import OpenAIChatModel
|
|
37
|
+
from agentscope.tool import Toolkit
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
async def main():
|
|
41
|
+
agent = Agent(
|
|
42
|
+
name="Friday",
|
|
43
|
+
system_prompt="You help people choose an API.",
|
|
44
|
+
model=OpenAIChatModel(
|
|
45
|
+
credential=OpenAICredential(api_key=os.environ["OPENAI_API_KEY"]),
|
|
46
|
+
model="gpt-4.1",
|
|
47
|
+
),
|
|
48
|
+
toolkit=Toolkit(tools=agentscope_datacircle.tools()),
|
|
49
|
+
)
|
|
50
|
+
reply = await agent.reply(UserMsg(name="user", content="Which email finder API is best for under $5 per 1,000?"))
|
|
51
|
+
print(reply.get_text_content())
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
asyncio.run(main())
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
The model picks a tool. The agent runs the tool and gives the model the result. Each tool only reads data, so AgentScope runs it without asking you first, in every permission mode. That includes explore mode.
|
|
58
|
+
|
|
59
|
+
To add the Datacircle tools to your own tools, list them together: `Toolkit(tools=[Bash(), Read(), *agentscope_datacircle.tools()])`. On AgentScope 2.0.5 or later, you can add them to a toolkit you already have: `await toolkit.add_tool(agentscope_datacircle.tools())`. To give an agent only a few Datacircle tools, list only those: `Toolkit(tools=[agentscope_datacircle.DatacircleBestPlans()])`.
|
|
60
|
+
|
|
61
|
+
## AgentScope 1.0
|
|
62
|
+
|
|
63
|
+
On AgentScope 1.0, `register` adds the four tools to a `Toolkit` with `register_tool_function`. A new install of AgentScope 1.0 also needs older mcp and openai packages, and two packages it leaves out, greenlet and tqdm:
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
pip install agentscope-datacircle "agentscope<2" "mcp<2" "openai<3.25" greenlet tqdm
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Then:
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
import os
|
|
73
|
+
|
|
74
|
+
import agentscope_datacircle
|
|
75
|
+
from agentscope.agent import ReActAgent
|
|
76
|
+
from agentscope.formatter import OpenAIChatFormatter
|
|
77
|
+
from agentscope.model import OpenAIChatModel
|
|
78
|
+
from agentscope.tool import Toolkit
|
|
79
|
+
|
|
80
|
+
toolkit = Toolkit()
|
|
81
|
+
agentscope_datacircle.register(toolkit)
|
|
82
|
+
|
|
83
|
+
agent = ReActAgent(
|
|
84
|
+
name="Friday",
|
|
85
|
+
sys_prompt="You help people choose an API.",
|
|
86
|
+
model=OpenAIChatModel(model_name="gpt-4.1", api_key=os.environ["OPENAI_API_KEY"]),
|
|
87
|
+
formatter=OpenAIChatFormatter(),
|
|
88
|
+
toolkit=toolkit,
|
|
89
|
+
)
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
To put the tools in a tool group of your own, create the group first and give its name: `agentscope_datacircle.register(toolkit, group_name="datacircle")`. Each tool is also an async function that returns a `ToolResponse`, like `agentscope_datacircle.datacircle_best_plans`.
|
|
93
|
+
|
|
94
|
+
## Call a tool yourself
|
|
95
|
+
|
|
96
|
+
The functions `list_apis`, `best_plans`, `search_plans` and `provider` return each tool's output as Python dicts:
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
import agentscope_datacircle
|
|
100
|
+
|
|
101
|
+
result = agentscope_datacircle.best_plans("email-finder", limit=3)
|
|
102
|
+
print(result["plans"][0])
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
## Tool output for the model
|
|
106
|
+
|
|
107
|
+
Each result is our API's answer as JSON 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.
|
|
108
|
+
|
|
109
|
+
You can give a provider's name in place of a slug. The tool turns `Bright Data` into `bright-data`.
|
|
110
|
+
|
|
111
|
+
For an unknown slug, the model gets `{"error": ...}` with a list of every valid slug. The model can then pick a valid slug and call the tool again. The tool checks each value from the model before the API call. For a number out of range, the tool makes no API call. The model gets `{"error": ...}` instead. On AgentScope 2, the tool result's state is then `error`.
|
|
112
|
+
|
|
113
|
+
## Network
|
|
114
|
+
|
|
115
|
+
Each tool call makes one HTTPS GET request to https://api.datacircle.dev/v1 and no other network calls. The request holds only the tool's input. The API takes up to 60 calls a minute from one IP address. If the API says to wait, the tool waits up to a minute. The tool waits at most once per call. All plans are in one file at https://datacircle.dev/datacircle.json.
|
|
116
|
+
|
|
117
|
+
## Links
|
|
118
|
+
|
|
119
|
+
- Datacircle: https://datacircle.dev
|
|
120
|
+
- The API: https://datacircle.dev/api
|
|
121
|
+
- The API's spec: https://api.datacircle.dev/v1/openapi.json
|
|
122
|
+
- The meaning of each key: https://datacircle.dev/fields
|
|
123
|
+
|
|
124
|
+
MIT license.
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "agentscope-datacircle"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "AgentScope tools for the Datacircle API: find the best GTM APIs"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
dependencies = ["agentscope>=1.0.0"]
|
|
13
|
+
keywords = ["agentscope", "agents", "tools", "function-calling", "react", "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/agentscope-datacircle"
|
|
24
|
+
|
|
25
|
+
[dependency-groups]
|
|
26
|
+
test = ["pytest>=8"]
|
|
27
|
+
|
|
28
|
+
[tool.hatch.build.targets.wheel]
|
|
29
|
+
packages = ["src/agentscope_datacircle"]
|
|
30
|
+
|
|
31
|
+
[tool.hatch.build.targets.sdist]
|
|
32
|
+
include = ["src", "tests", "README.md", "LICENSE", "pyproject.toml"]
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""AgentScope tools for Datacircle's open API, https://api.datacircle.dev/v1: every GTM API, who is best for each, every
|
|
2
|
+
plan and a provider's ranks. No key, no account. https://datacircle.dev
|
|
3
|
+
|
|
4
|
+
On AgentScope 2: Toolkit(tools=agentscope_datacircle.tools()). On AgentScope 1: agentscope_datacircle.register(toolkit).
|
|
5
|
+
list_apis, best_plans, search_plans and provider give each tool's answer as a dict, on either."""
|
|
6
|
+
|
|
7
|
+
__version__ = "0.1.0"
|
|
8
|
+
|
|
9
|
+
from agentscope_datacircle._api import DatacircleError
|
|
10
|
+
from agentscope_datacircle._plain import NAMES, best_plans, list_apis, provider, search_plans
|
|
11
|
+
|
|
12
|
+
import importlib.metadata as _metadata
|
|
13
|
+
|
|
14
|
+
# The installed AgentScope's major version, which tools() and register() are made for.
|
|
15
|
+
AGENTSCOPE = int(_metadata.version("agentscope").split(".")[0])
|
|
16
|
+
|
|
17
|
+
if AGENTSCOPE >= 2:
|
|
18
|
+
from agentscope_datacircle._v2 import (DatacircleBestPlans, DatacircleListApis, DatacircleProvider,
|
|
19
|
+
DatacircleSearchPlans, DatacircleTool, register, tools)
|
|
20
|
+
else:
|
|
21
|
+
from agentscope_datacircle._v1 import (datacircle_best_plans, datacircle_list_apis, datacircle_provider,
|
|
22
|
+
datacircle_search_plans, json_schema, register, tools)
|
|
@@ -0,0 +1,101 @@
|
|
|
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
|
+
BASE_URL = "https://api.datacircle.dev/v1"
|
|
14
|
+
TIMEOUT = 30.0
|
|
15
|
+
USER_AGENT = "agentscope-datacircle/0.1.0"
|
|
16
|
+
|
|
17
|
+
# 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.
|
|
18
|
+
PLAN_KEYS = ["api", "rank", "provider", "plan", "score", "perThousand", "notFoundPerThousand", "billing", "pay",
|
|
19
|
+
"currency", "units", "unit", "strengths", "latencyMs", "page", "pricingPage", "docs"]
|
|
20
|
+
API_KEYS = ["api", "slug", "plans", "providers", "best", "bestPage", "sheetPage"]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class DatacircleError(Exception):
|
|
24
|
+
"""The API's refusal in its own words, why it could not be reached, or an argument it can't take: each tool gives
|
|
25
|
+
the model its words as the call's result, {"error": ...}. status is the API's HTTP status, None when
|
|
26
|
+
it gave none; retryable, whether the same call may be answered later (the API out of reach, busy or failing)."""
|
|
27
|
+
|
|
28
|
+
def __init__(self, message: str, status: Optional[int] = None, retryable: bool = False):
|
|
29
|
+
super().__init__(message)
|
|
30
|
+
self.status = status
|
|
31
|
+
self.retryable = retryable
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def brief(item: Dict[str, Any], keys: List[str] = PLAN_KEYS) -> Dict[str, Any]:
|
|
35
|
+
return {key: item[key] for key in keys if item.get(key) is not None}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def slug(value: Any) -> str:
|
|
39
|
+
"""The API's rule for a slug: the name in lowercase letters and digits, the rest a hyphen."""
|
|
40
|
+
plain = unicodedata.normalize("NFKD", str(value or "").strip().lower())
|
|
41
|
+
plain = "".join(char for char in plain if not unicodedata.combining(char))
|
|
42
|
+
return re.sub(r"[^a-z0-9]+", "-", plain).strip("-")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def whole(name: str, value: Any, low: int, high: Optional[int] = None) -> Optional[int]:
|
|
46
|
+
"""A whole number from low to high, or None when left out: a plain call may send one as text."""
|
|
47
|
+
if value is None or value == "":
|
|
48
|
+
return None
|
|
49
|
+
try:
|
|
50
|
+
number = float(value)
|
|
51
|
+
except (TypeError, ValueError):
|
|
52
|
+
number = float("nan")
|
|
53
|
+
if isinstance(value, bool) or not math.isfinite(number) or number != int(number):
|
|
54
|
+
raise DatacircleError(f"{name} must be a whole number, not {value!r}")
|
|
55
|
+
if number < low or (high is not None and number > high):
|
|
56
|
+
raise DatacircleError(f"{name} must be from {low} to {high}, not {int(number)}" if high is not None
|
|
57
|
+
else f"{name} must be {low} or more, not {int(number)}")
|
|
58
|
+
return int(number)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _words(body: bytes) -> str:
|
|
62
|
+
"""A refusal's words: the API's error, with every slug when the slug was unknown."""
|
|
63
|
+
text = body.decode("utf-8", "replace")
|
|
64
|
+
try:
|
|
65
|
+
parsed = json.loads(text)
|
|
66
|
+
if parsed.get("slugs"):
|
|
67
|
+
return f"{parsed['error']}; the slugs: {', '.join(parsed['slugs'])}"
|
|
68
|
+
return str(parsed.get("error", text))
|
|
69
|
+
except (ValueError, KeyError, TypeError, AttributeError):
|
|
70
|
+
return text
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def get(path: str, params: Optional[Dict[str, Any]] = None) -> Any:
|
|
74
|
+
"""The API's JSON answer, or a DatacircleError with its words: waits once when it answers 429."""
|
|
75
|
+
query = urllib.parse.urlencode({key: value for key, value in (params or {}).items() if value not in (None, "")})
|
|
76
|
+
url = f"{BASE_URL.rstrip('/')}{path}" + (f"?{query}" if query else "")
|
|
77
|
+
request = urllib.request.Request(url, headers={"Accept": "application/json", "User-Agent": USER_AGENT})
|
|
78
|
+
for attempt in range(2):
|
|
79
|
+
try:
|
|
80
|
+
with urllib.request.urlopen(request, timeout=TIMEOUT) as answer:
|
|
81
|
+
body = answer.read()
|
|
82
|
+
except urllib.error.HTTPError as error:
|
|
83
|
+
body = error.read()
|
|
84
|
+
if error.code == 429 and not attempt:
|
|
85
|
+
try:
|
|
86
|
+
wait = int(error.headers.get("Retry-After") or 30)
|
|
87
|
+
except ValueError:
|
|
88
|
+
wait = 30
|
|
89
|
+
time.sleep(min(max(wait, 1), 60))
|
|
90
|
+
continue
|
|
91
|
+
if error.code == 429:
|
|
92
|
+
raise DatacircleError("Datacircle's API answered 429 twice: wait a minute and call again", 429, True) from None
|
|
93
|
+
raise DatacircleError(f"Datacircle's API answered {error.code}: {_words(body)[:3000]}", error.code,
|
|
94
|
+
error.code >= 500) from None
|
|
95
|
+
except (urllib.error.URLError, OSError) as error:
|
|
96
|
+
raise DatacircleError(f"Datacircle's API could not be reached: {getattr(error, 'reason', error)}",
|
|
97
|
+
retryable=True) from None
|
|
98
|
+
try:
|
|
99
|
+
return json.loads(body)
|
|
100
|
+
except ValueError as error:
|
|
101
|
+
raise DatacircleError(f"Datacircle's API gave no JSON: {error}") from None
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""The four calls of Datacircle's open API as plain functions giving dicts, and what a model reads of each tool: its
|
|
2
|
+
name, its description and its parameters as a JSON schema. Both AgentScope 1 and 2 tools are made from these."""
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import urllib.parse
|
|
6
|
+
from typing import Any, Dict, Optional
|
|
7
|
+
|
|
8
|
+
from agentscope_datacircle import _api
|
|
9
|
+
|
|
10
|
+
NAMES = ["datacircle_list_apis", "datacircle_best_plans", "datacircle_search_plans", "datacircle_provider"]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _best(plans: Any) -> Optional[Dict[str, Any]]:
|
|
14
|
+
"""A provider's best plan on an API: its lowest rank, a plan with no score having none."""
|
|
15
|
+
ranked = sorted(plans, key=lambda plan: plan.get("rank") if isinstance(plan.get("rank"), (int, float)) else float("inf"))
|
|
16
|
+
return _api.brief(ranked[0], ["plan", "score", "perThousand", "page"]) if ranked else None
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _text(value: Any) -> Optional[str]:
|
|
20
|
+
"""A text argument as the API takes it: a number made text, null left out."""
|
|
21
|
+
return None if value is None else str(value)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def list_apis(query: Optional[str] = None, limit: Optional[int] = None) -> Dict[str, Any]:
|
|
25
|
+
"""Every API on the sheet, those whose name or slug holds the most words of query first: {"total", "apis"}."""
|
|
26
|
+
count = _api.whole("limit", limit, 1, 200) or 20
|
|
27
|
+
apis = _api.get("/apis")
|
|
28
|
+
words = [word for word in str(query or "").lower().replace("-", " ").split() if word]
|
|
29
|
+
held = []
|
|
30
|
+
for index, api in enumerate(apis):
|
|
31
|
+
name = f"{api.get('api', '')} {str(api.get('slug', '')).replace('-', ' ')}".lower()
|
|
32
|
+
matched = sum(word in name for word in words)
|
|
33
|
+
if matched or not words:
|
|
34
|
+
held.append((-matched, index, api))
|
|
35
|
+
found = [_api.brief(api, _api.API_KEYS) for _, _, api in sorted(held, key=lambda h: h[:2])]
|
|
36
|
+
return {"total": len(found), "apis": found[:count]}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def best_plans(slug: Optional[str] = None, limit: Optional[int] = None) -> Dict[str, Any]:
|
|
40
|
+
"""One API's plans best first by score, each with its rank."""
|
|
41
|
+
made = _api.slug(slug)
|
|
42
|
+
if not made:
|
|
43
|
+
raise _api.DatacircleError("Give an API's slug, like 'email-finder'. The list of APIs gives every slug.")
|
|
44
|
+
answer = _api.get(f"/apis/{urllib.parse.quote(made)}/best", {"limit": _api.whole("limit", limit, 1, 50)})
|
|
45
|
+
return {**answer, "plans": [_api.brief(plan) for plan in answer.get("plans") or []]}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def search_plans(api: Optional[str] = None, query: Optional[str] = None, sort: Optional[str] = None,
|
|
49
|
+
limit: Optional[int] = None, offset: Optional[int] = None) -> Dict[str, Any]:
|
|
50
|
+
"""Every plan, or one API's, or those whose provider or plan name holds every word of query: {"total", "offset", "plans"}."""
|
|
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": _text(api), "query": _text(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: Optional[str] = None) -> Dict[str, Any]:
|
|
61
|
+
"""One provider's APIs, its rank on each and its best plan there. A name is made a slug."""
|
|
62
|
+
made = _api.slug(slug)
|
|
63
|
+
if not made:
|
|
64
|
+
raise _api.DatacircleError("Give a provider's slug or name, like 'bright-data' or 'Bright Data'")
|
|
65
|
+
answer = _api.get(f"/providers/{urllib.parse.quote(made)}")
|
|
66
|
+
apis = [{**_api.brief(entry, ["api", "slug", "rank", "bestPage"]), "plans": len(entry.get("plans") or []),
|
|
67
|
+
"best": _best(entry.get("plans") or [])} for entry in answer.get("apis") or []]
|
|
68
|
+
return {**answer, "apis": apis}
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _schema(properties: Dict[str, Any], required: Optional[list] = None) -> Dict[str, Any]:
|
|
72
|
+
return {"type": "object", "properties": properties, "required": required or []}
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
_PRICE = " perThousand is a plan's price of 1,000 items in dollars, pay the plan's whole price in its currency."
|
|
76
|
+
_LIMIT = {"type": "integer", "minimum": 1, "maximum": 50, "description": "How many plans to give, 1 to 50. 10 when left out."}
|
|
77
|
+
|
|
78
|
+
# Each tool: (its description, its parameters, the plain function it calls with them).
|
|
79
|
+
TOOLS = {
|
|
80
|
+
"datacircle_list_apis": (
|
|
81
|
+
"Lists the GTM APIs on Datacircle's sheet (https://datacircle.dev), with each API's slug, how many plans and "
|
|
82
|
+
"providers it has and its best plan. Use it first to find an API's slug. Gives total, the APIs found, and apis, "
|
|
83
|
+
"up to limit of them.",
|
|
84
|
+
_schema({
|
|
85
|
+
"query": {"type": "string", "description": "Words of the API's name or slug, like 'email' or 'linkedin "
|
|
86
|
+
"profile': the APIs that hold the most of them come first. The sheet's order when left out."},
|
|
87
|
+
"limit": {"type": "integer", "minimum": 1, "maximum": 200, "description": "How many APIs to give, 1 to "
|
|
88
|
+
"200. 20 when left out."},
|
|
89
|
+
}),
|
|
90
|
+
lambda args: list_apis(_text(args.get("query")), args.get("limit")),
|
|
91
|
+
),
|
|
92
|
+
"datacircle_best_plans": (
|
|
93
|
+
"Gives an API's plans best first by their score out of 100 on Datacircle's benchmark (https://datacircle.dev), "
|
|
94
|
+
"each with its rank, provider, plan, $ per 1,000 calls and its page: the best providers of an API." + _PRICE,
|
|
95
|
+
_schema({
|
|
96
|
+
"slug": {"type": "string", "description": "The API's slug, like 'email-finder' or 'linkedin-profile'. The "
|
|
97
|
+
"list of APIs gives every slug."},
|
|
98
|
+
"limit": _LIMIT,
|
|
99
|
+
}, ["slug"]),
|
|
100
|
+
lambda args: best_plans(_text(args.get("slug")), args.get("limit")),
|
|
101
|
+
),
|
|
102
|
+
"datacircle_search_plans": (
|
|
103
|
+
"Searches every plan on Datacircle's sheet (https://datacircle.dev), or one API's, by provider or plan name, "
|
|
104
|
+
"sorted by score, provider or price. Gives total, offset and up to limit plans." + _PRICE,
|
|
105
|
+
_schema({
|
|
106
|
+
"api": {"type": "string", "description": "Only this API's plans: its name or slug, like 'email-finder'. A "
|
|
107
|
+
"provider's name goes in query, never here. Every API when left out."},
|
|
108
|
+
"query": {"type": "string", "description": "Words that must all appear in the provider's or plan's name, "
|
|
109
|
+
"like 'bright data'."},
|
|
110
|
+
"sort": {"type": "string", "enum": ["score", "provider", "price"], "description": "score (best first, the "
|
|
111
|
+
"default), provider (A to Z) or price ($ per 1,000, lowest first)."},
|
|
112
|
+
"limit": _LIMIT,
|
|
113
|
+
"offset": {"type": "integer", "minimum": 0, "description": "How many found plans to skip first. 0 when "
|
|
114
|
+
"left out."},
|
|
115
|
+
}),
|
|
116
|
+
lambda args: search_plans(args.get("api"), args.get("query"), args.get("sort"), args.get("limit"),
|
|
117
|
+
args.get("offset")),
|
|
118
|
+
),
|
|
119
|
+
"datacircle_provider": (
|
|
120
|
+
"Gives each API one provider sells and its rank on each on Datacircle's benchmark (https://datacircle.dev), "
|
|
121
|
+
"with its best plan there.",
|
|
122
|
+
_schema({
|
|
123
|
+
"slug": {"type": "string", "description": "The provider's slug, like 'bright-data', or its name, like "
|
|
124
|
+
"'Bright Data': the name is made a slug."},
|
|
125
|
+
}, ["slug"]),
|
|
126
|
+
lambda args: provider(_text(args.get("slug"))),
|
|
127
|
+
),
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def answer(name: str, args: Dict[str, Any]) -> "tuple[str, bool]":
|
|
132
|
+
"""A tool's call with the model's arguments: the answer as JSON text and True, or {"error": ...} and False when the
|
|
133
|
+
API or the tool refused it, in their words, so the model can call again."""
|
|
134
|
+
try:
|
|
135
|
+
return json.dumps(TOOLS[name][2](args), ensure_ascii=False), True
|
|
136
|
+
except _api.DatacircleError as error:
|
|
137
|
+
return json.dumps({"error": str(error)}, ensure_ascii=False), False
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""The four tools for AgentScope 1: async tool functions giving a ToolResponse, which register(toolkit) adds to a
|
|
2
|
+
Toolkit by its register_tool_function, with their JSON schemas, beside an app's own, for a ReActAgent.
|
|
3
|
+
|
|
4
|
+
A function's docstring is the schema AgentScope 1 reads when the function is registered alone. A call runs the API's
|
|
5
|
+
one HTTPS GET in a thread and gives the model the answer as JSON text; a refusal (an unknown slug, a number out of
|
|
6
|
+
range, the API out of reach) is {"error": ...}, so the model can call again."""
|
|
7
|
+
|
|
8
|
+
import asyncio
|
|
9
|
+
import copy
|
|
10
|
+
from typing import Any, Callable, Dict, List, Optional
|
|
11
|
+
|
|
12
|
+
from agentscope.message import TextBlock
|
|
13
|
+
from agentscope.tool import ToolResponse
|
|
14
|
+
|
|
15
|
+
from agentscope_datacircle import _plain
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
async def _respond(name: str, args: Dict[str, Any]) -> ToolResponse:
|
|
19
|
+
text, _ = await asyncio.to_thread(_plain.answer, name, args)
|
|
20
|
+
return ToolResponse(content=[TextBlock(type="text", text=text)])
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
async def datacircle_list_apis(query: Optional[str] = None, limit: Optional[int] = None) -> ToolResponse:
|
|
24
|
+
return await _respond("datacircle_list_apis", {"query": query, "limit": limit})
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
async def datacircle_best_plans(slug: str, limit: Optional[int] = None) -> ToolResponse:
|
|
28
|
+
return await _respond("datacircle_best_plans", {"slug": slug, "limit": limit})
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
async def datacircle_search_plans(api: Optional[str] = None, query: Optional[str] = None, sort: Optional[str] = None,
|
|
32
|
+
limit: Optional[int] = None, offset: Optional[int] = None) -> ToolResponse:
|
|
33
|
+
return await _respond("datacircle_search_plans", {"api": api, "query": query, "sort": sort, "limit": limit,
|
|
34
|
+
"offset": offset})
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
async def datacircle_provider(slug: str) -> ToolResponse:
|
|
38
|
+
return await _respond("datacircle_provider", {"slug": slug})
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
FUNCTIONS: List[Callable[..., Any]] = [datacircle_list_apis, datacircle_best_plans, datacircle_search_plans,
|
|
42
|
+
datacircle_provider]
|
|
43
|
+
_TYPES = {"string": "str", "integer": "int"}
|
|
44
|
+
|
|
45
|
+
for _function in FUNCTIONS:
|
|
46
|
+
_description, _schema, _ = _plain.TOOLS[_function.__name__]
|
|
47
|
+
_function.__doc__ = _description + "\n\nArgs:\n" + "".join(
|
|
48
|
+
f" {key} (`{_TYPES[spec['type']]}`{'' if key in _schema['required'] else ', optional'}):\n"
|
|
49
|
+
f" {spec['description']}\n" for key, spec in _schema["properties"].items())
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def json_schema(name: str) -> Dict[str, Any]:
|
|
53
|
+
"""A tool's schema as AgentScope 1's register_tool_function takes it."""
|
|
54
|
+
description, schema, _ = _plain.TOOLS[name]
|
|
55
|
+
return {"type": "function", "function": {"name": name, "description": description,
|
|
56
|
+
"parameters": copy.deepcopy(schema)}}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def tools() -> List[Callable[..., Any]]:
|
|
60
|
+
"""The four tool functions."""
|
|
61
|
+
return list(FUNCTIONS)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def register(toolkit: Any, group_name: str = "basic") -> None:
|
|
65
|
+
"""Adds the four tools to an AgentScope 1 Toolkit, in its basic group (always active) or in group_name, a group
|
|
66
|
+
made with toolkit.create_tool_group first."""
|
|
67
|
+
for function in FUNCTIONS:
|
|
68
|
+
toolkit.register_tool_function(function, group_name=group_name, json_schema=json_schema(function.__name__))
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""The four tools for AgentScope 2: ToolBase objects for a Toolkit's tools (Toolkit(tools=tools()), or
|
|
2
|
+
await toolkit.add_tool(tools()) on a toolkit that exists), beside an app's own tools, for an Agent's ReAct loop.
|
|
3
|
+
|
|
4
|
+
Each is read-only, so the permission engine allows it in every mode, explore mode too, and its check_permissions allows
|
|
5
|
+
it too, so no user is asked to confirm a call. A call runs the API's one HTTPS GET in a thread and gives the model the
|
|
6
|
+
answer as JSON text in a ToolChunk; a refusal (an unknown slug, a number out of range, the API out of reach) is
|
|
7
|
+
{"error": ...} in a ToolChunk whose state is error, so the model can call again."""
|
|
8
|
+
|
|
9
|
+
import asyncio
|
|
10
|
+
import copy
|
|
11
|
+
from typing import Any, List
|
|
12
|
+
|
|
13
|
+
from agentscope.message import TextBlock, ToolResultState
|
|
14
|
+
from agentscope.permission import PermissionBehavior, PermissionDecision
|
|
15
|
+
from agentscope.tool import ToolBase, ToolChunk
|
|
16
|
+
|
|
17
|
+
from agentscope_datacircle import _plain
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class DatacircleTool(ToolBase):
|
|
21
|
+
"""One call of Datacircle's open API: its name, description and input_schema are the model's, its call the API's."""
|
|
22
|
+
|
|
23
|
+
is_concurrency_safe = True
|
|
24
|
+
is_read_only = True
|
|
25
|
+
|
|
26
|
+
def __init__(self, **kwargs: Any) -> None:
|
|
27
|
+
super().__init__(**kwargs)
|
|
28
|
+
self.input_schema = copy.deepcopy(type(self).input_schema)
|
|
29
|
+
|
|
30
|
+
async def check_permissions(self, *args: Any, **kwargs: Any) -> PermissionDecision:
|
|
31
|
+
return PermissionDecision(behavior=PermissionBehavior.ALLOW,
|
|
32
|
+
message=f"{self.name} only reads Datacircle's open API.")
|
|
33
|
+
|
|
34
|
+
async def call(self, **kwargs: Any) -> ToolChunk:
|
|
35
|
+
kwargs.pop("_agent_state", None)
|
|
36
|
+
text, ok = await asyncio.to_thread(_plain.answer, self.name, kwargs)
|
|
37
|
+
if ok:
|
|
38
|
+
return ToolChunk(content=[TextBlock(text=text)])
|
|
39
|
+
return ToolChunk(content=[TextBlock(text=text)], state=ToolResultState.ERROR)
|
|
40
|
+
|
|
41
|
+
if not hasattr(ToolBase, "call"): # AgentScope 2.0.0 calls a tool's __call__, later ones its call
|
|
42
|
+
async def __call__(self, **kwargs: Any) -> ToolChunk:
|
|
43
|
+
return await self.call(**kwargs)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _tool(name: str, class_name: str) -> type:
|
|
47
|
+
description, schema, _ = _plain.TOOLS[name]
|
|
48
|
+
return type(class_name, (DatacircleTool,), {"name": name, "description": description, "input_schema": schema,
|
|
49
|
+
"__doc__": description, "__module__": __name__})
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
DatacircleListApis = _tool("datacircle_list_apis", "DatacircleListApis")
|
|
53
|
+
DatacircleBestPlans = _tool("datacircle_best_plans", "DatacircleBestPlans")
|
|
54
|
+
DatacircleSearchPlans = _tool("datacircle_search_plans", "DatacircleSearchPlans")
|
|
55
|
+
DatacircleProvider = _tool("datacircle_provider", "DatacircleProvider")
|
|
56
|
+
CLASSES = [DatacircleListApis, DatacircleBestPlans, DatacircleSearchPlans, DatacircleProvider]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def tools() -> List[DatacircleTool]:
|
|
60
|
+
"""The four tools, new objects each time, for Toolkit(tools=[...]) or toolkit.add_tool(...)."""
|
|
61
|
+
return [cls() for cls in CLASSES]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def register(toolkit: Any, group_name: str = "basic") -> None:
|
|
65
|
+
raise TypeError("AgentScope 2 takes tools in Toolkit(tools=...) or await toolkit.add_tool(...): "
|
|
66
|
+
"give it agentscope_datacircle.tools()")
|
|
File without changes
|
|
@@ -0,0 +1,454 @@
|
|
|
1
|
+
"""Offline tests: the tools against a local stand-in for the API on 127.0.0.1, by their plain functions, by the
|
|
2
|
+
installed AgentScope's Toolkit, and run by its agent (AgentScope 2's Agent, AgentScope 1's ReActAgent) on a scripted
|
|
3
|
+
OpenAI-compatible model, also on 127.0.0.1. Each version's tests skip on the other."""
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import json
|
|
7
|
+
import threading
|
|
8
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
9
|
+
from urllib.parse import parse_qs, urlparse
|
|
10
|
+
|
|
11
|
+
import pytest
|
|
12
|
+
|
|
13
|
+
import agentscope_datacircle as dc
|
|
14
|
+
from agentscope_datacircle import _api
|
|
15
|
+
|
|
16
|
+
V2 = dc.AGENTSCOPE >= 2
|
|
17
|
+
only2 = pytest.mark.skipif(not V2, reason="AgentScope 2's tools")
|
|
18
|
+
only1 = pytest.mark.skipif(V2, reason="AgentScope 1's tools")
|
|
19
|
+
|
|
20
|
+
PLAN = {"api": "Employee email", "rank": 1, "provider": "Hunter", "plan": "Starter", "score": 80.1, "perThousand": 4.9,
|
|
21
|
+
"page": "https://datacircle.dev/x", "terms": "long", "aggregators": ["a"]}
|
|
22
|
+
BRIEF = {key: value for key, value in PLAN.items() if key not in ("terms", "aggregators")}
|
|
23
|
+
SEEN = []
|
|
24
|
+
BUSY = []
|
|
25
|
+
ASKED = []
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def text_of(content):
|
|
29
|
+
return content if isinstance(content, str) else "".join(part.get("text", "") for part in content or [])
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def script_start(messages):
|
|
33
|
+
"""The index of the last user message with a CALL line, else of the last user message: AgentScope 2 adds a user
|
|
34
|
+
message of its own after the user's, a reminder of the time."""
|
|
35
|
+
users = [i for i, m in enumerate(messages) if m.get("role") == "user"]
|
|
36
|
+
return max([i for i in users if "CALL " in text_of(messages[i].get("content"))] or users)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class Handler(BaseHTTPRequestHandler):
|
|
40
|
+
"""The API's stand-in on GET, the scripted model's on POST /v1/chat/completions: the last user message's with
|
|
41
|
+
`CALL <tool> <json>` lines are the tool calls it makes, a batch a turn (a `THEN` line ends a batch), then
|
|
42
|
+
`DONE <results>` once the request holds a result for each."""
|
|
43
|
+
|
|
44
|
+
def log_message(self, *args):
|
|
45
|
+
pass
|
|
46
|
+
|
|
47
|
+
def reply(self, status, body, headers=None, kind="application/json"):
|
|
48
|
+
data = body.encode() if isinstance(body, str) else json.dumps(body).encode()
|
|
49
|
+
self.send_response(status)
|
|
50
|
+
for key, value in {"Content-Type": kind, "Content-Length": str(len(data)), **(headers or {})}.items():
|
|
51
|
+
self.send_header(key, value)
|
|
52
|
+
self.end_headers()
|
|
53
|
+
self.wfile.write(data)
|
|
54
|
+
|
|
55
|
+
def do_GET(self):
|
|
56
|
+
url = urlparse(self.path)
|
|
57
|
+
query = {key: values[0] for key, values in parse_qs(url.query).items()}
|
|
58
|
+
SEEN.append((url.path, query, self.headers.get("User-Agent")))
|
|
59
|
+
if url.path == "/v1/plans" and query.get("query") == "busy" and not BUSY:
|
|
60
|
+
BUSY.append(1)
|
|
61
|
+
return self.reply(429, {"error": "slow down"}, {"Retry-After": "1"})
|
|
62
|
+
if url.path == "/v1/apis":
|
|
63
|
+
return self.reply(200, [{"api": "Employee email", "slug": "email-finder", "plans": 9, "providers": 3, "extra": 1},
|
|
64
|
+
{"api": "Employee profile", "slug": "linkedin-profile", "plans": 4, "providers": 2}])
|
|
65
|
+
if url.path == "/v1/apis/email-finder/best":
|
|
66
|
+
return self.reply(200, {"api": "Employee email", "slug": "email-finder", "total": 1, "plans": [PLAN]})
|
|
67
|
+
if url.path.startswith("/v1/apis/"):
|
|
68
|
+
return self.reply(404, {"error": "no API has the slug nope", "slugs": ["email-finder", "linkedin-profile"]})
|
|
69
|
+
if url.path == "/v1/plans" and query.get("query") == "down":
|
|
70
|
+
return self.reply(503, {"error": "down for a minute"})
|
|
71
|
+
if url.path == "/v1/plans":
|
|
72
|
+
return self.reply(200, {"total": 1, "offset": 0, "plans": [PLAN]})
|
|
73
|
+
if url.path == "/v1/providers/bright-data":
|
|
74
|
+
return self.reply(200, {"provider": "Bright Data", "slug": "bright-data", "website": "https://brightdata.com",
|
|
75
|
+
"apis": [{"api": "Employee email", "slug": "email-finder", "rank": 7, "sheetPage": "s",
|
|
76
|
+
"plans": [dict(PLAN, rank=9, plan="B"), dict(PLAN, rank=7, plan="A")]}]})
|
|
77
|
+
return self.reply(404, {"error": "no provider has this slug"})
|
|
78
|
+
|
|
79
|
+
def do_POST(self):
|
|
80
|
+
body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}")
|
|
81
|
+
ASKED.append(body)
|
|
82
|
+
messages = body.get("messages", [])
|
|
83
|
+
start = script_start(messages)
|
|
84
|
+
results = [text_of(m.get("content")) for m in messages[start:] if m.get("role") == "tool"]
|
|
85
|
+
batches, batch = [], []
|
|
86
|
+
for line in text_of(messages[start]["content"]).splitlines():
|
|
87
|
+
if line.startswith("CALL "):
|
|
88
|
+
_, name, given = line.split(" ", 2)
|
|
89
|
+
batch.append({"type": "function", "function": {"name": name, "arguments": given}})
|
|
90
|
+
elif line == "THEN" and batch:
|
|
91
|
+
batches, batch = batches + [batch], []
|
|
92
|
+
batches += [batch] if batch else []
|
|
93
|
+
calls, done = [], 0
|
|
94
|
+
for each in batches:
|
|
95
|
+
if done + len(each) > len(results):
|
|
96
|
+
calls = [dict(call, id=f"call_{done + i}") for i, call in enumerate(each)]
|
|
97
|
+
break
|
|
98
|
+
done += len(each)
|
|
99
|
+
content = None if calls else "DONE " + " | ".join(results)
|
|
100
|
+
if not body.get("stream"):
|
|
101
|
+
message = {"role": "assistant", "content": content, **({"tool_calls": calls} if calls else {})}
|
|
102
|
+
return self.reply(200, {"id": "chatcmpl-1", "object": "chat.completion", "created": 1, "model": body.get("model"),
|
|
103
|
+
"choices": [{"index": 0, "message": message,
|
|
104
|
+
"finish_reason": "tool_calls" if calls else "stop"}],
|
|
105
|
+
"usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}})
|
|
106
|
+
chunks = [({"role": "assistant", "content": content or ""}, None)]
|
|
107
|
+
for index, call in enumerate(calls):
|
|
108
|
+
chunks.append(({"tool_calls": [{"index": index, "id": call["id"], "type": "function",
|
|
109
|
+
"function": {"name": call["function"]["name"], "arguments": ""}}]}, None))
|
|
110
|
+
chunks.append(({"tool_calls": [{"index": index, "function": {"arguments": call["function"]["arguments"]}}]}, None))
|
|
111
|
+
chunks.append(({}, "tool_calls" if calls else "stop"))
|
|
112
|
+
events = "".join("data: " + json.dumps({"id": "chatcmpl-1", "object": "chat.completion.chunk", "created": 1,
|
|
113
|
+
"model": body.get("model"),
|
|
114
|
+
"choices": [{"index": 0, "delta": delta, "finish_reason": reason}]}) + "\n\n"
|
|
115
|
+
for delta, reason in chunks)
|
|
116
|
+
self.reply(200, events + "data: [DONE]\n\n", kind="text/event-stream")
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
@pytest.fixture(scope="module", autouse=True)
|
|
120
|
+
def stand_in():
|
|
121
|
+
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
|
122
|
+
threading.Thread(target=server.serve_forever, daemon=True).start()
|
|
123
|
+
base = _api.BASE_URL
|
|
124
|
+
_api.BASE_URL = f"http://127.0.0.1:{server.server_address[1]}/v1"
|
|
125
|
+
yield f"http://127.0.0.1:{server.server_address[1]}/v1"
|
|
126
|
+
_api.BASE_URL = base
|
|
127
|
+
server.shutdown()
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def last_results():
|
|
131
|
+
"""The tool results the scripted model got in its last request, in the order of its calls (an agent that runs
|
|
132
|
+
them at once may give them in the order they finished)."""
|
|
133
|
+
messages = ASKED[-1]["messages"]
|
|
134
|
+
tools = [m for m in messages[script_start(messages):] if m.get("role") == "tool"]
|
|
135
|
+
return [text_of(m.get("content")) for m in sorted(tools, key=lambda m: int(m["tool_call_id"].split("_")[1]))]
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
SCRIPT = ('CALL datacircle_best_plans {"slug": "email-finder", "limit": 1}\n'
|
|
139
|
+
'CALL datacircle_provider {"slug": "Bright Data"}\n'
|
|
140
|
+
'CALL datacircle_best_plans {"slug": "nope"}\n'
|
|
141
|
+
'CALL datacircle_list_apis {"query": "email"}\n'
|
|
142
|
+
'CALL datacircle_search_plans {"query": "hunter", "sort": "price", "limit": 5}\n'
|
|
143
|
+
'CALL app_add {"a": 2, "b": 3}')
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def check_script_results(results):
|
|
147
|
+
assert json.loads(results[0])["plans"] == [BRIEF]
|
|
148
|
+
assert json.loads(results[1])["provider"] == "Bright Data"
|
|
149
|
+
assert "no API has the slug nope" in results[2] and "email-finder, linkedin-profile" in results[2]
|
|
150
|
+
assert json.loads(results[3])["apis"][0]["slug"] == "email-finder"
|
|
151
|
+
assert json.loads(results[4])["plans"] == [BRIEF]
|
|
152
|
+
assert "SUM 5" in results[5]
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
# Both versions: the plain functions and what the API is sent.
|
|
156
|
+
|
|
157
|
+
def test_plain_functions():
|
|
158
|
+
assert dc.NAMES == ["datacircle_list_apis", "datacircle_best_plans", "datacircle_search_plans", "datacircle_provider"]
|
|
159
|
+
assert dc.list_apis("email", 1) == {"total": 1, "apis": [{"api": "Employee email", "slug": "email-finder", "plans": 9,
|
|
160
|
+
"providers": 3}]}
|
|
161
|
+
assert dc.list_apis()["total"] == 2
|
|
162
|
+
assert dc.best_plans("email-finder", 1)["plans"] == [BRIEF]
|
|
163
|
+
assert SEEN[-1][1] == {"limit": "1"} and SEEN[-1][2] == f"agentscope-datacircle/{dc.__version__}"
|
|
164
|
+
assert dc.search_plans("email-finder", "hunter", "price", "5", 2)["plans"] == [BRIEF]
|
|
165
|
+
assert SEEN[-1][1] == {"api": "email-finder", "query": "hunter", "sort": "price", "limit": "5", "offset": "2"}
|
|
166
|
+
sold = dc.provider("Bright Data")
|
|
167
|
+
assert SEEN[-1][0] == "/v1/providers/bright-data"
|
|
168
|
+
assert sold["apis"] == [{"api": "Employee email", "slug": "email-finder", "rank": 7, "plans": 2,
|
|
169
|
+
"best": {"plan": "A", "score": 80.1, "perThousand": 4.9, "page": "https://datacircle.dev/x"}}]
|
|
170
|
+
with pytest.raises(dc.DatacircleError) as refused:
|
|
171
|
+
dc.best_plans("nope")
|
|
172
|
+
assert refused.value.status == 404 and "email-finder, linkedin-profile" in str(refused.value)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def test_refusals_make_no_call():
|
|
176
|
+
from agentscope_datacircle import _plain
|
|
177
|
+
before = len(SEEN)
|
|
178
|
+
for name, args, words in [("datacircle_best_plans", {"slug": "email-finder", "limit": 0}, "limit must be from 1 to 50, not 0"),
|
|
179
|
+
("datacircle_best_plans", {"slug": " "}, "Give an API's slug"),
|
|
180
|
+
("datacircle_search_plans", {"sort": "cheap"}, "sort must be score, provider or price"),
|
|
181
|
+
("datacircle_search_plans", {"offset": -1}, "offset must be 0 or more"),
|
|
182
|
+
("datacircle_list_apis", {"limit": True}, "limit must be a whole number"),
|
|
183
|
+
("datacircle_provider", {}, "Give a provider's slug")]:
|
|
184
|
+
text, ok = _plain.answer(name, args)
|
|
185
|
+
assert not ok and words in json.loads(text)["error"], (name, text)
|
|
186
|
+
assert len(SEEN) == before
|
|
187
|
+
text, ok = _plain.answer("datacircle_search_plans", {"query": "down"})
|
|
188
|
+
assert not ok and "503" in text and "down for a minute" in text
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def test_waits_once_on_429():
|
|
192
|
+
assert dc.search_plans(query="busy")["total"] == 1 and BUSY
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
# AgentScope 2: ToolBase tools in a Toolkit, its permission engine, its Agent.
|
|
196
|
+
|
|
197
|
+
def call2(toolkit, name, args, state=None):
|
|
198
|
+
from agentscope.message import ToolCallBlock
|
|
199
|
+
from agentscope.state import AgentState
|
|
200
|
+
|
|
201
|
+
async def run():
|
|
202
|
+
last = None
|
|
203
|
+
async for item in toolkit.call_tool(ToolCallBlock(id="c1", name=name, input=json.dumps(args)), state or AgentState()):
|
|
204
|
+
last = item
|
|
205
|
+
return last
|
|
206
|
+
return asyncio.run(run())
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def app_tools():
|
|
210
|
+
"""An app's own tools beside ours: a read-only adder its check allows, and a writing tool it leaves to the engine."""
|
|
211
|
+
from agentscope.message import TextBlock
|
|
212
|
+
from agentscope.permission import PermissionBehavior, PermissionDecision
|
|
213
|
+
from agentscope.tool import ToolBase, ToolChunk
|
|
214
|
+
|
|
215
|
+
class Add(ToolBase):
|
|
216
|
+
name = "app_add"
|
|
217
|
+
description = "Adds two numbers."
|
|
218
|
+
input_schema = {"type": "object", "properties": {"a": {"type": "integer"}, "b": {"type": "integer"}},
|
|
219
|
+
"required": ["a", "b"]}
|
|
220
|
+
is_concurrency_safe = True
|
|
221
|
+
is_read_only = True
|
|
222
|
+
|
|
223
|
+
async def check_permissions(self, *args, **kwargs):
|
|
224
|
+
return PermissionDecision(behavior=PermissionBehavior.ALLOW, message="adds")
|
|
225
|
+
|
|
226
|
+
async def call(self, a, b):
|
|
227
|
+
return ToolChunk(content=[TextBlock(text=f"SUM {a + b}")])
|
|
228
|
+
|
|
229
|
+
__call__ = call if not hasattr(ToolBase, "call") else ToolBase.__call__
|
|
230
|
+
|
|
231
|
+
class Note(Add):
|
|
232
|
+
name = "app_note"
|
|
233
|
+
description = "Writes a note."
|
|
234
|
+
input_schema = {"type": "object", "properties": {"text": {"type": "string"}}, "required": ["text"]}
|
|
235
|
+
is_read_only = False
|
|
236
|
+
|
|
237
|
+
async def check_permissions(self, *args, **kwargs):
|
|
238
|
+
return PermissionDecision(behavior=PermissionBehavior.PASSTHROUGH, message="writes")
|
|
239
|
+
|
|
240
|
+
async def call(self, text):
|
|
241
|
+
return ToolChunk(content=[TextBlock(text="NOTED")])
|
|
242
|
+
|
|
243
|
+
__call__ = call if not hasattr(ToolBase, "call") else ToolBase.__call__
|
|
244
|
+
|
|
245
|
+
return Add(), Note()
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
@only2
|
|
249
|
+
def test_v2_toolkit_schemas():
|
|
250
|
+
from agentscope.tool import Toolkit
|
|
251
|
+
tools = dc.tools()
|
|
252
|
+
assert [type(t) for t in tools] == [dc.DatacircleListApis, dc.DatacircleBestPlans, dc.DatacircleSearchPlans,
|
|
253
|
+
dc.DatacircleProvider]
|
|
254
|
+
assert all(isinstance(t, dc.DatacircleTool) and t.is_read_only and t.is_concurrency_safe for t in tools)
|
|
255
|
+
assert tools[0] is not dc.tools()[0]
|
|
256
|
+
schemas = asyncio.run(Toolkit(tools=tools).get_tool_schemas())
|
|
257
|
+
assert [s["function"]["name"] for s in schemas] == dc.NAMES
|
|
258
|
+
for schema in schemas:
|
|
259
|
+
assert "datacircle.dev" in schema["function"]["description"]
|
|
260
|
+
assert schema["function"]["parameters"]["type"] == "object"
|
|
261
|
+
assert schemas[1]["function"]["parameters"]["required"] == ["slug"]
|
|
262
|
+
assert schemas[2]["function"]["parameters"]["properties"]["sort"]["enum"] == ["score", "provider", "price"]
|
|
263
|
+
with pytest.raises(TypeError, match="Toolkit\\(tools=...\\)"):
|
|
264
|
+
dc.register(Toolkit())
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
@only2
|
|
268
|
+
def test_v2_toolkit_calls():
|
|
269
|
+
from agentscope.message import ToolResultState
|
|
270
|
+
from agentscope.tool import Toolkit
|
|
271
|
+
toolkit = Toolkit(tools=dc.tools())
|
|
272
|
+
best = call2(toolkit, "datacircle_best_plans", {"slug": "email-finder", "limit": 1})
|
|
273
|
+
assert best.state == ToolResultState.SUCCESS and json.loads(best.content[0].text)["plans"] == [BRIEF]
|
|
274
|
+
sold = call2(toolkit, "datacircle_provider", {"slug": "Bright Data"})
|
|
275
|
+
assert json.loads(sold.content[0].text)["slug"] == "bright-data"
|
|
276
|
+
listed = call2(toolkit, "datacircle_list_apis", {})
|
|
277
|
+
assert json.loads(listed.content[0].text)["total"] == 2
|
|
278
|
+
found = call2(toolkit, "datacircle_search_plans", {"api": "email-finder", "sort": "price", "limit": "5", "extra": 1})
|
|
279
|
+
assert json.loads(found.content[0].text)["plans"] == [BRIEF] and SEEN[-1][1]["limit"] == "5"
|
|
280
|
+
unknown = call2(toolkit, "datacircle_best_plans", {"slug": "nope"})
|
|
281
|
+
assert unknown.state == ToolResultState.ERROR and "the slugs: email-finder" in json.loads(unknown.content[0].text)["error"]
|
|
282
|
+
low = call2(toolkit, "datacircle_best_plans", {"slug": "email-finder", "limit": 0})
|
|
283
|
+
assert low.state == ToolResultState.ERROR and "limit must be from 1 to 50" in low.content[0].text
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
@only2
|
|
287
|
+
def test_v2_add_tool_and_group():
|
|
288
|
+
from agentscope.tool import Toolkit, ToolGroup
|
|
289
|
+
add, _ = app_tools()
|
|
290
|
+
if hasattr(Toolkit, "add_tool"): # since 2.0.5
|
|
291
|
+
toolkit = Toolkit(tools=[add])
|
|
292
|
+
asyncio.run(toolkit.add_tool(dc.tools()))
|
|
293
|
+
assert [s["function"]["name"] for s in asyncio.run(toolkit.get_tool_schemas())] == ["app_add"] + dc.NAMES
|
|
294
|
+
grouped = Toolkit(tool_groups=[ToolGroup(name="datacircle", description="Datacircle's GTM API tools.",
|
|
295
|
+
tools=dc.tools())])
|
|
296
|
+
names = [s["function"]["name"] for s in asyncio.run(grouped.get_tool_schemas())]
|
|
297
|
+
assert "reset_tools" in names and "datacircle_best_plans" not in names
|
|
298
|
+
assert [s["function"]["name"] for s in asyncio.run(grouped.get_tool_schemas(["datacircle"]))][-4:] == dc.NAMES
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
@only2
|
|
302
|
+
@pytest.mark.parametrize("mode", ["DEFAULT", "EXPLORE", "ACCEPT_EDITS", "BYPASS", "DONT_ASK"])
|
|
303
|
+
def test_v2_permission_allows_in_every_mode(mode):
|
|
304
|
+
from agentscope.permission import PermissionBehavior, PermissionContext, PermissionEngine, PermissionMode
|
|
305
|
+
engine = PermissionEngine(PermissionContext(mode=PermissionMode[mode]))
|
|
306
|
+
for tool in dc.tools():
|
|
307
|
+
decision = asyncio.run(engine.check_permission(tool, {"slug": "email-finder"}))
|
|
308
|
+
assert decision.behavior == PermissionBehavior.ALLOW, (mode, tool.name, decision)
|
|
309
|
+
_, note = app_tools()
|
|
310
|
+
if mode in ("EXPLORE", "DONT_ASK"):
|
|
311
|
+
assert asyncio.run(engine.check_permission(note, {"text": "x"})).behavior == PermissionBehavior.DENY
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def agent2(stand_in, toolkit, stream, mode=None):
|
|
315
|
+
from agentscope.agent import Agent
|
|
316
|
+
from agentscope.credential import OpenAICredential
|
|
317
|
+
from agentscope.model import OpenAIChatModel
|
|
318
|
+
from agentscope.permission import PermissionContext, PermissionMode
|
|
319
|
+
from agentscope.state import AgentState
|
|
320
|
+
state = AgentState(permission_context=PermissionContext(mode=PermissionMode[mode])) if mode else None
|
|
321
|
+
return Agent(name="Friday", system_prompt="You help people choose an API.",
|
|
322
|
+
model=OpenAIChatModel(credential=OpenAICredential(api_key="scripted", base_url=stand_in),
|
|
323
|
+
model="scripted", stream=stream),
|
|
324
|
+
toolkit=toolkit, state=state)
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def ask2(agent, text):
|
|
328
|
+
from agentscope.message import UserMsg
|
|
329
|
+
return asyncio.run(agent.reply(UserMsg(name="user", content=text)))
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
@only2
|
|
333
|
+
@pytest.mark.parametrize("stream", [False, True])
|
|
334
|
+
def test_v2_agent_runs_the_tools(stand_in, stream):
|
|
335
|
+
from agentscope.tool import Toolkit
|
|
336
|
+
add, _ = app_tools()
|
|
337
|
+
agent = agent2(stand_in, Toolkit(tools=[add, *dc.tools()]), stream)
|
|
338
|
+
reply = ask2(agent, SCRIPT)
|
|
339
|
+
sent = [t["function"]["name"] for t in ASKED[-2].get("tools") or []]
|
|
340
|
+
assert all(name in sent for name in dc.NAMES + ["app_add"])
|
|
341
|
+
check_script_results(last_results())
|
|
342
|
+
assert reply.get_text_content().startswith("DONE ")
|
|
343
|
+
again = ask2(agent, 'CALL datacircle_best_plans {"slug": "email-finder", "limit": 1}')
|
|
344
|
+
assert json.loads(last_results()[-1])["plans"] == [BRIEF] and again.get_text_content().startswith("DONE ")
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
@only2
|
|
348
|
+
def test_v2_agent_in_explore_mode(stand_in):
|
|
349
|
+
"""Explore mode runs our read-only tools and denies the app's writing one."""
|
|
350
|
+
from agentscope.tool import Toolkit
|
|
351
|
+
add, note = app_tools()
|
|
352
|
+
agent = agent2(stand_in, Toolkit(tools=[add, note, *dc.tools()]), False, "EXPLORE")
|
|
353
|
+
reply = ask2(agent, 'CALL datacircle_provider {"slug": "bright-data"}\nCALL app_note {"text": "x"}')
|
|
354
|
+
results = last_results()
|
|
355
|
+
assert json.loads(results[0])["slug"] == "bright-data"
|
|
356
|
+
assert "NOTED" not in results[1] and "explore" in results[1].lower()
|
|
357
|
+
assert reply.get_text_content().startswith("DONE ")
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
@only2
|
|
361
|
+
def test_v2_agent_activates_a_group(stand_in):
|
|
362
|
+
"""Tools in a group of their own, which the agent turns on by the Toolkit's meta tool first."""
|
|
363
|
+
from agentscope.tool import Toolkit, ToolGroup
|
|
364
|
+
toolkit = Toolkit(tool_groups=[ToolGroup(name="datacircle", description="Datacircle's GTM API tools.",
|
|
365
|
+
tools=dc.tools())])
|
|
366
|
+
reply = ask2(agent2(stand_in, toolkit, True), 'CALL reset_tools {"datacircle": true}\nTHEN\n'
|
|
367
|
+
'CALL datacircle_best_plans {"slug": "email-finder", "limit": 1}')
|
|
368
|
+
assert "datacircle_best_plans" in [t["function"]["name"] for t in ASKED[-2].get("tools") or []]
|
|
369
|
+
assert json.loads(last_results()[1])["plans"] == [BRIEF] and reply.get_text_content().startswith("DONE ")
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
# AgentScope 1: tool functions registered in a Toolkit, its ReActAgent.
|
|
373
|
+
|
|
374
|
+
def call1(toolkit, name, args):
|
|
375
|
+
from agentscope.message import ToolUseBlock
|
|
376
|
+
|
|
377
|
+
async def run():
|
|
378
|
+
last = None
|
|
379
|
+
async for item in await toolkit.call_tool_function(ToolUseBlock(type="tool_use", id="c1", name=name, input=args)):
|
|
380
|
+
last = item
|
|
381
|
+
return last
|
|
382
|
+
return asyncio.run(run()).content[0]["text"]
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def app_add_v1(a: int, b: int):
|
|
386
|
+
"""Adds two numbers.
|
|
387
|
+
|
|
388
|
+
Args:
|
|
389
|
+
a (`int`): A number.
|
|
390
|
+
b (`int`): Another number.
|
|
391
|
+
"""
|
|
392
|
+
from agentscope.message import TextBlock
|
|
393
|
+
from agentscope.tool import ToolResponse
|
|
394
|
+
return ToolResponse(content=[TextBlock(type="text", text=f"SUM {a + b}")])
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
app_add_v1.__name__ = "app_add"
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
@only1
|
|
401
|
+
def test_v1_register_and_call():
|
|
402
|
+
from agentscope.tool import Toolkit
|
|
403
|
+
toolkit = Toolkit()
|
|
404
|
+
dc.register(toolkit)
|
|
405
|
+
schemas = toolkit.get_json_schemas()
|
|
406
|
+
assert [s["function"]["name"] for s in schemas] == dc.NAMES
|
|
407
|
+
assert schemas[1]["function"]["parameters"]["required"] == ["slug"]
|
|
408
|
+
assert schemas[2]["function"]["parameters"]["properties"]["sort"]["enum"] == ["score", "provider", "price"]
|
|
409
|
+
assert json.loads(call1(toolkit, "datacircle_best_plans", {"slug": "email-finder", "limit": 1}))["plans"] == [BRIEF]
|
|
410
|
+
assert json.loads(call1(toolkit, "datacircle_provider", {"slug": "Bright Data"}))["slug"] == "bright-data"
|
|
411
|
+
assert json.loads(call1(toolkit, "datacircle_list_apis", {}))["total"] == 2
|
|
412
|
+
assert json.loads(call1(toolkit, "datacircle_search_plans", {"query": "hunter", "limit": 5}))["plans"] == [BRIEF]
|
|
413
|
+
assert "the slugs: email-finder" in json.loads(call1(toolkit, "datacircle_best_plans", {"slug": "nope"}))["error"]
|
|
414
|
+
assert dc.tools() == [dc.datacircle_list_apis, dc.datacircle_best_plans, dc.datacircle_search_plans,
|
|
415
|
+
dc.datacircle_provider]
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
@only1
|
|
419
|
+
def test_v1_group_and_docstring():
|
|
420
|
+
from agentscope.tool import Toolkit
|
|
421
|
+
toolkit = Toolkit()
|
|
422
|
+
toolkit.create_tool_group("datacircle", "Datacircle's GTM API tools.")
|
|
423
|
+
dc.register(toolkit, group_name="datacircle")
|
|
424
|
+
assert toolkit.get_json_schemas() == []
|
|
425
|
+
toolkit.update_tool_groups(["datacircle"], True)
|
|
426
|
+
assert [s["function"]["name"] for s in toolkit.get_json_schemas()] == dc.NAMES
|
|
427
|
+
alone = Toolkit()
|
|
428
|
+
alone.register_tool_function(dc.datacircle_best_plans)
|
|
429
|
+
schema = alone.get_json_schemas()[0]["function"]
|
|
430
|
+
assert schema["name"] == "datacircle_best_plans" and "datacircle.dev" in schema["description"]
|
|
431
|
+
assert schema["parameters"]["required"] == ["slug"] and "limit" in schema["parameters"]["properties"]
|
|
432
|
+
assert json.loads(call1(alone, "datacircle_best_plans", {"slug": "email-finder"}))["plans"] == [BRIEF]
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
@only1
|
|
436
|
+
@pytest.mark.parametrize("stream", [False, True])
|
|
437
|
+
def test_v1_react_agent_runs_the_tools(stand_in, stream):
|
|
438
|
+
from agentscope.agent import ReActAgent
|
|
439
|
+
from agentscope.formatter import OpenAIChatFormatter
|
|
440
|
+
from agentscope.message import Msg
|
|
441
|
+
from agentscope.model import OpenAIChatModel
|
|
442
|
+
from agentscope.tool import Toolkit
|
|
443
|
+
toolkit = Toolkit()
|
|
444
|
+
toolkit.register_tool_function(app_add_v1)
|
|
445
|
+
dc.register(toolkit)
|
|
446
|
+
agent = ReActAgent(name="Friday", sys_prompt="You help people choose an API.",
|
|
447
|
+
model=OpenAIChatModel(model_name="scripted", api_key="scripted", stream=stream,
|
|
448
|
+
client_args={"base_url": stand_in}),
|
|
449
|
+
formatter=OpenAIChatFormatter(), toolkit=toolkit)
|
|
450
|
+
reply = asyncio.run(agent(Msg("user", SCRIPT, "user")))
|
|
451
|
+
sent = [t["function"]["name"] for t in ASKED[-2].get("tools") or []]
|
|
452
|
+
assert all(name in sent for name in dc.NAMES + ["app_add"])
|
|
453
|
+
check_script_results(last_results())
|
|
454
|
+
assert reply.get_text_content().startswith("DONE ")
|