groq-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.
- groq_datacircle-0.1.0/.gitignore +4 -0
- groq_datacircle-0.1.0/LICENSE +9 -0
- groq_datacircle-0.1.0/PKG-INFO +160 -0
- groq_datacircle-0.1.0/README.md +143 -0
- groq_datacircle-0.1.0/pyproject.toml +33 -0
- groq_datacircle-0.1.0/src/groq_datacircle/__init__.py +8 -0
- groq_datacircle-0.1.0/src/groq_datacircle/_api.py +114 -0
- groq_datacircle-0.1.0/src/groq_datacircle/py.typed +0 -0
- groq_datacircle-0.1.0/src/groq_datacircle/tools.py +247 -0
- groq_datacircle-0.1.0/tests/stand_in.py +163 -0
- groq_datacircle-0.1.0/tests/test_tools.py +280 -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,160 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: groq-datacircle
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Tools for Groq's Python library on 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/groq-python-datacircle
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: api,api-pricing,b2b-data,datacircle,function-calling,groq,gtm,llm,tool-calling,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: groq>=0.13.0
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
|
|
18
|
+
# groq-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 [Groq's Python library](https://github.com/groq/groq-python) four tools that call Datacircle's open API, https://api.datacircle.dev/v1. You pass the four Datacircle tools to `client.chat.completions.create()`. The package then runs each tool call the model returns. Our API needs no key and no account.
|
|
25
|
+
|
|
26
|
+
| Tool | What the 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, with the provider's rank and best plan on each API | `GET /providers/{slug}` |
|
|
32
|
+
|
|
33
|
+
## Install
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
pip install groq-datacircle
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
groq-datacircle works with `groq` 0.13.0 and later, on Python 3.9 and later.
|
|
40
|
+
|
|
41
|
+
## Use the tools
|
|
42
|
+
|
|
43
|
+
Pass the tools to `client.chat.completions.create()`. If the model calls a tool, `call_all()` gives you the tool messages to send back:
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
from groq import Groq
|
|
47
|
+
from groq_datacircle import call_all, datacircle_tools
|
|
48
|
+
|
|
49
|
+
client = Groq()
|
|
50
|
+
messages = [{"role": "user", "content": "Who are the 3 best providers for the email-finder API?"}]
|
|
51
|
+
message = client.chat.completions.create(model="openai/gpt-oss-20b", messages=messages, tools=datacircle_tools()).choices[0].message
|
|
52
|
+
|
|
53
|
+
while message.tool_calls:
|
|
54
|
+
messages.append(message)
|
|
55
|
+
messages.extend(call_all(message))
|
|
56
|
+
message = client.chat.completions.create(model="openai/gpt-oss-20b", messages=messages, tools=datacircle_tools()).choices[0].message
|
|
57
|
+
|
|
58
|
+
print(message.content)
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Each tool message has `role: "tool"`, the call's id in `tool_call_id`, and the answer as JSON text in `content`.
|
|
62
|
+
|
|
63
|
+
## Use the tools with a stream
|
|
64
|
+
|
|
65
|
+
With `stream=True`, the model's tool calls come in pieces. `collect_tool_calls()` puts the pieces of each call together:
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
from groq import Groq
|
|
69
|
+
from groq_datacircle import call_all, collect_tool_calls, datacircle_tools
|
|
70
|
+
|
|
71
|
+
client = Groq()
|
|
72
|
+
messages = [{"role": "user", "content": "Which provider has the cheapest plan of the email-finder API?"}]
|
|
73
|
+
|
|
74
|
+
while True:
|
|
75
|
+
content, calls = "", []
|
|
76
|
+
for chunk in client.chat.completions.create(model="openai/gpt-oss-20b", messages=messages, tools=datacircle_tools(), stream=True):
|
|
77
|
+
if chunk.choices:
|
|
78
|
+
content += chunk.choices[0].delta.content or ""
|
|
79
|
+
collect_tool_calls(calls, chunk.choices[0].delta.tool_calls)
|
|
80
|
+
if not calls:
|
|
81
|
+
break
|
|
82
|
+
messages.append({"role": "assistant", "content": content, "tool_calls": calls})
|
|
83
|
+
messages.extend(call_all(calls))
|
|
84
|
+
|
|
85
|
+
print(content)
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
## Use the tools with AsyncGroq
|
|
89
|
+
|
|
90
|
+
With `AsyncGroq`, use `await acall_all(message)`. `acall_all()` runs the calls at the same time. Your event loop keeps running.
|
|
91
|
+
|
|
92
|
+
```python
|
|
93
|
+
import asyncio
|
|
94
|
+
|
|
95
|
+
from groq import AsyncGroq
|
|
96
|
+
from groq_datacircle import acall_all, datacircle_tools
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
async def main():
|
|
100
|
+
client = AsyncGroq()
|
|
101
|
+
messages = [{"role": "user", "content": "Which APIs does Bright Data sell?"}]
|
|
102
|
+
message = (await client.chat.completions.create(model="openai/gpt-oss-20b", messages=messages, tools=datacircle_tools())).choices[0].message
|
|
103
|
+
while message.tool_calls:
|
|
104
|
+
messages.append(message)
|
|
105
|
+
messages.extend(await acall_all(message))
|
|
106
|
+
message = (await client.chat.completions.create(model="openai/gpt-oss-20b", messages=messages, tools=datacircle_tools())).choices[0].message
|
|
107
|
+
print(message.content)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
asyncio.run(main())
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
## Use the Datacircle tools beside your own tools
|
|
114
|
+
|
|
115
|
+
You can put the Datacircle tools in the same list as yours: `tools=[*datacircle_tools(), my_tool]`.
|
|
116
|
+
|
|
117
|
+
`call()` runs one tool call. For your own tools, `call()` returns `None`. Your code then runs the tool itself:
|
|
118
|
+
|
|
119
|
+
```python
|
|
120
|
+
from groq_datacircle import call
|
|
121
|
+
|
|
122
|
+
for tool_call in message.tool_calls or []:
|
|
123
|
+
messages.append(call(tool_call) or my_tool_message(tool_call))
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
To give the model fewer Datacircle tools, list the tool names: `datacircle_tools(["datacircle_best_plans"])`.
|
|
127
|
+
|
|
128
|
+
## Call a tool yourself
|
|
129
|
+
|
|
130
|
+
You can call each tool without a model. You get the JSON text of the tool's answer:
|
|
131
|
+
|
|
132
|
+
```python
|
|
133
|
+
import json
|
|
134
|
+
|
|
135
|
+
from groq_datacircle import run
|
|
136
|
+
|
|
137
|
+
answer = json.loads(run("datacircle_best_plans", {"slug": "email-finder", "limit": 3}))
|
|
138
|
+
print(answer["plans"])
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
## What the model reads
|
|
142
|
+
|
|
143
|
+
Each tool gives the model 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.
|
|
144
|
+
|
|
145
|
+
You can give a provider's name in place of a slug. The tool turns `Bright Data` into `bright-data`.
|
|
146
|
+
|
|
147
|
+
The tool returns `{"error": "..."}` with the API's message when the API gives no data, such as for an unknown slug. The error for an unknown API slug lists every valid slug. The tool checks each number from the model first. For a number out of range, the tool returns `{"error": "..."}` and makes no API call. If the network fails, the tool returns `{"error": "..."}` with the network error's message. The model can then call the tool again.
|
|
148
|
+
|
|
149
|
+
## Network
|
|
150
|
+
|
|
151
|
+
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 API can ask the tool to wait. The tool then waits once, for a minute at most. Each call uses only Python's standard library. Nothing goes to disk.
|
|
152
|
+
|
|
153
|
+
## Links
|
|
154
|
+
|
|
155
|
+
- Datacircle: https://datacircle.dev
|
|
156
|
+
- The API: https://datacircle.dev/api
|
|
157
|
+
- The API's spec: https://api.datacircle.dev/v1/openapi.json
|
|
158
|
+
- Every field of a plan: https://datacircle.dev/fields
|
|
159
|
+
|
|
160
|
+
MIT license.
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
# groq-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 [Groq's Python library](https://github.com/groq/groq-python) four tools that call Datacircle's open API, https://api.datacircle.dev/v1. You pass the four Datacircle tools to `client.chat.completions.create()`. The package then runs each tool call the model returns. Our API needs no key and no account.
|
|
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, with the provider's rank and best plan on each API | `GET /providers/{slug}` |
|
|
15
|
+
|
|
16
|
+
## Install
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
pip install groq-datacircle
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
groq-datacircle works with `groq` 0.13.0 and later, on Python 3.9 and later.
|
|
23
|
+
|
|
24
|
+
## Use the tools
|
|
25
|
+
|
|
26
|
+
Pass the tools to `client.chat.completions.create()`. If the model calls a tool, `call_all()` gives you the tool messages to send back:
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
from groq import Groq
|
|
30
|
+
from groq_datacircle import call_all, datacircle_tools
|
|
31
|
+
|
|
32
|
+
client = Groq()
|
|
33
|
+
messages = [{"role": "user", "content": "Who are the 3 best providers for the email-finder API?"}]
|
|
34
|
+
message = client.chat.completions.create(model="openai/gpt-oss-20b", messages=messages, tools=datacircle_tools()).choices[0].message
|
|
35
|
+
|
|
36
|
+
while message.tool_calls:
|
|
37
|
+
messages.append(message)
|
|
38
|
+
messages.extend(call_all(message))
|
|
39
|
+
message = client.chat.completions.create(model="openai/gpt-oss-20b", messages=messages, tools=datacircle_tools()).choices[0].message
|
|
40
|
+
|
|
41
|
+
print(message.content)
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Each tool message has `role: "tool"`, the call's id in `tool_call_id`, and the answer as JSON text in `content`.
|
|
45
|
+
|
|
46
|
+
## Use the tools with a stream
|
|
47
|
+
|
|
48
|
+
With `stream=True`, the model's tool calls come in pieces. `collect_tool_calls()` puts the pieces of each call together:
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
from groq import Groq
|
|
52
|
+
from groq_datacircle import call_all, collect_tool_calls, datacircle_tools
|
|
53
|
+
|
|
54
|
+
client = Groq()
|
|
55
|
+
messages = [{"role": "user", "content": "Which provider has the cheapest plan of the email-finder API?"}]
|
|
56
|
+
|
|
57
|
+
while True:
|
|
58
|
+
content, calls = "", []
|
|
59
|
+
for chunk in client.chat.completions.create(model="openai/gpt-oss-20b", messages=messages, tools=datacircle_tools(), stream=True):
|
|
60
|
+
if chunk.choices:
|
|
61
|
+
content += chunk.choices[0].delta.content or ""
|
|
62
|
+
collect_tool_calls(calls, chunk.choices[0].delta.tool_calls)
|
|
63
|
+
if not calls:
|
|
64
|
+
break
|
|
65
|
+
messages.append({"role": "assistant", "content": content, "tool_calls": calls})
|
|
66
|
+
messages.extend(call_all(calls))
|
|
67
|
+
|
|
68
|
+
print(content)
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## Use the tools with AsyncGroq
|
|
72
|
+
|
|
73
|
+
With `AsyncGroq`, use `await acall_all(message)`. `acall_all()` runs the calls at the same time. Your event loop keeps running.
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
import asyncio
|
|
77
|
+
|
|
78
|
+
from groq import AsyncGroq
|
|
79
|
+
from groq_datacircle import acall_all, datacircle_tools
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
async def main():
|
|
83
|
+
client = AsyncGroq()
|
|
84
|
+
messages = [{"role": "user", "content": "Which APIs does Bright Data sell?"}]
|
|
85
|
+
message = (await client.chat.completions.create(model="openai/gpt-oss-20b", messages=messages, tools=datacircle_tools())).choices[0].message
|
|
86
|
+
while message.tool_calls:
|
|
87
|
+
messages.append(message)
|
|
88
|
+
messages.extend(await acall_all(message))
|
|
89
|
+
message = (await client.chat.completions.create(model="openai/gpt-oss-20b", messages=messages, tools=datacircle_tools())).choices[0].message
|
|
90
|
+
print(message.content)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
asyncio.run(main())
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
## Use the Datacircle tools beside your own tools
|
|
97
|
+
|
|
98
|
+
You can put the Datacircle tools in the same list as yours: `tools=[*datacircle_tools(), my_tool]`.
|
|
99
|
+
|
|
100
|
+
`call()` runs one tool call. For your own tools, `call()` returns `None`. Your code then runs the tool itself:
|
|
101
|
+
|
|
102
|
+
```python
|
|
103
|
+
from groq_datacircle import call
|
|
104
|
+
|
|
105
|
+
for tool_call in message.tool_calls or []:
|
|
106
|
+
messages.append(call(tool_call) or my_tool_message(tool_call))
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
To give the model fewer Datacircle tools, list the tool names: `datacircle_tools(["datacircle_best_plans"])`.
|
|
110
|
+
|
|
111
|
+
## Call a tool yourself
|
|
112
|
+
|
|
113
|
+
You can call each tool without a model. You get the JSON text of the tool's answer:
|
|
114
|
+
|
|
115
|
+
```python
|
|
116
|
+
import json
|
|
117
|
+
|
|
118
|
+
from groq_datacircle import run
|
|
119
|
+
|
|
120
|
+
answer = json.loads(run("datacircle_best_plans", {"slug": "email-finder", "limit": 3}))
|
|
121
|
+
print(answer["plans"])
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
## What the model reads
|
|
125
|
+
|
|
126
|
+
Each tool gives the model 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.
|
|
127
|
+
|
|
128
|
+
You can give a provider's name in place of a slug. The tool turns `Bright Data` into `bright-data`.
|
|
129
|
+
|
|
130
|
+
The tool returns `{"error": "..."}` with the API's message when the API gives no data, such as for an unknown slug. The error for an unknown API slug lists every valid slug. The tool checks each number from the model first. For a number out of range, the tool returns `{"error": "..."}` and makes no API call. If the network fails, the tool returns `{"error": "..."}` with the network error's message. The model can then call the tool again.
|
|
131
|
+
|
|
132
|
+
## Network
|
|
133
|
+
|
|
134
|
+
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 API can ask the tool to wait. The tool then waits once, for a minute at most. Each call uses only Python's standard library. Nothing goes to disk.
|
|
135
|
+
|
|
136
|
+
## Links
|
|
137
|
+
|
|
138
|
+
- Datacircle: https://datacircle.dev
|
|
139
|
+
- The API: https://datacircle.dev/api
|
|
140
|
+
- The API's spec: https://api.datacircle.dev/v1/openapi.json
|
|
141
|
+
- Every field of a plan: https://datacircle.dev/fields
|
|
142
|
+
|
|
143
|
+
MIT license.
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "groq-datacircle"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Tools for Groq's Python library on the Datacircle API: find the best GTM APIs"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.9"
|
|
12
|
+
# 0.13.0 is the first groq that runs with httpx 0.28 (older ones pass it proxies). The tools are plain dicts and the run of their calls.
|
|
13
|
+
dependencies = ["groq>=0.13.0"]
|
|
14
|
+
keywords = ["groq", "llm", "tools", "function-calling", "tool-calling", "gtm", "api", "api-pricing", "b2b-data", "datacircle"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Operating System :: OS Independent",
|
|
18
|
+
"Topic :: Software Development :: Libraries",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
[project.urls]
|
|
22
|
+
Homepage = "https://datacircle.dev"
|
|
23
|
+
Documentation = "https://api.datacircle.dev/v1/openapi.json"
|
|
24
|
+
Repository = "https://github.com/waynehamadi/groq-python-datacircle"
|
|
25
|
+
|
|
26
|
+
[dependency-groups]
|
|
27
|
+
test = ["pytest>=8"]
|
|
28
|
+
|
|
29
|
+
[tool.hatch.build.targets.wheel]
|
|
30
|
+
packages = ["src/groq_datacircle"]
|
|
31
|
+
|
|
32
|
+
[tool.hatch.build.targets.sdist]
|
|
33
|
+
include = ["src", "tests", "README.md", "LICENSE", "pyproject.toml"]
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""Tools for Groq's Python library on Datacircle's open API (https://api.datacircle.dev/v1): find the best GTM APIs, no key."""
|
|
2
|
+
|
|
3
|
+
from groq_datacircle._api import BASE_URL, DatacircleError
|
|
4
|
+
from groq_datacircle.tools import TOOL_NAMES, acall, acall_all, call, call_all, collect_tool_calls, datacircle_tools, run
|
|
5
|
+
|
|
6
|
+
__version__ = "0.1.0"
|
|
7
|
+
__all__ = ["BASE_URL", "DatacircleError", "TOOL_NAMES", "acall", "acall_all", "call", "call_all", "collect_tool_calls",
|
|
8
|
+
"datacircle_tools", "run"]
|
|
@@ -0,0 +1,114 @@
|
|
|
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 gzip
|
|
4
|
+
import json
|
|
5
|
+
import math
|
|
6
|
+
import re
|
|
7
|
+
import time
|
|
8
|
+
import unicodedata
|
|
9
|
+
import urllib.error
|
|
10
|
+
import urllib.parse
|
|
11
|
+
import urllib.request
|
|
12
|
+
import zlib
|
|
13
|
+
from typing import Any, Dict, List, Optional
|
|
14
|
+
|
|
15
|
+
BASE_URL = "https://api.datacircle.dev/v1"
|
|
16
|
+
TIMEOUT = 30.0
|
|
17
|
+
USER_AGENT = "groq-datacircle/0.1.0"
|
|
18
|
+
|
|
19
|
+
# 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.
|
|
20
|
+
PLAN_KEYS = ["api", "rank", "provider", "plan", "score", "perThousand", "notFoundPerThousand", "billing", "pay",
|
|
21
|
+
"currency", "units", "unit", "strengths", "latencyMs", "page", "pricingPage", "docs"]
|
|
22
|
+
API_KEYS = ["api", "slug", "plans", "providers", "best", "bestPage", "sheetPage"]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class DatacircleError(Exception):
|
|
26
|
+
"""The API's refusal in its own words, why it could not be reached, or an argument it can't take: a tool gives the
|
|
27
|
+
model its words as its JSON text, {"error": ...}. status is the API's HTTP status, None when it gave none;
|
|
28
|
+
retryable, whether the same call may be answered later (the API out of reach, busy or failing)."""
|
|
29
|
+
|
|
30
|
+
def __init__(self, message: str, status: Optional[int] = None, retryable: bool = False):
|
|
31
|
+
super().__init__(message)
|
|
32
|
+
self.status = status
|
|
33
|
+
self.retryable = retryable
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def brief(item: Dict[str, Any], keys: List[str] = PLAN_KEYS) -> Dict[str, Any]:
|
|
37
|
+
return {key: item[key] for key in keys if item.get(key) is not None}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def slug(value: Any) -> str:
|
|
41
|
+
"""The API's rule for a slug: the name in lowercase letters and digits, the rest a hyphen."""
|
|
42
|
+
plain = unicodedata.normalize("NFKD", str(value or "").strip().lower())
|
|
43
|
+
plain = "".join(char for char in plain if not unicodedata.combining(char))
|
|
44
|
+
return re.sub(r"[^a-z0-9]+", "-", plain).strip("-")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def whole(name: str, value: Any, low: int, high: Optional[int] = None) -> Optional[int]:
|
|
48
|
+
"""A whole number from low to high, or None when left out: a plain call may send one as text."""
|
|
49
|
+
if value is None or value == "":
|
|
50
|
+
return None
|
|
51
|
+
try:
|
|
52
|
+
number = float(value)
|
|
53
|
+
except (TypeError, ValueError):
|
|
54
|
+
number = float("nan")
|
|
55
|
+
if isinstance(value, bool) or not math.isfinite(number) or number != int(number):
|
|
56
|
+
raise DatacircleError(f"{name} must be a whole number, not {value!r}")
|
|
57
|
+
if number < low or (high is not None and number > high):
|
|
58
|
+
raise DatacircleError(f"{name} must be from {low} to {high}, not {int(number)}" if high is not None
|
|
59
|
+
else f"{name} must be {low} or more, not {int(number)}")
|
|
60
|
+
return int(number)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _words(body: bytes) -> str:
|
|
64
|
+
"""A refusal's words: the API's error, with every slug when the slug was unknown."""
|
|
65
|
+
text = body.decode("utf-8", "replace")
|
|
66
|
+
try:
|
|
67
|
+
parsed = json.loads(text)
|
|
68
|
+
if parsed.get("slugs"):
|
|
69
|
+
return f"{parsed['error']}; the slugs: {', '.join(parsed['slugs'])}"
|
|
70
|
+
return str(parsed.get("error", text))
|
|
71
|
+
except (ValueError, KeyError, TypeError, AttributeError):
|
|
72
|
+
return text
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _unpacked(body: bytes, headers: Any) -> bytes:
|
|
76
|
+
"""The answer's bytes as sent before it was squeezed: urllib unpacks nothing by itself, and an answer may pass 10 MB."""
|
|
77
|
+
if str((headers or {}).get("Content-Encoding") or "").strip().lower() != "gzip":
|
|
78
|
+
return body
|
|
79
|
+
try:
|
|
80
|
+
return gzip.decompress(body)
|
|
81
|
+
except (OSError, EOFError, zlib.error) as error:
|
|
82
|
+
raise DatacircleError(f"Datacircle's API gave a broken gzip answer: {error}", retryable=True) from None
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def get(path: str, params: Optional[Dict[str, Any]] = None) -> Any:
|
|
86
|
+
"""The API's JSON answer, or a DatacircleError with its words: waits once when it answers 429."""
|
|
87
|
+
query = urllib.parse.urlencode({key: value for key, value in (params or {}).items() if value not in (None, "")})
|
|
88
|
+
url = f"{BASE_URL.rstrip('/')}{path}" + (f"?{query}" if query else "")
|
|
89
|
+
request = urllib.request.Request(url, headers={"Accept": "application/json", "Accept-Encoding": "gzip",
|
|
90
|
+
"User-Agent": USER_AGENT})
|
|
91
|
+
for attempt in range(2):
|
|
92
|
+
try:
|
|
93
|
+
with urllib.request.urlopen(request, timeout=TIMEOUT) as answer:
|
|
94
|
+
body = _unpacked(answer.read(), answer.headers)
|
|
95
|
+
except urllib.error.HTTPError as error:
|
|
96
|
+
body = _unpacked(error.read(), error.headers)
|
|
97
|
+
if error.code == 429 and not attempt:
|
|
98
|
+
try:
|
|
99
|
+
wait = int(error.headers.get("Retry-After") or 30)
|
|
100
|
+
except ValueError:
|
|
101
|
+
wait = 30
|
|
102
|
+
time.sleep(min(max(wait, 1), 60))
|
|
103
|
+
continue
|
|
104
|
+
if error.code == 429:
|
|
105
|
+
raise DatacircleError("Datacircle's API answered 429 twice: wait a minute and call again", 429, True) from None
|
|
106
|
+
raise DatacircleError(f"Datacircle's API answered {error.code}: {_words(body)[:3000]}", error.code,
|
|
107
|
+
error.code >= 500) from None
|
|
108
|
+
except (urllib.error.URLError, OSError) as error:
|
|
109
|
+
raise DatacircleError(f"Datacircle's API could not be reached: {getattr(error, 'reason', error)}",
|
|
110
|
+
retryable=True) from None
|
|
111
|
+
try:
|
|
112
|
+
return json.loads(body)
|
|
113
|
+
except ValueError as error:
|
|
114
|
+
raise DatacircleError(f"Datacircle's API gave no JSON: {error}") from None
|
|
File without changes
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
"""Tools for Groq's Python library (groq) on Datacircle's open API, https://api.datacircle.dev/v1: no key, no account.
|
|
2
|
+
|
|
3
|
+
datacircle_tools() gives the four as tool definitions for client.chat.completions.create(tools=...), Groq's and
|
|
4
|
+
AsyncGroq's, streamed or not, beside an app's own tools; call() and call_all() run the tool calls the model returns into
|
|
5
|
+
the tool messages to send back, acall() and acall_all() in a thread for an event loop, and collect_tool_calls() gathers
|
|
6
|
+
a stream's calls. A tool makes one HTTPS GET and gives the model the API's answer as JSON text. A refusal (an unknown
|
|
7
|
+
slug, an argument out of range, the API out of reach) is the JSON text {"error": the API's words}, so the model can call
|
|
8
|
+
again and the chat goes on. Not every model keeps to a tool's schema, so each tool checks its arguments before any call.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
import copy
|
|
13
|
+
import json
|
|
14
|
+
import urllib.parse
|
|
15
|
+
from typing import Any, Dict, List, Mapping, Optional, Sequence
|
|
16
|
+
|
|
17
|
+
from groq_datacircle import _api
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _text(answer: Any) -> str:
|
|
21
|
+
return json.dumps(answer, ensure_ascii=False)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _best(plans: Any) -> Optional[Dict[str, Any]]:
|
|
25
|
+
"""A provider's best plan on an API: its lowest rank, a plan with no score having none."""
|
|
26
|
+
ranked = sorted(plans, key=lambda plan: plan.get("rank") if isinstance(plan.get("rank"), (int, float)) else float("inf"))
|
|
27
|
+
return _api.brief(ranked[0], ["plan", "score", "perThousand", "page"]) if ranked else None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _list_apis(query: Any = None, limit: Any = None) -> Dict[str, Any]:
|
|
31
|
+
count = _api.whole("limit", limit, 1, 200) or 20
|
|
32
|
+
apis = _api.get("/apis")
|
|
33
|
+
words = [word for word in str(query or "").lower().replace("-", " ").split() if word]
|
|
34
|
+
held = []
|
|
35
|
+
for index, api in enumerate(apis):
|
|
36
|
+
name = f"{api.get('api', '')} {str(api.get('slug', '')).replace('-', ' ')}".lower()
|
|
37
|
+
matched = sum(word in name for word in words)
|
|
38
|
+
if matched or not words:
|
|
39
|
+
held.append((-matched, index, api))
|
|
40
|
+
found = [_api.brief(api, _api.API_KEYS) for _, _, api in sorted(held, key=lambda h: h[:2])]
|
|
41
|
+
return {"total": len(found), "apis": found[:count]}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _best_plans(slug: Any = None, limit: Any = None) -> Dict[str, Any]:
|
|
45
|
+
made = _api.slug(slug)
|
|
46
|
+
if not made:
|
|
47
|
+
raise _api.DatacircleError("Give an API's slug, like 'email-finder': datacircle_list_apis gives every slug")
|
|
48
|
+
answer = _api.get(f"/apis/{urllib.parse.quote(made)}/best", {"limit": _api.whole("limit", limit, 1, 50)})
|
|
49
|
+
return {**answer, "plans": [_api.brief(plan) for plan in answer.get("plans") or []]}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _search_plans(api: Any = None, query: Any = None, sort: Any = None, limit: Any = None, offset: Any = None) -> Dict[str, Any]:
|
|
53
|
+
order = str(sort).strip().lower() if sort not in (None, "") else None
|
|
54
|
+
if order is not None and order not in ("score", "provider", "price"):
|
|
55
|
+
raise _api.DatacircleError(f"sort must be score, provider or price, not {sort!r}")
|
|
56
|
+
params = {"api": api, "query": query, "sort": order, "limit": _api.whole("limit", limit, 1, 50),
|
|
57
|
+
"offset": _api.whole("offset", offset, 0)}
|
|
58
|
+
answer = _api.get("/plans", params)
|
|
59
|
+
return {**answer, "plans": [_api.brief(plan) for plan in answer.get("plans") or []]}
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _provider(slug: Any = None) -> Dict[str, Any]:
|
|
63
|
+
made = _api.slug(slug)
|
|
64
|
+
if not made:
|
|
65
|
+
raise _api.DatacircleError("Give a provider's slug or name, like 'bright-data' or 'Bright Data'")
|
|
66
|
+
# plans=best: each API's best plan of the provider alone, its count in planCount (a provider's every plan passes 10 MB)
|
|
67
|
+
answer = _api.get(f"/providers/{urllib.parse.quote(made)}", {"plans": "best"})
|
|
68
|
+
apis = [{**_api.brief(entry, ["api", "slug", "rank", "bestPage"]),
|
|
69
|
+
"plans": entry.get("planCount", len(entry.get("plans") or [])), "best": _best(entry.get("plans") or [])}
|
|
70
|
+
for entry in answer.get("apis") or []]
|
|
71
|
+
return {**answer, "apis": apis}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
_PRICE = "perThousand is a plan's price of 1,000 items in dollars, pay the plan's whole price in its currency."
|
|
75
|
+
_LIMIT = {"type": "integer", "minimum": 1, "maximum": 50, "description": "How many plans to give, 1 to 50. 10 when left out."}
|
|
76
|
+
|
|
77
|
+
# Each tool: what the model reads of it, and the function that answers it. The schemas use only the plain words of JSON
|
|
78
|
+
# Schema every model on Groq takes: type, description, enum, minimum, maximum, required.
|
|
79
|
+
_TOOLS: Dict[str, Dict[str, Any]] = {
|
|
80
|
+
"datacircle_list_apis": {
|
|
81
|
+
"run": _list_apis,
|
|
82
|
+
"description": "Lists the GTM APIs on Datacircle's sheet (https://datacircle.dev), with each API's slug, how many plans "
|
|
83
|
+
"and providers it has and its best plan. Call it to find an API's slug when you don't know it. Gives "
|
|
84
|
+
"total, the APIs found, and apis, up to limit of them.",
|
|
85
|
+
"parameters": {"type": "object", "properties": {
|
|
86
|
+
"query": {"type": "string", "description": "Words of the API's name or slug, like 'email' or 'linkedin profile'. "
|
|
87
|
+
"The APIs that hold the most of them come first, in the sheet's order "
|
|
88
|
+
"when left out."},
|
|
89
|
+
"limit": {"type": "integer", "minimum": 1, "maximum": 200,
|
|
90
|
+
"description": "How many APIs to give, 1 to 200. 20 when left out, of about 170."}}},
|
|
91
|
+
},
|
|
92
|
+
"datacircle_best_plans": {
|
|
93
|
+
"run": _best_plans,
|
|
94
|
+
"description": "Gives an API's plans best first by their score out of 100 on Datacircle's benchmark "
|
|
95
|
+
"(https://datacircle.dev), each with its rank, provider, plan, $ per 1,000 calls and its page: the "
|
|
96
|
+
"best providers of an API. " + _PRICE,
|
|
97
|
+
"parameters": {"type": "object", "properties": {
|
|
98
|
+
"slug": {"type": "string", "description": "The API's slug, like 'email-finder' or 'linkedin-profile', as "
|
|
99
|
+
"datacircle_list_apis gives it."},
|
|
100
|
+
"limit": _LIMIT}, "required": ["slug"]},
|
|
101
|
+
},
|
|
102
|
+
"datacircle_search_plans": {
|
|
103
|
+
"run": _search_plans,
|
|
104
|
+
"description": "Searches every plan on Datacircle's sheet (https://datacircle.dev), or one API's, by provider or plan "
|
|
105
|
+
"name, sorted by score, provider or price. Gives total, offset and up to limit plans. " + _PRICE,
|
|
106
|
+
"parameters": {"type": "object", "properties": {
|
|
107
|
+
"api": {"type": "string", "description": "Only this API's plans, by its name or slug, like 'email-finder'. A "
|
|
108
|
+
"provider's name goes in query, never here. Every API when left out."},
|
|
109
|
+
"query": {"type": "string", "description": "Words that must all appear in the provider's or plan's name, like "
|
|
110
|
+
"'bright data'."},
|
|
111
|
+
"sort": {"type": "string", "enum": ["score", "provider", "price"],
|
|
112
|
+
"description": "score (best first, the default), provider (A to Z) or price ($ per 1,000, lowest first)."},
|
|
113
|
+
"limit": _LIMIT,
|
|
114
|
+
"offset": {"type": "integer", "minimum": 0, "description": "How many found plans to skip first. 0 when left out."}}},
|
|
115
|
+
},
|
|
116
|
+
"datacircle_provider": {
|
|
117
|
+
"run": _provider,
|
|
118
|
+
"description": "Gives each API one provider sells and its rank on each on Datacircle's benchmark "
|
|
119
|
+
"(https://datacircle.dev), with how many plans it has there and its best one.",
|
|
120
|
+
"parameters": {"type": "object", "properties": {
|
|
121
|
+
"slug": {"type": "string", "description": "The provider's slug, like 'bright-data', or its name, like 'Bright "
|
|
122
|
+
"Data', which is made a slug."}}, "required": ["slug"]},
|
|
123
|
+
},
|
|
124
|
+
}
|
|
125
|
+
TOOL_NAMES = list(_TOOLS)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _names(tool_names: Optional[Sequence[str]]) -> List[str]:
|
|
129
|
+
if isinstance(tool_names, str):
|
|
130
|
+
raise TypeError("tool_names is a list of names, like ['datacircle_best_plans']")
|
|
131
|
+
for name in tool_names or []:
|
|
132
|
+
if name not in _TOOLS:
|
|
133
|
+
raise ValueError(f"Datacircle has no tool {name!r}: its tools are {', '.join(TOOL_NAMES)}")
|
|
134
|
+
return TOOL_NAMES if tool_names is None else list(tool_names)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def datacircle_tools(tool_names: Optional[Sequence[str]] = None) -> List[Dict[str, Any]]:
|
|
138
|
+
"""The tools for client.chat.completions.create(model=..., messages=..., tools=datacircle_tools()), Groq's and
|
|
139
|
+
AsyncGroq's, or beside one's own: tools=[*datacircle_tools(), my_tool]. tool_names keeps some of them only, in their
|
|
140
|
+
order here; all four when left out. Each is a new dict, so an app may change its copy."""
|
|
141
|
+
return [{"type": "function", "function": {"name": name, "description": _TOOLS[name]["description"],
|
|
142
|
+
"parameters": copy.deepcopy(_TOOLS[name]["parameters"])}}
|
|
143
|
+
for name in _names(tool_names)]
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def run(name: str, arguments: Any = None) -> str:
|
|
147
|
+
"""What a tool gives the model for these arguments, as JSON text: the API's answer, or {"error": its words}.
|
|
148
|
+
arguments is a mapping or its JSON text; the ones the tool doesn't take are left out, and null ones too."""
|
|
149
|
+
if name not in _TOOLS:
|
|
150
|
+
raise ValueError(f"Datacircle has no tool {name!r}: its tools are {', '.join(TOOL_NAMES)}")
|
|
151
|
+
if isinstance(arguments, bytes):
|
|
152
|
+
arguments = arguments.decode("utf-8", "replace")
|
|
153
|
+
if isinstance(arguments, str):
|
|
154
|
+
try:
|
|
155
|
+
arguments = json.loads(arguments) if arguments.strip() else {}
|
|
156
|
+
except ValueError:
|
|
157
|
+
return _text({"error": f"the arguments are no JSON object: {arguments[:200]!r}"})
|
|
158
|
+
if arguments is not None and not isinstance(arguments, Mapping):
|
|
159
|
+
return _text({"error": f"the arguments are no JSON object: {str(arguments)[:200]!r}"})
|
|
160
|
+
given = dict(arguments or {})
|
|
161
|
+
taken = _TOOLS[name]["parameters"]["properties"]
|
|
162
|
+
try:
|
|
163
|
+
return _text(_TOOLS[name]["run"](**{key: given.get(key) for key in taken}))
|
|
164
|
+
except _api.DatacircleError as error:
|
|
165
|
+
return _text({"error": str(error)})
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _field(item: Any, key: str) -> Any:
|
|
169
|
+
"""A field of a dict, or of groq's types by attribute."""
|
|
170
|
+
return item.get(key) if isinstance(item, Mapping) else getattr(item, key, None)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _named(tool_call: Any) -> Optional[str]:
|
|
174
|
+
"""The tool's name in a tool call (groq's ChatCompletionMessageToolCall, or a dict of its shape): when it is one of
|
|
175
|
+
ours."""
|
|
176
|
+
name = _field(_field(tool_call, "function"), "name")
|
|
177
|
+
return name if name in _TOOLS else None
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def call(tool_call: Any) -> Optional[Dict[str, str]]:
|
|
181
|
+
"""The tool message for one tool call the model returned (one of completion.choices[0].message.tool_calls, or a
|
|
182
|
+
dict of its shape), to append to the messages: {"role": "tool", "tool_call_id": its id, "content": the JSON text}.
|
|
183
|
+
None when the call is for a tool that is not one of these four, so the app runs its own."""
|
|
184
|
+
name = _named(tool_call)
|
|
185
|
+
if name is None:
|
|
186
|
+
return None
|
|
187
|
+
return {"role": "tool", "tool_call_id": _field(tool_call, "id"),
|
|
188
|
+
"content": run(name, _field(_field(tool_call, "function"), "arguments"))}
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _calls(message_or_calls: Any) -> Sequence[Any]:
|
|
192
|
+
"""A reply's tool calls, from its message (or a dict of its shape) or from the list itself."""
|
|
193
|
+
if message_or_calls is None:
|
|
194
|
+
return []
|
|
195
|
+
if isinstance(message_or_calls, (list, tuple)):
|
|
196
|
+
return message_or_calls
|
|
197
|
+
return _field(message_or_calls, "tool_calls") or []
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def call_all(message_or_calls: Any) -> List[Dict[str, str]]:
|
|
201
|
+
"""The tool messages for the calls of these four tools in a reply (its message, or its tool_calls), in their order.
|
|
202
|
+
Calls of other tools are left out, for the app to run."""
|
|
203
|
+
return [message for message in (call(tool_call) for tool_call in _calls(message_or_calls)) if message is not None]
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
async def acall(tool_call: Any) -> Optional[Dict[str, str]]:
|
|
207
|
+
"""call() for AsyncGroq: its HTTPS GET runs in a thread, so the event loop goes on."""
|
|
208
|
+
if _named(tool_call) is None:
|
|
209
|
+
return None
|
|
210
|
+
return await asyncio.to_thread(call, tool_call)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
async def acall_all(message_or_calls: Any) -> List[Dict[str, str]]:
|
|
214
|
+
"""call_all() for AsyncGroq: the calls run at once, their messages in the calls' order."""
|
|
215
|
+
messages = await asyncio.gather(*(acall(tool_call) for tool_call in _calls(message_or_calls)))
|
|
216
|
+
return [message for message in messages if message is not None]
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
class _Gathered(dict):
|
|
220
|
+
"""A tool call gathered from a stream: a plain dict to the JSON that is sent, its index in the stream kept aside, as
|
|
221
|
+
Groq's API takes no index in an assistant message's tool_calls."""
|
|
222
|
+
|
|
223
|
+
index: Any = None
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def collect_tool_calls(calls: List[Dict[str, Any]], delta_tool_calls: Any) -> List[Dict[str, Any]]:
|
|
227
|
+
"""Adds a stream chunk's tool calls (chunk.choices[0].delta.tool_calls) to calls and gives calls back. A call may
|
|
228
|
+
come in pieces, its id and name on the first and the call's index on each, and the pieces of an index make one call.
|
|
229
|
+
Each call is a dict {"id", "type": "function", "function": {"name", "arguments"}}, for the assistant message's
|
|
230
|
+
tool_calls and for call_all()."""
|
|
231
|
+
for delta in delta_tool_calls or []:
|
|
232
|
+
index, given = _field(delta, "index"), _field(delta, "id")
|
|
233
|
+
function = _field(delta, "function")
|
|
234
|
+
name, arguments = _field(function, "name"), _field(function, "arguments")
|
|
235
|
+
held = next((made for made in reversed(calls) if index is not None and getattr(made, "index", None) == index), None)
|
|
236
|
+
if held is None or (given and held["id"] and given != held["id"]):
|
|
237
|
+
held = _Gathered(id=given, type="function", function={"name": "", "arguments": ""})
|
|
238
|
+
held.index = index if index is not None else len(calls)
|
|
239
|
+
calls.append(held)
|
|
240
|
+
held["id"] = held["id"] or given
|
|
241
|
+
held["function"]["name"] = held["function"]["name"] or name or ""
|
|
242
|
+
if isinstance(arguments, str):
|
|
243
|
+
held["function"]["arguments"] += arguments
|
|
244
|
+
return calls
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
__all__: List[str] = ["TOOL_NAMES", "acall", "acall_all", "call", "call_all", "collect_tool_calls", "datacircle_tools", "run"]
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
"""A stand-in on 127.0.0.1 for Groq's chat server, as groq's Groq and AsyncGroq reach one through base_url (POST
|
|
2
|
+
/openai/v1/chat/completions), and for Datacircle's API when asked.
|
|
3
|
+
|
|
4
|
+
The chat runs a script: the first user text holds one or more lines `CALL <tool> <json arguments>`, and the model asks
|
|
5
|
+
for those tools at once, with its reasoning, as Groq's reasoning models give it; once every call has its result, it
|
|
6
|
+
answers `DONE <each result's first 300 characters>`. As Groq's API does, a request is refused with a 400 when a tool
|
|
7
|
+
message's tool_call_id is no call of the assistant message before it, when a reply's calls are not each answered, or
|
|
8
|
+
when a message holds a key groq's message types have not (an index in a tool call). A stream gives each call in pieces:
|
|
9
|
+
its id and name first, then its arguments in two, the call's index on each, and x_groq on its first and last chunks.
|
|
10
|
+
Every request is kept in REQUESTS: its path, its body, what was refused in it (None when nothing) and its
|
|
11
|
+
authorization. Datacircle's answers are sent gzipped when the request asks for it.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import gzip
|
|
15
|
+
import json
|
|
16
|
+
import re
|
|
17
|
+
import threading
|
|
18
|
+
import time
|
|
19
|
+
import uuid
|
|
20
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
21
|
+
from typing import Any, Callable, Dict, List, Optional, Tuple
|
|
22
|
+
from urllib.parse import parse_qs, urlparse
|
|
23
|
+
|
|
24
|
+
REQUESTS: List[Dict[str, Any]] = []
|
|
25
|
+
KEYS = {"system": {"role", "content", "name"}, "developer": {"role", "content", "name"}, "user": {"role", "content", "name"},
|
|
26
|
+
"assistant": {"role", "content", "name", "tool_calls", "reasoning", "function_call"},
|
|
27
|
+
"tool": {"role", "content", "tool_call_id", "name"}}
|
|
28
|
+
CALL_KEYS = {"id", "type", "function"}
|
|
29
|
+
REASONING = "The user asks for these tools."
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def text_of(content: Any) -> str:
|
|
33
|
+
if isinstance(content, str):
|
|
34
|
+
return content
|
|
35
|
+
if isinstance(content, list):
|
|
36
|
+
return " ".join(part.get("text", "") for part in content if isinstance(part, dict))
|
|
37
|
+
return ""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def script(texts: List[str]) -> List[Tuple[str, Dict[str, Any]]]:
|
|
41
|
+
for text in texts:
|
|
42
|
+
found = re.findall(r"CALL (\w+) (\{.*?\})\s*$", text, re.M)
|
|
43
|
+
if found:
|
|
44
|
+
return [(name, json.loads(arguments)) for name, arguments in found]
|
|
45
|
+
return []
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def done(results: List[str]) -> str:
|
|
49
|
+
return "DONE " + " | ".join(result[:300] for result in results)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def chat_view(body: Dict[str, Any]) -> Tuple[List[str], List[Dict[str, Any]], Optional[str]]:
|
|
53
|
+
"""The user's texts, the tool messages, and what Groq's API would refuse in the messages."""
|
|
54
|
+
users, results, ids, answered, wrong = [], [], [], [], None
|
|
55
|
+
for number, message in enumerate(body.get("messages", [])):
|
|
56
|
+
role = message.get("role")
|
|
57
|
+
extra = set(message) - KEYS.get(role, set())
|
|
58
|
+
if wrong is None and (role not in KEYS or extra):
|
|
59
|
+
wrong = f"messages[{number}]: role {role!r}, keys not allowed: {sorted(extra)}"
|
|
60
|
+
if role != "tool" and ids and len(answered) != len(ids) and wrong is None:
|
|
61
|
+
wrong = f"messages[{number}]: {len(ids)} tool calls, {len(answered)} tool messages"
|
|
62
|
+
if role == "assistant":
|
|
63
|
+
calls = message.get("tool_calls") or []
|
|
64
|
+
for tool_call in calls:
|
|
65
|
+
extra = set(tool_call) - CALL_KEYS
|
|
66
|
+
if wrong is None and extra:
|
|
67
|
+
wrong = f"messages[{number}].tool_calls: keys not allowed: {sorted(extra)}"
|
|
68
|
+
arguments = (tool_call.get("function") or {}).get("arguments")
|
|
69
|
+
if wrong is None and not isinstance(arguments, str):
|
|
70
|
+
wrong = f"messages[{number}].tool_calls: arguments must be a string, not {arguments!r}"
|
|
71
|
+
ids, answered = [tool_call.get("id") for tool_call in calls], []
|
|
72
|
+
elif role == "tool":
|
|
73
|
+
given = message.get("tool_call_id")
|
|
74
|
+
results.append({"tool_call_id": given, "content": text_of(message.get("content"))})
|
|
75
|
+
answered.append(given)
|
|
76
|
+
if wrong is None and given not in ids:
|
|
77
|
+
wrong = f"messages[{number}]: tool_call_id {given} is no call of the assistant message before it"
|
|
78
|
+
elif role == "user":
|
|
79
|
+
users.append(text_of(message.get("content")))
|
|
80
|
+
if ids and len(answered) != len(ids) and wrong is None:
|
|
81
|
+
wrong = f"{len(ids)} tool calls, {len(answered)} tool messages"
|
|
82
|
+
return users, results, wrong
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class Handler(BaseHTTPRequestHandler):
|
|
86
|
+
api: Optional[Callable[[str, Dict[str, str], Dict[str, str]], Tuple[int, Any, Dict[str, str]]]] = None
|
|
87
|
+
|
|
88
|
+
def log_message(self, *args: Any) -> None:
|
|
89
|
+
pass
|
|
90
|
+
|
|
91
|
+
def send(self, status: int, body: Any, content_type: str = "application/json", headers: Optional[Dict[str, str]] = None,
|
|
92
|
+
squeeze: bool = False) -> None:
|
|
93
|
+
data = body.encode() if isinstance(body, str) else json.dumps(body).encode()
|
|
94
|
+
headers = dict(headers or {})
|
|
95
|
+
if squeeze:
|
|
96
|
+
data, headers["Content-Encoding"] = gzip.compress(data), "gzip"
|
|
97
|
+
self.send_response(status)
|
|
98
|
+
for key, value in {"Content-Type": content_type, "Content-Length": str(len(data)), **headers}.items():
|
|
99
|
+
self.send_header(key, value)
|
|
100
|
+
self.end_headers()
|
|
101
|
+
self.wfile.write(data)
|
|
102
|
+
|
|
103
|
+
def do_GET(self) -> None:
|
|
104
|
+
url = urlparse(self.path)
|
|
105
|
+
if type(self).api is None or not url.path.startswith("/v1/"):
|
|
106
|
+
return self.send(404, {"error": "no such path"})
|
|
107
|
+
query = {key: values[0] for key, values in parse_qs(url.query).items()}
|
|
108
|
+
status, body, headers = type(self).api(url.path, query, dict(self.headers))
|
|
109
|
+
self.send(status, body, headers=headers, squeeze="gzip" in (self.headers.get("Accept-Encoding") or ""))
|
|
110
|
+
|
|
111
|
+
def do_POST(self) -> None:
|
|
112
|
+
body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}")
|
|
113
|
+
seen = {"path": self.path, "body": body, "wrong": None, "authorization": self.headers.get("Authorization")}
|
|
114
|
+
REQUESTS.append(seen)
|
|
115
|
+
if self.path == "/openai/v1/chat/completions":
|
|
116
|
+
return self.chat(body, seen)
|
|
117
|
+
self.send(404, {"error": {"message": f"Unknown request URL: POST {self.path}", "type": "invalid_request_error"}})
|
|
118
|
+
|
|
119
|
+
def chat(self, body: Dict[str, Any], seen: Dict[str, Any]) -> None:
|
|
120
|
+
users, results, wrong = chat_view(body)
|
|
121
|
+
if wrong is not None:
|
|
122
|
+
seen["wrong"] = wrong
|
|
123
|
+
return self.send(400, {"error": {"message": wrong, "type": "invalid_request_error"}})
|
|
124
|
+
calls = script(users)
|
|
125
|
+
answer = done([result["content"] for result in results]) if len(results) >= len(calls) else None
|
|
126
|
+
rid, now = "chatcmpl-" + uuid.uuid4().hex, int(time.time())
|
|
127
|
+
usage = {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}
|
|
128
|
+
tool_calls = [{"id": "call_" + uuid.uuid4().hex[:24], "type": "function",
|
|
129
|
+
"function": {"name": name, "arguments": json.dumps(arguments)}} for name, arguments in calls]
|
|
130
|
+
if not body.get("stream"):
|
|
131
|
+
message = {"role": "assistant", "content": answer} if answer else \
|
|
132
|
+
{"role": "assistant", "reasoning": REASONING, "tool_calls": tool_calls}
|
|
133
|
+
return self.send(200, {"id": rid, "object": "chat.completion", "model": body.get("model"), "usage": usage,
|
|
134
|
+
"created": now, "system_fingerprint": "stand-in", "x_groq": {"id": "req_" + rid},
|
|
135
|
+
"choices": [{"index": 0, "message": message, "logprobs": None,
|
|
136
|
+
"finish_reason": "stop" if answer else "tool_calls"}]})
|
|
137
|
+
|
|
138
|
+
def chunk(delta: Dict[str, Any], finish: Optional[str], **more: Any) -> str:
|
|
139
|
+
return "data: " + json.dumps({"id": rid, "object": "chat.completion.chunk", "created": now, "model": body.get("model"),
|
|
140
|
+
"system_fingerprint": "stand-in", **more,
|
|
141
|
+
"choices": [{"index": 0, "delta": delta, "logprobs": None, "finish_reason": finish}]}) + "\n\n"
|
|
142
|
+
events = [chunk({"role": "assistant", "content": ""}, None, x_groq={"id": "req_" + rid})]
|
|
143
|
+
if answer:
|
|
144
|
+
events += [chunk({"content": answer[:20]}, None), chunk({"content": answer[20:]}, None)]
|
|
145
|
+
else:
|
|
146
|
+
events.append(chunk({"reasoning": REASONING}, None))
|
|
147
|
+
for index, tool_call in enumerate(tool_calls):
|
|
148
|
+
arguments = tool_call["function"]["arguments"]
|
|
149
|
+
half = len(arguments) // 2
|
|
150
|
+
events.append(chunk({"tool_calls": [{"index": index, "id": tool_call["id"], "type": "function",
|
|
151
|
+
"function": {"name": tool_call["function"]["name"], "arguments": ""}}]}, None))
|
|
152
|
+
events.append(chunk({"tool_calls": [{"index": index, "function": {"arguments": arguments[:half]}}]}, None))
|
|
153
|
+
events.append(chunk({"tool_calls": [{"index": index, "function": {"arguments": arguments[half:]}}]}, None))
|
|
154
|
+
events.append(chunk({}, "stop" if answer else "tool_calls", x_groq={"id": "req_" + rid, "usage": usage}))
|
|
155
|
+
self.send(200, "".join(events) + "data: [DONE]\n\n", "text/event-stream")
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def start(api: Optional[Callable[..., Tuple[int, Any, Dict[str, str]]]] = None) -> ThreadingHTTPServer:
|
|
159
|
+
"""The stand-in, serving on a free port of 127.0.0.1 in a thread; api answers GET /v1/... when given."""
|
|
160
|
+
handler = type("StandIn", (Handler,), {"api": staticmethod(api) if api else None})
|
|
161
|
+
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
|
|
162
|
+
threading.Thread(target=server.serve_forever, daemon=True).start()
|
|
163
|
+
return server
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
"""Offline tests: the tools against a stand-in for Datacircle's API on 127.0.0.1, by run(), call() and call_all() on
|
|
2
|
+
groq's own tool calls, sent by Groq's chat.completions.create (plain and streamed) and AsyncGroq's to a stand-in for
|
|
3
|
+
Groq's chat server through base_url."""
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import sys
|
|
9
|
+
import time
|
|
10
|
+
|
|
11
|
+
import pytest
|
|
12
|
+
|
|
13
|
+
sys.path.insert(0, os.path.dirname(__file__))
|
|
14
|
+
import stand_in # noqa: E402
|
|
15
|
+
|
|
16
|
+
from groq import AsyncGroq, Groq # noqa: E402
|
|
17
|
+
|
|
18
|
+
from groq_datacircle import ( # noqa: E402
|
|
19
|
+
TOOL_NAMES,
|
|
20
|
+
acall,
|
|
21
|
+
acall_all,
|
|
22
|
+
call,
|
|
23
|
+
call_all,
|
|
24
|
+
collect_tool_calls,
|
|
25
|
+
datacircle_tools,
|
|
26
|
+
run,
|
|
27
|
+
)
|
|
28
|
+
from groq_datacircle import _api # noqa: E402
|
|
29
|
+
|
|
30
|
+
PLAN = {"api": "Employee email", "rank": 1, "provider": "Hunter", "plan": "Starter", "score": 80.1, "perThousand": 4.9,
|
|
31
|
+
"page": "https://datacircle.dev/x", "terms": "long", "aggregators": ["a"]}
|
|
32
|
+
SEEN = []
|
|
33
|
+
BUSY = []
|
|
34
|
+
MODEL = "openai/gpt-oss-20b"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def api(path, query, headers):
|
|
38
|
+
SEEN.append((path, query, headers.get("User-Agent"), headers.get("Accept-Encoding")))
|
|
39
|
+
if path == "/v1/plans" and query.get("query") == "busy" and not BUSY:
|
|
40
|
+
BUSY.append(1)
|
|
41
|
+
return 429, {"error": "slow down"}, {"Retry-After": "1"}
|
|
42
|
+
if path == "/v1/apis":
|
|
43
|
+
return 200, [{"api": "Employee email", "slug": "email-finder", "plans": 9, "providers": 3, "extra": 1},
|
|
44
|
+
{"api": "Employee profile", "slug": "linkedin-profile", "plans": 4, "providers": 2}], {}
|
|
45
|
+
if path == "/v1/apis/email-finder/best":
|
|
46
|
+
return 200, {"api": "Employee email", "slug": "email-finder", "total": 1, "plans": [PLAN]}, {}
|
|
47
|
+
if path.startswith("/v1/apis/"):
|
|
48
|
+
return 404, {"error": "no API has the slug nope", "slugs": ["email-finder", "linkedin-profile"]}, {}
|
|
49
|
+
if path == "/v1/plans" and query.get("query") == "down":
|
|
50
|
+
return 503, {"error": "down for a minute"}, {}
|
|
51
|
+
if path == "/v1/plans":
|
|
52
|
+
return 200, {"total": 1, "offset": 0, "plans": [PLAN]}, {}
|
|
53
|
+
if path == "/v1/providers/bright-data":
|
|
54
|
+
# plans=best: each API's best plan alone and planCount, as the API gives them once asked
|
|
55
|
+
return 200, {"provider": "Bright Data", "slug": "bright-data", "website": "https://brightdata.com",
|
|
56
|
+
"apis": [{"api": "Employee email", "slug": "email-finder", "rank": 7, "sheetPage": "s",
|
|
57
|
+
"plans": [dict(PLAN, rank=7, plan="A")], "planCount": 2}]}, {}
|
|
58
|
+
if path == "/v1/providers/hunter":
|
|
59
|
+
# an API that leaves plans=best out gives every plan and no planCount
|
|
60
|
+
return 200, {"provider": "Hunter", "slug": "hunter", "website": "https://hunter.io",
|
|
61
|
+
"apis": [{"api": "Employee email", "slug": "email-finder", "rank": 1, "sheetPage": "s",
|
|
62
|
+
"plans": [dict(PLAN, rank=9, plan="B"), dict(PLAN, rank=1, plan="A"), dict(PLAN, rank=None)]}]}, {}
|
|
63
|
+
return 404, {"error": "no provider has this slug"}, {}
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@pytest.fixture(scope="module", autouse=True)
|
|
67
|
+
def server():
|
|
68
|
+
made = stand_in.start(api)
|
|
69
|
+
before = _api.BASE_URL
|
|
70
|
+
_api.BASE_URL = f"http://127.0.0.1:{made.server_address[1]}/v1"
|
|
71
|
+
yield f"http://127.0.0.1:{made.server_address[1]}"
|
|
72
|
+
_api.BASE_URL = before
|
|
73
|
+
made.shutdown()
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@pytest.fixture
|
|
77
|
+
def client(server):
|
|
78
|
+
return Groq(base_url=server, api_key="test", max_retries=0)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def calls_made(name, arguments):
|
|
82
|
+
SEEN.clear()
|
|
83
|
+
return json.loads(run(name, arguments)), list(SEEN)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def field(item, key):
|
|
87
|
+
return item[key] if isinstance(item, dict) else getattr(item, key)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def add_two_numbers(a, b):
|
|
91
|
+
return int(a) + int(b)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
ADD = {"type": "function", "function": {"name": "add_two_numbers", "description": "Adds two numbers.", "parameters": {
|
|
95
|
+
"type": "object", "properties": {"a": {"type": "integer"}, "b": {"type": "integer"}}, "required": ["a", "b"]}}}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def test_definitions():
|
|
99
|
+
tools = datacircle_tools()
|
|
100
|
+
assert [tool["function"]["name"] for tool in tools] == TOOL_NAMES == [
|
|
101
|
+
"datacircle_list_apis", "datacircle_best_plans", "datacircle_search_plans", "datacircle_provider"]
|
|
102
|
+
for tool in tools:
|
|
103
|
+
assert tool["type"] == "function" and "https://datacircle.dev" in tool["function"]["description"]
|
|
104
|
+
assert tool["function"]["parameters"]["type"] == "object"
|
|
105
|
+
search = tools[2]["function"]["parameters"]["properties"]
|
|
106
|
+
assert search["sort"]["enum"] == ["score", "provider", "price"] and search["limit"]["maximum"] == 50
|
|
107
|
+
assert tools[1]["function"]["parameters"]["required"] == ["slug"]
|
|
108
|
+
assert [tool["function"]["name"] for tool in datacircle_tools(["datacircle_provider"])] == ["datacircle_provider"]
|
|
109
|
+
tools[0]["function"]["description"] = "changed"
|
|
110
|
+
assert datacircle_tools()[0]["function"]["description"] != "changed"
|
|
111
|
+
with pytest.raises(ValueError):
|
|
112
|
+
datacircle_tools(["nope"])
|
|
113
|
+
with pytest.raises(TypeError):
|
|
114
|
+
datacircle_tools("datacircle_provider")
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def test_each_tool_calls_the_api_gzipped():
|
|
118
|
+
answer, seen = calls_made("datacircle_list_apis", {"query": "profile", "limit": 1})
|
|
119
|
+
assert answer == {"total": 1, "apis": [{"api": "Employee profile", "slug": "linkedin-profile", "plans": 4, "providers": 2}]}
|
|
120
|
+
assert seen == [("/v1/apis", {}, "groq-datacircle/0.1.0", "gzip")]
|
|
121
|
+
answer, seen = calls_made("datacircle_best_plans", '{"slug": "Email Finder", "limit": 3}')
|
|
122
|
+
assert seen[0][:2] == ("/v1/apis/email-finder/best", {"limit": "3"})
|
|
123
|
+
assert answer["plans"] == [{key: PLAN[key] for key in ("api", "rank", "provider", "plan", "score", "perThousand", "page")}]
|
|
124
|
+
answer, seen = calls_made("datacircle_search_plans", {"api": "email-finder", "query": "hunter", "sort": "price",
|
|
125
|
+
"limit": "2", "offset": 1, "unknown": 1})
|
|
126
|
+
assert seen[0][:2] == ("/v1/plans", {"api": "email-finder", "query": "hunter", "sort": "price", "limit": "2", "offset": "1"})
|
|
127
|
+
best = {"plan": "A", "score": 80.1, "perThousand": 4.9, "page": "https://datacircle.dev/x"}
|
|
128
|
+
answer, seen = calls_made("datacircle_provider", {"slug": "Bright Data"})
|
|
129
|
+
assert seen[0][:2] == ("/v1/providers/bright-data", {"plans": "best"})
|
|
130
|
+
assert answer["apis"] == [{"api": "Employee email", "slug": "email-finder", "rank": 7, "plans": 2, "best": best}]
|
|
131
|
+
answer, _ = calls_made("datacircle_provider", {"slug": "hunter"})
|
|
132
|
+
assert answer["apis"] == [{"api": "Employee email", "slug": "email-finder", "rank": 1, "plans": 3, "best": best}]
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def test_refusals_in_the_apis_words():
|
|
136
|
+
answer, _ = calls_made("datacircle_best_plans", {"slug": "nope"})
|
|
137
|
+
assert "404" in answer["error"] and "email-finder, linkedin-profile" in answer["error"]
|
|
138
|
+
answer, _ = calls_made("datacircle_search_plans", {"query": "down"})
|
|
139
|
+
assert "503" in answer["error"] and "down for a minute" in answer["error"]
|
|
140
|
+
answer, seen = calls_made("datacircle_best_plans", {"slug": "email-finder", "limit": 51})
|
|
141
|
+
assert answer == {"error": "limit must be from 1 to 50, not 51"} and seen == []
|
|
142
|
+
answer, seen = calls_made("datacircle_search_plans", '{"sort": "cheapest"}')
|
|
143
|
+
assert "sort must be score, provider or price" in answer["error"] and seen == []
|
|
144
|
+
assert "no JSON object" in json.loads(run("datacircle_provider", "{oops"))["error"]
|
|
145
|
+
assert "Give a provider's slug" in json.loads(run("datacircle_provider", None))["error"]
|
|
146
|
+
with pytest.raises(ValueError):
|
|
147
|
+
run("nope", {})
|
|
148
|
+
started = time.monotonic()
|
|
149
|
+
answer, seen = calls_made("datacircle_search_plans", {"query": "busy"})
|
|
150
|
+
assert answer["total"] == 1 and len(seen) == 2 and time.monotonic() - started >= 1
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def test_call_on_groqs_tool_calls():
|
|
154
|
+
from groq.types.chat import ChatCompletionMessage
|
|
155
|
+
# construct() builds groq's nested types from dicts, as the client does from Groq's answer
|
|
156
|
+
message = ChatCompletionMessage.construct(role="assistant", content=None, tool_calls=[
|
|
157
|
+
{"id": "call_1", "type": "function", "function": {"name": "datacircle_best_plans", "arguments": '{"slug": "email-finder"}'}},
|
|
158
|
+
{"id": "call_2", "type": "function", "function": {"name": "add_two_numbers", "arguments": '{"a": 1, "b": 2}'}},
|
|
159
|
+
{"id": "call_3", "type": "function", "function": {"name": "datacircle_provider", "arguments": '{"slug": "bright-data"}'}}])
|
|
160
|
+
assert type(message.tool_calls[0]).__name__ == "ChatCompletionMessageToolCall"
|
|
161
|
+
first = call(message.tool_calls[0])
|
|
162
|
+
assert first == {"role": "tool", "tool_call_id": "call_1", "content": first["content"]}
|
|
163
|
+
assert json.loads(first["content"])["plans"][0]["provider"] == "Hunter"
|
|
164
|
+
assert call(message.tool_calls[1]) is None
|
|
165
|
+
messages = call_all(message)
|
|
166
|
+
assert [m["tool_call_id"] for m in messages] == ["call_1", "call_3"]
|
|
167
|
+
assert json.loads(messages[1]["content"])["slug"] == "bright-data"
|
|
168
|
+
assert [m["tool_call_id"] for m in call_all(message.tool_calls[2:])] == ["call_3"] and call_all(None) == []
|
|
169
|
+
assert call_all({"role": "assistant", "tool_calls": [{"id": "call_4", "type": "function", "function": {
|
|
170
|
+
"name": "datacircle_list_apis", "arguments": "{}"}}]})[0]["tool_call_id"] == "call_4"
|
|
171
|
+
assert asyncio.run(acall(message.tool_calls[1])) is None
|
|
172
|
+
assert [m["tool_call_id"] for m in asyncio.run(acall_all(message))] == ["call_1", "call_3"]
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def stream_turn(chunks):
|
|
176
|
+
content, calls = "", []
|
|
177
|
+
for chunk in chunks:
|
|
178
|
+
if not chunk.choices:
|
|
179
|
+
continue
|
|
180
|
+
delta = chunk.choices[0].delta
|
|
181
|
+
content += delta.content or ""
|
|
182
|
+
collect_tool_calls(calls, delta.tool_calls)
|
|
183
|
+
return content, calls
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def chat_loop(client, question, tools, stream=False):
|
|
187
|
+
"""The README's loop: ask, run each call (ours with call(), the app's own itself), ask again, till an answer."""
|
|
188
|
+
messages = [{"role": "user", "content": question}]
|
|
189
|
+
for _ in range(4):
|
|
190
|
+
if stream:
|
|
191
|
+
content, calls = stream_turn(client.chat.completions.create(model=MODEL, messages=messages, tools=tools, stream=True))
|
|
192
|
+
message = {"role": "assistant", "content": content, "tool_calls": calls}
|
|
193
|
+
else:
|
|
194
|
+
message = client.chat.completions.create(model=MODEL, messages=messages, tools=tools).choices[0].message
|
|
195
|
+
content, calls = message.content, message.tool_calls or []
|
|
196
|
+
if not calls:
|
|
197
|
+
return content
|
|
198
|
+
messages.append(message)
|
|
199
|
+
for tool_call in calls:
|
|
200
|
+
result = call(tool_call)
|
|
201
|
+
if result is None:
|
|
202
|
+
function = field(tool_call, "function")
|
|
203
|
+
result = {"role": "tool", "tool_call_id": field(tool_call, "id"),
|
|
204
|
+
"content": str(add_two_numbers(**json.loads(field(function, "arguments"))))}
|
|
205
|
+
messages.append(result)
|
|
206
|
+
raise AssertionError("no answer after 4 turns")
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
QUESTION = ('CALL datacircle_best_plans {"slug": "email-finder", "limit": 1}\nCALL add_two_numbers {"a": 1, "b": 2}\n'
|
|
210
|
+
'CALL datacircle_list_apis {"query": "profile"}')
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
@pytest.mark.parametrize("stream", [False, True])
|
|
214
|
+
def test_chat_beside_an_apps_own_tool(client, stream):
|
|
215
|
+
stand_in.REQUESTS.clear()
|
|
216
|
+
answer = chat_loop(client, QUESTION, [*datacircle_tools(), ADD], stream)
|
|
217
|
+
assert answer.startswith("DONE ") and '"Hunter"' in answer and "| 3 |" in answer and "linkedin-profile" in answer
|
|
218
|
+
sent = stand_in.REQUESTS
|
|
219
|
+
assert [r["wrong"] for r in sent] == [None, None] and all(bool(r["body"].get("stream")) == stream for r in sent)
|
|
220
|
+
assert all(r["path"] == "/openai/v1/chat/completions" and r["authorization"] == "Bearer test" for r in sent)
|
|
221
|
+
assert [tool["function"]["name"] for tool in sent[0]["body"]["tools"]] == TOOL_NAMES + ["add_two_numbers"]
|
|
222
|
+
assert sent[0]["body"]["tools"][2]["function"]["parameters"] == datacircle_tools()[2]["function"]["parameters"]
|
|
223
|
+
tool_messages = [m for m in sent[1]["body"]["messages"] if m["role"] == "tool"]
|
|
224
|
+
assert [m["content"] for m in tool_messages][1] == "3" and len(tool_messages) == 3
|
|
225
|
+
assert json.loads(tool_messages[0]["content"])["plans"][0]["provider"] == "Hunter"
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def test_a_refusal_goes_back_to_the_model(client):
|
|
229
|
+
stand_in.REQUESTS.clear()
|
|
230
|
+
answer = chat_loop(client, 'CALL datacircle_best_plans {"slug": "nope"}', datacircle_tools())
|
|
231
|
+
assert "no API has the slug nope" in answer and "email-finder, linkedin-profile" in answer
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
@pytest.mark.parametrize("stream", [False, True])
|
|
235
|
+
def test_async_groq_runs_the_calls_at_once(server, stream):
|
|
236
|
+
stand_in.REQUESTS.clear()
|
|
237
|
+
|
|
238
|
+
async def main():
|
|
239
|
+
client = AsyncGroq(base_url=server, api_key="test", max_retries=0)
|
|
240
|
+
|
|
241
|
+
async def turn(messages):
|
|
242
|
+
if not stream:
|
|
243
|
+
return (await client.chat.completions.create(model=MODEL, messages=messages,
|
|
244
|
+
tools=datacircle_tools())).choices[0].message
|
|
245
|
+
content, calls = "", []
|
|
246
|
+
async for chunk in await client.chat.completions.create(model=MODEL, messages=messages, tools=datacircle_tools(),
|
|
247
|
+
stream=True):
|
|
248
|
+
if chunk.choices:
|
|
249
|
+
content += chunk.choices[0].delta.content or ""
|
|
250
|
+
collect_tool_calls(calls, chunk.choices[0].delta.tool_calls)
|
|
251
|
+
return {"role": "assistant", "content": content, "tool_calls": calls}
|
|
252
|
+
|
|
253
|
+
messages = [{"role": "user", "content": 'CALL datacircle_best_plans {"slug": "email-finder"}\n'
|
|
254
|
+
'CALL datacircle_provider {"slug": "Bright Data"}'}]
|
|
255
|
+
message = await turn(messages)
|
|
256
|
+
if field(message, "tool_calls"):
|
|
257
|
+
messages.append(message)
|
|
258
|
+
messages.extend(await acall_all(message))
|
|
259
|
+
message = await turn(messages)
|
|
260
|
+
await client.close()
|
|
261
|
+
return field(message, "content")
|
|
262
|
+
answer = asyncio.run(main())
|
|
263
|
+
assert answer.startswith("DONE ") and "Hunter" in answer and "bright-data" in answer
|
|
264
|
+
assert [r["wrong"] for r in stand_in.REQUESTS] == [None, None]
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def test_collect_tool_calls_from_pieces():
|
|
268
|
+
calls = []
|
|
269
|
+
collect_tool_calls(calls, [{"index": 0, "id": "call_1", "function": {"name": "datacircle_provider", "arguments": '{"sl'}}])
|
|
270
|
+
collect_tool_calls(calls, [{"index": 0, "function": {"arguments": 'ug": "bright-data"}'}},
|
|
271
|
+
{"index": 1, "id": "call_2", "function": {"name": "add_two_numbers", "arguments": '{"a": 1}'}}])
|
|
272
|
+
collect_tool_calls(calls, None)
|
|
273
|
+
assert json.loads(json.dumps(calls)) == calls == [
|
|
274
|
+
{"id": "call_1", "type": "function", "function": {"name": "datacircle_provider", "arguments": '{"slug": "bright-data"}'}},
|
|
275
|
+
{"id": "call_2", "type": "function", "function": {"name": "add_two_numbers", "arguments": '{"a": 1}'}}]
|
|
276
|
+
assert [json.loads(m["content"])["slug"] for m in call_all(calls)] == ["bright-data"]
|
|
277
|
+
whole = []
|
|
278
|
+
collect_tool_calls(whole, [{"index": 0, "id": "call_a", "function": {"name": "datacircle_provider", "arguments": "{}"}}])
|
|
279
|
+
collect_tool_calls(whole, [{"index": 0, "id": "call_b", "function": {"name": "datacircle_list_apis", "arguments": "{}"}}])
|
|
280
|
+
assert [made["id"] for made in whole] == ["call_a", "call_b"]
|