llama-cpp-python-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.
- llama_cpp_python_datacircle-0.1.0/.gitignore +4 -0
- llama_cpp_python_datacircle-0.1.0/LICENSE +9 -0
- llama_cpp_python_datacircle-0.1.0/PKG-INFO +154 -0
- llama_cpp_python_datacircle-0.1.0/README.md +138 -0
- llama_cpp_python_datacircle-0.1.0/pyproject.toml +34 -0
- llama_cpp_python_datacircle-0.1.0/src/llama_cpp_datacircle/__init__.py +7 -0
- llama_cpp_python_datacircle-0.1.0/src/llama_cpp_datacircle/_api.py +101 -0
- llama_cpp_python_datacircle-0.1.0/src/llama_cpp_datacircle/py.typed +0 -0
- llama_cpp_python_datacircle-0.1.0/src/llama_cpp_datacircle/tools.py +287 -0
- llama_cpp_python_datacircle-0.1.0/tests/conftest.py +77 -0
- llama_cpp_python_datacircle-0.1.0/tests/test_live.py +29 -0
- llama_cpp_python_datacircle-0.1.0/tests/test_llama.py +66 -0
- llama_cpp_python_datacircle-0.1.0/tests/test_replies.py +83 -0
- llama_cpp_python_datacircle-0.1.0/tests/test_tools.py +81 -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,154 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: llama-cpp-python-datacircle
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: llama-cpp-python 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/llama-cpp-python-datacircle
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: api,api-pricing,b2b-data,datacircle,function-calling,gguf,gtm,llama-cpp-python,llama.cpp,local-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
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
|
|
17
|
+
# llama-cpp-python-datacircle
|
|
18
|
+
|
|
19
|
+
Find the best GTM APIs. We benchmark all the GTM APIs and we put the results on our website.
|
|
20
|
+
|
|
21
|
+
Our website: https://datacircle.dev
|
|
22
|
+
|
|
23
|
+
This package gives [llama-cpp-python](https://github.com/abetlen/llama-cpp-python) four tools that call Datacircle's open API, https://api.datacircle.dev/v1. You pass the four tools to `Llama.create_chat_completion()` or to llama-cpp-python's OpenAI-compatible server. The package then runs each tool call the model returns. You need no key and no account.
|
|
24
|
+
|
|
25
|
+
| Tool | What the tool gives | Call |
|
|
26
|
+
| --- | --- | --- |
|
|
27
|
+
| `datacircle_list_apis` | Every GTM API on Datacircle, with the API's slug, number of plans, number of providers and best plan | `GET /apis` |
|
|
28
|
+
| `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` |
|
|
29
|
+
| `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` |
|
|
30
|
+
| `datacircle_provider` | The APIs a provider sells, and the provider's rank on each API | `GET /providers/{slug}` |
|
|
31
|
+
|
|
32
|
+
## Install
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install llama-cpp-python-datacircle
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
llama-cpp-python-datacircle works with any version of `llama-cpp-python`, on Python 3.9 and later. The package does not import `llama_cpp`.
|
|
39
|
+
|
|
40
|
+
## Use the tools with the model's own chat template
|
|
41
|
+
|
|
42
|
+
Most GGUF models come with a chat template. llama-cpp-python uses that template when you give no `chat_format`. Some chat templates take tools. With one of those templates, the model writes each tool call in the text of the reply. `call_all()` reads those calls and gives you the tool messages to send back:
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
from llama_cpp import Llama
|
|
46
|
+
from llama_cpp_datacircle import call_all, datacircle_tools
|
|
47
|
+
|
|
48
|
+
llm = Llama(model_path="qwen2.5-3b-instruct-q4_k_m.gguf", n_ctx=8192)
|
|
49
|
+
messages = [{"role": "user", "content": "Who are the 3 best providers for the email-finder API?"}]
|
|
50
|
+
reply = llm.create_chat_completion(messages=messages, tools=datacircle_tools())
|
|
51
|
+
|
|
52
|
+
while tool_messages := call_all(reply):
|
|
53
|
+
messages.append(reply["choices"][0]["message"])
|
|
54
|
+
messages.extend(tool_messages)
|
|
55
|
+
reply = llm.create_chat_completion(messages=messages, tools=datacircle_tools())
|
|
56
|
+
|
|
57
|
+
print(reply["choices"][0]["message"]["content"])
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
On each new call, the model's chat template puts each tool message in the prompt. We tested this loop with Qwen 2.5 (3B) and Qwen 3 (1.7B). Qwen writes each call in a `<tool_call>` block. Llama 3.2 writes calls as JSON. `call_all()` reads both formats.
|
|
61
|
+
|
|
62
|
+
## Use the tools with chatml-function-calling
|
|
63
|
+
|
|
64
|
+
With `chat_format="chatml-function-calling"`, llama-cpp-python puts the model's tool calls in the reply's `tool_calls`. `call_all()` runs those calls like calls from any other chat format. In llama-cpp-python 0.3.38, chatml-function-calling leaves tool messages out of the prompt. So the model never reads the tool's answer. To let the model read tool answers, use the model's own chat template.
|
|
65
|
+
|
|
66
|
+
To make the model call one tool, name the tool in `tool_choice`. Naming a tool works with any chat format. llama-cpp-python then makes the model write only the tool's arguments. The call comes in `tool_calls`:
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
reply = llm.create_chat_completion(
|
|
70
|
+
messages=messages,
|
|
71
|
+
tools=datacircle_tools(),
|
|
72
|
+
tool_choice={"type": "function", "function": {"name": "datacircle_best_plans"}},
|
|
73
|
+
)
|
|
74
|
+
messages.append(reply["choices"][0]["message"])
|
|
75
|
+
messages.extend(call_all(reply))
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Use the Datacircle tools beside your own tools
|
|
79
|
+
|
|
80
|
+
You can put the Datacircle tools in the same list as yours: `tools=[*datacircle_tools(), my_tool]`.
|
|
81
|
+
|
|
82
|
+
`tool_calls()` gives every call in a reply, including calls to your own tools. `call()` runs one call. For your own tools, `call()` returns `None`. Your code then runs the tool itself:
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
from llama_cpp_datacircle import call, tool_calls
|
|
86
|
+
|
|
87
|
+
calls = tool_calls(reply)
|
|
88
|
+
messages.append(reply["choices"][0]["message"])
|
|
89
|
+
for tool_call in calls:
|
|
90
|
+
messages.append(call(tool_call) or my_run_tool(tool_call))
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
Each call is an OpenAI-format tool call with an `id`. Each tool message has `role: "tool"`, the call's id in `tool_call_id`, and the answer as JSON text in `content`.
|
|
94
|
+
|
|
95
|
+
To give the model only some of the tools, list their names: `datacircle_tools(["datacircle_best_plans"])`.
|
|
96
|
+
|
|
97
|
+
## Use the tools with the OpenAI-compatible server
|
|
98
|
+
|
|
99
|
+
Start llama-cpp-python's server, then call the server with the OpenAI client. `call_all()` reads the reply from the OpenAI client:
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
pip install 'llama-cpp-python[server]' openai
|
|
103
|
+
python -m llama_cpp.server --model qwen2.5-3b-instruct-q4_k_m.gguf --n_ctx 8192
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
```python
|
|
107
|
+
from openai import OpenAI
|
|
108
|
+
from llama_cpp_datacircle import call_all, datacircle_tools
|
|
109
|
+
|
|
110
|
+
client = OpenAI(base_url="http://localhost:8000/v1", api_key="none")
|
|
111
|
+
messages = [{"role": "user", "content": "Who are the 3 best providers for the email-finder API?"}]
|
|
112
|
+
reply = client.chat.completions.create(model="local", messages=messages, tools=datacircle_tools())
|
|
113
|
+
|
|
114
|
+
while tool_messages := call_all(reply):
|
|
115
|
+
messages.append(reply.choices[0].message.model_dump(exclude_none=True))
|
|
116
|
+
messages.extend(tool_messages)
|
|
117
|
+
reply = client.chat.completions.create(model="local", messages=messages, tools=datacircle_tools())
|
|
118
|
+
|
|
119
|
+
print(reply.choices[0].message.content)
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
## Call a tool yourself
|
|
123
|
+
|
|
124
|
+
You can call each tool without a model. You get the JSON text of the tool's answer:
|
|
125
|
+
|
|
126
|
+
```python
|
|
127
|
+
import json
|
|
128
|
+
|
|
129
|
+
from llama_cpp_datacircle import run
|
|
130
|
+
|
|
131
|
+
answer = json.loads(run("datacircle_best_plans", {"slug": "email-finder", "limit": 3}))
|
|
132
|
+
print(answer["plans"])
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
## What the model reads
|
|
136
|
+
|
|
137
|
+
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.
|
|
138
|
+
|
|
139
|
+
You can give a provider's name in place of a slug. The tool turns `Bright Data` into `bright-data`.
|
|
140
|
+
|
|
141
|
+
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.
|
|
142
|
+
|
|
143
|
+
## Network
|
|
144
|
+
|
|
145
|
+
Your model runs on your machine. 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.
|
|
146
|
+
|
|
147
|
+
## Links
|
|
148
|
+
|
|
149
|
+
- Datacircle: https://datacircle.dev
|
|
150
|
+
- The API: https://datacircle.dev/api
|
|
151
|
+
- The API's spec: https://api.datacircle.dev/v1/openapi.json
|
|
152
|
+
- Every field of a plan: https://datacircle.dev/fields
|
|
153
|
+
|
|
154
|
+
MIT license.
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
# llama-cpp-python-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 [llama-cpp-python](https://github.com/abetlen/llama-cpp-python) four tools that call Datacircle's open API, https://api.datacircle.dev/v1. You pass the four tools to `Llama.create_chat_completion()` or to llama-cpp-python's OpenAI-compatible server. The package then runs each tool call the model returns. You need 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, and the provider's rank on each API | `GET /providers/{slug}` |
|
|
15
|
+
|
|
16
|
+
## Install
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
pip install llama-cpp-python-datacircle
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
llama-cpp-python-datacircle works with any version of `llama-cpp-python`, on Python 3.9 and later. The package does not import `llama_cpp`.
|
|
23
|
+
|
|
24
|
+
## Use the tools with the model's own chat template
|
|
25
|
+
|
|
26
|
+
Most GGUF models come with a chat template. llama-cpp-python uses that template when you give no `chat_format`. Some chat templates take tools. With one of those templates, the model writes each tool call in the text of the reply. `call_all()` reads those calls and gives you the tool messages to send back:
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
from llama_cpp import Llama
|
|
30
|
+
from llama_cpp_datacircle import call_all, datacircle_tools
|
|
31
|
+
|
|
32
|
+
llm = Llama(model_path="qwen2.5-3b-instruct-q4_k_m.gguf", n_ctx=8192)
|
|
33
|
+
messages = [{"role": "user", "content": "Who are the 3 best providers for the email-finder API?"}]
|
|
34
|
+
reply = llm.create_chat_completion(messages=messages, tools=datacircle_tools())
|
|
35
|
+
|
|
36
|
+
while tool_messages := call_all(reply):
|
|
37
|
+
messages.append(reply["choices"][0]["message"])
|
|
38
|
+
messages.extend(tool_messages)
|
|
39
|
+
reply = llm.create_chat_completion(messages=messages, tools=datacircle_tools())
|
|
40
|
+
|
|
41
|
+
print(reply["choices"][0]["message"]["content"])
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
On each new call, the model's chat template puts each tool message in the prompt. We tested this loop with Qwen 2.5 (3B) and Qwen 3 (1.7B). Qwen writes each call in a `<tool_call>` block. Llama 3.2 writes calls as JSON. `call_all()` reads both formats.
|
|
45
|
+
|
|
46
|
+
## Use the tools with chatml-function-calling
|
|
47
|
+
|
|
48
|
+
With `chat_format="chatml-function-calling"`, llama-cpp-python puts the model's tool calls in the reply's `tool_calls`. `call_all()` runs those calls like calls from any other chat format. In llama-cpp-python 0.3.38, chatml-function-calling leaves tool messages out of the prompt. So the model never reads the tool's answer. To let the model read tool answers, use the model's own chat template.
|
|
49
|
+
|
|
50
|
+
To make the model call one tool, name the tool in `tool_choice`. Naming a tool works with any chat format. llama-cpp-python then makes the model write only the tool's arguments. The call comes in `tool_calls`:
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
reply = llm.create_chat_completion(
|
|
54
|
+
messages=messages,
|
|
55
|
+
tools=datacircle_tools(),
|
|
56
|
+
tool_choice={"type": "function", "function": {"name": "datacircle_best_plans"}},
|
|
57
|
+
)
|
|
58
|
+
messages.append(reply["choices"][0]["message"])
|
|
59
|
+
messages.extend(call_all(reply))
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Use the Datacircle tools beside your own tools
|
|
63
|
+
|
|
64
|
+
You can put the Datacircle tools in the same list as yours: `tools=[*datacircle_tools(), my_tool]`.
|
|
65
|
+
|
|
66
|
+
`tool_calls()` gives every call in a reply, including calls to your own tools. `call()` runs one call. For your own tools, `call()` returns `None`. Your code then runs the tool itself:
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
from llama_cpp_datacircle import call, tool_calls
|
|
70
|
+
|
|
71
|
+
calls = tool_calls(reply)
|
|
72
|
+
messages.append(reply["choices"][0]["message"])
|
|
73
|
+
for tool_call in calls:
|
|
74
|
+
messages.append(call(tool_call) or my_run_tool(tool_call))
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Each call is an OpenAI-format tool call with an `id`. Each tool message has `role: "tool"`, the call's id in `tool_call_id`, and the answer as JSON text in `content`.
|
|
78
|
+
|
|
79
|
+
To give the model only some of the tools, list their names: `datacircle_tools(["datacircle_best_plans"])`.
|
|
80
|
+
|
|
81
|
+
## Use the tools with the OpenAI-compatible server
|
|
82
|
+
|
|
83
|
+
Start llama-cpp-python's server, then call the server with the OpenAI client. `call_all()` reads the reply from the OpenAI client:
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
pip install 'llama-cpp-python[server]' openai
|
|
87
|
+
python -m llama_cpp.server --model qwen2.5-3b-instruct-q4_k_m.gguf --n_ctx 8192
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
from openai import OpenAI
|
|
92
|
+
from llama_cpp_datacircle import call_all, datacircle_tools
|
|
93
|
+
|
|
94
|
+
client = OpenAI(base_url="http://localhost:8000/v1", api_key="none")
|
|
95
|
+
messages = [{"role": "user", "content": "Who are the 3 best providers for the email-finder API?"}]
|
|
96
|
+
reply = client.chat.completions.create(model="local", messages=messages, tools=datacircle_tools())
|
|
97
|
+
|
|
98
|
+
while tool_messages := call_all(reply):
|
|
99
|
+
messages.append(reply.choices[0].message.model_dump(exclude_none=True))
|
|
100
|
+
messages.extend(tool_messages)
|
|
101
|
+
reply = client.chat.completions.create(model="local", messages=messages, tools=datacircle_tools())
|
|
102
|
+
|
|
103
|
+
print(reply.choices[0].message.content)
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
## Call a tool yourself
|
|
107
|
+
|
|
108
|
+
You can call each tool without a model. You get the JSON text of the tool's answer:
|
|
109
|
+
|
|
110
|
+
```python
|
|
111
|
+
import json
|
|
112
|
+
|
|
113
|
+
from llama_cpp_datacircle import run
|
|
114
|
+
|
|
115
|
+
answer = json.loads(run("datacircle_best_plans", {"slug": "email-finder", "limit": 3}))
|
|
116
|
+
print(answer["plans"])
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
## What the model reads
|
|
120
|
+
|
|
121
|
+
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.
|
|
122
|
+
|
|
123
|
+
You can give a provider's name in place of a slug. The tool turns `Bright Data` into `bright-data`.
|
|
124
|
+
|
|
125
|
+
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.
|
|
126
|
+
|
|
127
|
+
## Network
|
|
128
|
+
|
|
129
|
+
Your model runs on your machine. 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.
|
|
130
|
+
|
|
131
|
+
## Links
|
|
132
|
+
|
|
133
|
+
- Datacircle: https://datacircle.dev
|
|
134
|
+
- The API: https://datacircle.dev/api
|
|
135
|
+
- The API's spec: https://api.datacircle.dev/v1/openapi.json
|
|
136
|
+
- Every field of a plan: https://datacircle.dev/fields
|
|
137
|
+
|
|
138
|
+
MIT license.
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "llama-cpp-python-datacircle"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "llama-cpp-python tools for the Datacircle API: find the best GTM APIs"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.9"
|
|
12
|
+
# The tools are OpenAI-format definitions and the run of their calls: they never import llama_cpp, so any version takes them.
|
|
13
|
+
dependencies = []
|
|
14
|
+
keywords = ["llama-cpp-python", "llama.cpp", "gguf", "local-llm", "tools", "function-calling", "tool-calling", "gtm", "api",
|
|
15
|
+
"api-pricing", "b2b-data", "datacircle"]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Operating System :: OS Independent",
|
|
19
|
+
"Topic :: Software Development :: Libraries",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
[project.urls]
|
|
23
|
+
Homepage = "https://datacircle.dev"
|
|
24
|
+
Documentation = "https://api.datacircle.dev/v1/openapi.json"
|
|
25
|
+
Repository = "https://github.com/waynehamadi/llama-cpp-python-datacircle"
|
|
26
|
+
|
|
27
|
+
[dependency-groups]
|
|
28
|
+
test = ["pytest>=8"]
|
|
29
|
+
|
|
30
|
+
[tool.hatch.build.targets.wheel]
|
|
31
|
+
packages = ["src/llama_cpp_datacircle"]
|
|
32
|
+
|
|
33
|
+
[tool.hatch.build.targets.sdist]
|
|
34
|
+
include = ["src", "tests", "README.md", "LICENSE", "pyproject.toml"]
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""Tools for llama-cpp-python on Datacircle's open API (https://api.datacircle.dev/v1): find the best GTM APIs, no key."""
|
|
2
|
+
|
|
3
|
+
from llama_cpp_datacircle._api import BASE_URL, DatacircleError
|
|
4
|
+
from llama_cpp_datacircle.tools import TOOL_NAMES, call, call_all, datacircle_tools, run, tool_calls
|
|
5
|
+
|
|
6
|
+
__version__ = "0.1.0"
|
|
7
|
+
__all__ = ["BASE_URL", "DatacircleError", "TOOL_NAMES", "call", "call_all", "datacircle_tools", "run", "tool_calls"]
|
|
@@ -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 = "llama-cpp-python-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: a tool gives the
|
|
25
|
+
model its words as its JSON text, {"error": ...}. status is the API's HTTP status, None when it gave none;
|
|
26
|
+
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
|
|
File without changes
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
"""Tools for llama-cpp-python on Datacircle's open API, https://api.datacircle.dev/v1: no key, no account.
|
|
2
|
+
|
|
3
|
+
The tools are OpenAI-format definitions, for Llama.create_chat_completion(tools=...) and llama-cpp-python's OpenAI-compatible
|
|
4
|
+
server. The app runs the calls the model returns: call() and call_all(). A tool makes one HTTPS GET and gives the model
|
|
5
|
+
the API's answer as JSON text. A refusal (an unknown slug, an argument out of range, the API out of reach) is the JSON text
|
|
6
|
+
{"error": the API's words}, so the model can call again and the chat goes on.
|
|
7
|
+
|
|
8
|
+
llama-cpp-python gives a reply's calls as its tool_calls when its chat format reads them (chatml-function-calling,
|
|
9
|
+
functionary, a tool named in tool_choice). With the model's own chat template, the model writes them in its text, and
|
|
10
|
+
tool_calls() reads them there: <tool_call> blocks (Qwen 2.5 and 3) or a reply that is calls' JSON (Llama 3.2). A small
|
|
11
|
+
local model holds to a schema only under a grammar, so each tool checks its arguments before any call.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import copy
|
|
15
|
+
import hashlib
|
|
16
|
+
import json
|
|
17
|
+
import re
|
|
18
|
+
import urllib.parse
|
|
19
|
+
from typing import Any, Dict, List, Mapping, Optional, Sequence
|
|
20
|
+
|
|
21
|
+
from llama_cpp_datacircle import _api
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _text(answer: Any) -> str:
|
|
25
|
+
return json.dumps(answer, ensure_ascii=False)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _best(plans: Any) -> Optional[Dict[str, Any]]:
|
|
29
|
+
"""A provider's best plan on an API: its lowest rank, a plan with no score having none."""
|
|
30
|
+
ranked = sorted(plans, key=lambda plan: plan.get("rank") if isinstance(plan.get("rank"), (int, float)) else float("inf"))
|
|
31
|
+
return _api.brief(ranked[0], ["plan", "score", "perThousand", "page"]) if ranked else None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _list_apis(query: Any = None, limit: Any = None) -> Dict[str, Any]:
|
|
35
|
+
count = _api.whole("limit", limit, 1, 200) or 20
|
|
36
|
+
apis = _api.get("/apis")
|
|
37
|
+
words = [word for word in str(query or "").lower().replace("-", " ").split() if word]
|
|
38
|
+
held = []
|
|
39
|
+
for index, api in enumerate(apis):
|
|
40
|
+
name = f"{api.get('api', '')} {str(api.get('slug', '')).replace('-', ' ')}".lower()
|
|
41
|
+
matched = sum(word in name for word in words)
|
|
42
|
+
if matched or not words:
|
|
43
|
+
held.append((-matched, index, api))
|
|
44
|
+
found = [_api.brief(api, _api.API_KEYS) for _, _, api in sorted(held, key=lambda h: h[:2])]
|
|
45
|
+
return {"total": len(found), "apis": found[:count]}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _best_plans(slug: Any = None, limit: Any = None) -> Dict[str, Any]:
|
|
49
|
+
made = _api.slug(slug)
|
|
50
|
+
if not made:
|
|
51
|
+
raise _api.DatacircleError("Give an API's slug, like 'email-finder': datacircle_list_apis gives every slug")
|
|
52
|
+
answer = _api.get(f"/apis/{urllib.parse.quote(made)}/best", {"limit": _api.whole("limit", limit, 1, 50)})
|
|
53
|
+
return {**answer, "plans": [_api.brief(plan) for plan in answer.get("plans") or []]}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _search_plans(api: Any = None, query: Any = None, sort: Any = None, limit: Any = None, offset: Any = None) -> Dict[str, Any]:
|
|
57
|
+
order = str(sort).strip().lower() if sort not in (None, "") else None
|
|
58
|
+
if order is not None and order not in ("score", "provider", "price"):
|
|
59
|
+
raise _api.DatacircleError(f"sort must be score, provider or price, not {sort!r}")
|
|
60
|
+
params = {"api": api, "query": query, "sort": order, "limit": _api.whole("limit", limit, 1, 50),
|
|
61
|
+
"offset": _api.whole("offset", offset, 0)}
|
|
62
|
+
answer = _api.get("/plans", params)
|
|
63
|
+
return {**answer, "plans": [_api.brief(plan) for plan in answer.get("plans") or []]}
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _provider(slug: Any = None) -> Dict[str, Any]:
|
|
67
|
+
made = _api.slug(slug)
|
|
68
|
+
if not made:
|
|
69
|
+
raise _api.DatacircleError("Give a provider's slug or name, like 'bright-data' or 'Bright Data'")
|
|
70
|
+
answer = _api.get(f"/providers/{urllib.parse.quote(made)}")
|
|
71
|
+
apis = [{**_api.brief(entry, ["api", "slug", "rank", "bestPage"]), "plans": len(entry.get("plans") or []),
|
|
72
|
+
"best": _best(entry.get("plans") or [])} for entry in answer.get("apis") or []]
|
|
73
|
+
return {**answer, "apis": apis}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
_PRICE = "perThousand is a plan's price of 1,000 items in dollars, pay the plan's whole price in its currency."
|
|
77
|
+
_LIMIT = {"type": "integer", "minimum": 1, "maximum": 50, "description": "How many plans to give, 1 to 50. 10 when left out."}
|
|
78
|
+
|
|
79
|
+
# Each tool: what the model reads of it, and the function that answers it. A chat template shows the model each schema as
|
|
80
|
+
# JSON, and llama-cpp-python's grammars read them: type, description, enum, minimum, maximum, required.
|
|
81
|
+
_TOOLS: Dict[str, Dict[str, Any]] = {
|
|
82
|
+
"datacircle_list_apis": {
|
|
83
|
+
"run": _list_apis,
|
|
84
|
+
"description": "Lists the GTM APIs on Datacircle's sheet (https://datacircle.dev), with each API's slug, how many plans "
|
|
85
|
+
"and providers it has and its best plan. Call it to find an API's slug when you don't know it. Gives "
|
|
86
|
+
"total, the APIs found, and apis, up to limit of them.",
|
|
87
|
+
"parameters": {"type": "object", "properties": {
|
|
88
|
+
"query": {"type": "string", "description": "Words of the API's name or slug, like 'email' or 'linkedin profile'. "
|
|
89
|
+
"The APIs that hold the most of them come first, in the sheet's order "
|
|
90
|
+
"when left out."},
|
|
91
|
+
"limit": {"type": "integer", "minimum": 1, "maximum": 200,
|
|
92
|
+
"description": "How many APIs to give, 1 to 200. 20 when left out, of about 170."}}},
|
|
93
|
+
},
|
|
94
|
+
"datacircle_best_plans": {
|
|
95
|
+
"run": _best_plans,
|
|
96
|
+
"description": "Gives an API's plans best first by their score out of 100 on Datacircle's benchmark "
|
|
97
|
+
"(https://datacircle.dev), each with its rank, provider, plan, $ per 1,000 calls and its page: the "
|
|
98
|
+
"best providers of an API. " + _PRICE,
|
|
99
|
+
"parameters": {"type": "object", "properties": {
|
|
100
|
+
"slug": {"type": "string", "description": "The API's slug, like 'email-finder' or 'linkedin-profile', as "
|
|
101
|
+
"datacircle_list_apis gives it."},
|
|
102
|
+
"limit": _LIMIT}, "required": ["slug"]},
|
|
103
|
+
},
|
|
104
|
+
"datacircle_search_plans": {
|
|
105
|
+
"run": _search_plans,
|
|
106
|
+
"description": "Searches every plan on Datacircle's sheet (https://datacircle.dev), or one API's, by provider or plan "
|
|
107
|
+
"name, sorted by score, provider or price. Gives total, offset and up to limit plans. " + _PRICE,
|
|
108
|
+
"parameters": {"type": "object", "properties": {
|
|
109
|
+
"api": {"type": "string", "description": "Only this API's plans, by its name or slug, like 'email-finder'. A "
|
|
110
|
+
"provider's name goes in query, never here. Every API when left out."},
|
|
111
|
+
"query": {"type": "string", "description": "Words that must all appear in the provider's or plan's name, like "
|
|
112
|
+
"'bright data'."},
|
|
113
|
+
"sort": {"type": "string", "enum": ["score", "provider", "price"],
|
|
114
|
+
"description": "score (best first, the default), provider (A to Z) or price ($ per 1,000, lowest first)."},
|
|
115
|
+
"limit": _LIMIT,
|
|
116
|
+
"offset": {"type": "integer", "minimum": 0, "description": "How many found plans to skip first. 0 when left out."}}},
|
|
117
|
+
},
|
|
118
|
+
"datacircle_provider": {
|
|
119
|
+
"run": _provider,
|
|
120
|
+
"description": "Gives each API one provider sells and its rank on each on Datacircle's benchmark "
|
|
121
|
+
"(https://datacircle.dev), with its best plan there.",
|
|
122
|
+
"parameters": {"type": "object", "properties": {
|
|
123
|
+
"slug": {"type": "string", "description": "The provider's slug, like 'bright-data', or its name, like 'Bright "
|
|
124
|
+
"Data', which is made a slug."}}, "required": ["slug"]},
|
|
125
|
+
},
|
|
126
|
+
}
|
|
127
|
+
TOOL_NAMES = list(_TOOLS)
|
|
128
|
+
|
|
129
|
+
def _names(tool_names: Optional[Sequence[str]]) -> List[str]:
|
|
130
|
+
if isinstance(tool_names, str):
|
|
131
|
+
raise TypeError("tool_names is a list of names, like ['datacircle_best_plans']")
|
|
132
|
+
for name in tool_names or []:
|
|
133
|
+
if name not in _TOOLS:
|
|
134
|
+
raise ValueError(f"Datacircle has no tool {name!r}: its tools are {', '.join(TOOL_NAMES)}")
|
|
135
|
+
return TOOL_NAMES if tool_names is None else list(tool_names)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def datacircle_tools(tool_names: Optional[Sequence[str]] = None) -> List[Dict[str, Any]]:
|
|
139
|
+
"""The tools, for llm.create_chat_completion(messages, tools=datacircle_tools()) or beside one's own:
|
|
140
|
+
tools=[*datacircle_tools(), my_tool]. tool_names keeps some of them only, in their order here; all four when left out.
|
|
141
|
+
Each is a new dict, so an app may change its copy."""
|
|
142
|
+
return [{"type": "function", "function": {"name": name, "description": _TOOLS[name]["description"],
|
|
143
|
+
"parameters": copy.deepcopy(_TOOLS[name]["parameters"])}}
|
|
144
|
+
for name in _names(tool_names)]
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def run(name: str, arguments: Any = None) -> str:
|
|
148
|
+
"""What a tool gives the model for these arguments, as JSON text: the API's answer, or {"error": its words}.
|
|
149
|
+
arguments is a mapping or its JSON text; the ones the tool doesn't take are left out."""
|
|
150
|
+
if name not in _TOOLS:
|
|
151
|
+
raise ValueError(f"Datacircle has no tool {name!r}: its tools are {', '.join(TOOL_NAMES)}")
|
|
152
|
+
if isinstance(arguments, bytes):
|
|
153
|
+
arguments = arguments.decode("utf-8", "replace")
|
|
154
|
+
if isinstance(arguments, str):
|
|
155
|
+
try:
|
|
156
|
+
arguments = json.loads(arguments) if arguments.strip() else {}
|
|
157
|
+
except ValueError:
|
|
158
|
+
return _text({"error": f"the arguments are no JSON object: {arguments[:200]!r}"})
|
|
159
|
+
if arguments is not None and not isinstance(arguments, Mapping):
|
|
160
|
+
return _text({"error": f"the arguments are no JSON object: {str(arguments)[:200]!r}"})
|
|
161
|
+
given = dict(arguments or {})
|
|
162
|
+
taken = _TOOLS[name]["parameters"]["properties"]
|
|
163
|
+
try:
|
|
164
|
+
return _text(_TOOLS[name]["run"](**{key: given.get(key) for key in taken}))
|
|
165
|
+
except _api.DatacircleError as error:
|
|
166
|
+
return _text({"error": str(error)})
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _field(item: Any, key: str) -> Any:
|
|
170
|
+
return item.get(key) if isinstance(item, Mapping) else getattr(item, key, None)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _message(reply: Any) -> Any:
|
|
174
|
+
"""A reply's message: create_chat_completion's response (or the OpenAI client's) gives its first choice's."""
|
|
175
|
+
choices = _field(reply, "choices")
|
|
176
|
+
if choices:
|
|
177
|
+
return _field(choices[0], "message")
|
|
178
|
+
return reply
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
_THINKING = re.compile(r"<think>.*?(?:</think>|$)", re.S)
|
|
182
|
+
_BLOCK = re.compile(r"<tool_call>\s*(.*?)\s*(?:</tool_call>|$)", re.S)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _made(index: int, text: str, made: Any) -> Optional[Dict[str, Any]]:
|
|
186
|
+
"""A call the model wrote, {"name": ..., "arguments" or "parameters": {...}}, as a tool call of OpenAI's shape. Its id
|
|
187
|
+
is the same each time the same reply is read, so the ids of tool_calls() and call_all() agree."""
|
|
188
|
+
if not isinstance(made, Mapping) or not isinstance(made.get("name"), str) or \
|
|
189
|
+
set(made) - {"name", "arguments", "parameters", "type"}:
|
|
190
|
+
return None
|
|
191
|
+
given = made.get("arguments", made.get("parameters"))
|
|
192
|
+
arguments = given if isinstance(given, str) else json.dumps({} if given is None else given, ensure_ascii=False)
|
|
193
|
+
tag = hashlib.sha1(f"{index}\n{text}".encode("utf-8")).hexdigest()[:12]
|
|
194
|
+
return {"id": f"call_{tag}", "type": "function", "function": {"name": made["name"], "arguments": arguments}}
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _json(text: str) -> Any:
|
|
198
|
+
try:
|
|
199
|
+
return json.loads(text)
|
|
200
|
+
except ValueError:
|
|
201
|
+
return None
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _joined(text: str) -> Optional[List[Any]]:
|
|
205
|
+
"""JSON values joined by ';', as Llama 3.2 writes calls side by side; None when the text is anything else."""
|
|
206
|
+
decoder, at, items = json.JSONDecoder(), 0, []
|
|
207
|
+
while True:
|
|
208
|
+
try:
|
|
209
|
+
item, at = decoder.raw_decode(text, at)
|
|
210
|
+
except ValueError:
|
|
211
|
+
return None
|
|
212
|
+
items.append(item)
|
|
213
|
+
rest = text[at:].lstrip()
|
|
214
|
+
if not rest:
|
|
215
|
+
return items
|
|
216
|
+
if not rest.startswith(";"):
|
|
217
|
+
return None
|
|
218
|
+
after = rest[1:].lstrip()
|
|
219
|
+
if not after:
|
|
220
|
+
return items
|
|
221
|
+
at = len(text) - len(after)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _written(text: str) -> List[Dict[str, Any]]:
|
|
225
|
+
"""The calls a model wrote in its text: <tool_call> blocks, as Qwen writes them, a block that won't read left out;
|
|
226
|
+
else a text that is one call's JSON, a list of them or calls joined by ';', as Llama 3.2 writes them, after
|
|
227
|
+
<|python_tag|> or alone."""
|
|
228
|
+
plain = _THINKING.sub("", text)
|
|
229
|
+
blocks = [block for block in _BLOCK.findall(plain) if block]
|
|
230
|
+
if blocks:
|
|
231
|
+
wrote = [_json(block) for block in blocks]
|
|
232
|
+
else:
|
|
233
|
+
whole = plain.strip()
|
|
234
|
+
whole = whole[len("<|python_tag|>"):].lstrip() if whole.startswith("<|python_tag|>") else whole
|
|
235
|
+
parsed = _json(whole) if whole.startswith(("{", "[")) else None
|
|
236
|
+
wrote = parsed if isinstance(parsed, list) else [parsed] if parsed is not None else \
|
|
237
|
+
(_joined(whole) if whole.startswith("{") else None) or [None]
|
|
238
|
+
found = []
|
|
239
|
+
for item in wrote:
|
|
240
|
+
made = _made(len(found), text, item)
|
|
241
|
+
if made is None and not blocks:
|
|
242
|
+
return [] # a reply that is JSON but no call: an answer
|
|
243
|
+
if made is not None:
|
|
244
|
+
found.append(made)
|
|
245
|
+
return found
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def tool_calls(reply: Any) -> List[Any]:
|
|
249
|
+
"""Every tool call in a reply (create_chat_completion's response or its message, the OpenAI client's, or a dict of
|
|
250
|
+
their shape), the app's own tools' too: its tool_calls when llama-cpp-python read them, else the calls the model
|
|
251
|
+
wrote in its content, each a dict of OpenAI's shape with an id of its own."""
|
|
252
|
+
if isinstance(reply, (list, tuple)):
|
|
253
|
+
return list(reply)
|
|
254
|
+
message = _message(reply)
|
|
255
|
+
if message is None:
|
|
256
|
+
return []
|
|
257
|
+
native = _field(message, "tool_calls")
|
|
258
|
+
if native:
|
|
259
|
+
return list(native)
|
|
260
|
+
content = _field(message, "content")
|
|
261
|
+
return _written(content) if isinstance(content, str) else []
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _named(tool_call: Any) -> Optional[str]:
|
|
265
|
+
"""The tool's name in a tool call: one of ours, or None."""
|
|
266
|
+
name = _field(_field(tool_call, "function"), "name")
|
|
267
|
+
return name if name in _TOOLS else None
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def call(tool_call: Any) -> Optional[Dict[str, str]]:
|
|
271
|
+
"""The tool message for one tool call (one of tool_calls(reply), a dict of OpenAI's shape or the OpenAI client's
|
|
272
|
+
object), to append to the messages: {"role": "tool", "tool_call_id": its id, "content": the JSON text}. None when
|
|
273
|
+
the call is for a tool that is not one of these four, so the app runs its own."""
|
|
274
|
+
name = _named(tool_call)
|
|
275
|
+
if name is None:
|
|
276
|
+
return None
|
|
277
|
+
return {"role": "tool", "tool_call_id": _field(tool_call, "id"),
|
|
278
|
+
"content": run(name, _field(_field(tool_call, "function"), "arguments"))}
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def call_all(reply: Any) -> List[Dict[str, str]]:
|
|
282
|
+
"""The tool messages for the calls of these four tools in a reply (as tool_calls() reads it, or a list of tool
|
|
283
|
+
calls), in their order. Calls of other tools are left out, for the app to run."""
|
|
284
|
+
return [message for message in (call(tool_call) for tool_call in tool_calls(reply)) if message is not None]
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
__all__: List[str] = ["TOOL_NAMES", "call", "call_all", "datacircle_tools", "run", "tool_calls"]
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""A stand-in for Datacircle's API on 127.0.0.1: every call's answer, a refusal, a 429 and a 503."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import threading
|
|
6
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
7
|
+
from urllib.parse import parse_qs, urlparse
|
|
8
|
+
|
|
9
|
+
import pytest
|
|
10
|
+
|
|
11
|
+
os.environ["NO_PROXY"] = os.environ["no_proxy"] = "127.0.0.1,localhost"
|
|
12
|
+
|
|
13
|
+
from llama_cpp_datacircle import _api # noqa: E402
|
|
14
|
+
|
|
15
|
+
PLAN = {"api": "Employee email", "rank": 1, "provider": "Hunter", "plan": "Starter", "score": 80.1, "perThousand": 4.9,
|
|
16
|
+
"page": "https://datacircle.dev/x", "terms": "long", "aggregators": ["a"]}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class State:
|
|
20
|
+
def __init__(self):
|
|
21
|
+
self.seen, self.busy = [], []
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _send(handler, status, body, headers=None):
|
|
25
|
+
data = json.dumps(body).encode()
|
|
26
|
+
handler.send_response(status)
|
|
27
|
+
for key, value in {"Content-Type": "application/json", "Content-Length": str(len(data)), **(headers or {})}.items():
|
|
28
|
+
handler.send_header(key, value)
|
|
29
|
+
handler.end_headers()
|
|
30
|
+
handler.wfile.write(data)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _handler(state):
|
|
34
|
+
class Handler(BaseHTTPRequestHandler):
|
|
35
|
+
def log_message(self, *args):
|
|
36
|
+
pass
|
|
37
|
+
|
|
38
|
+
def do_GET(self):
|
|
39
|
+
url = urlparse(self.path)
|
|
40
|
+
query = {key: values[0] for key, values in parse_qs(url.query).items()}
|
|
41
|
+
state.seen.append((url.path, query, self.headers.get("User-Agent")))
|
|
42
|
+
headers = {}
|
|
43
|
+
if url.path == "/v1/plans" and query.get("query") == "busy" and not state.busy:
|
|
44
|
+
state.busy.append(1)
|
|
45
|
+
status, body, headers = 429, {"error": "slow down"}, {"Retry-After": "1"}
|
|
46
|
+
elif url.path == "/v1/plans" and query.get("query") == "always-busy":
|
|
47
|
+
status, body, headers = 429, {"error": "slow down"}, {"Retry-After": "1"}
|
|
48
|
+
elif url.path == "/v1/apis":
|
|
49
|
+
status, body = 200, [{"api": "Employee email", "slug": "email-finder", "plans": 9, "providers": 3, "extra": 1},
|
|
50
|
+
{"api": "Employee profile", "slug": "linkedin-profile", "plans": 4, "providers": 2}]
|
|
51
|
+
elif url.path == "/v1/apis/email-finder/best":
|
|
52
|
+
status, body = 200, {"api": "Employee email", "slug": "email-finder", "total": 1, "plans": [PLAN]}
|
|
53
|
+
elif url.path.startswith("/v1/apis/"):
|
|
54
|
+
status, body = 404, {"error": "no API has the slug nope", "slugs": ["email-finder", "linkedin-profile"]}
|
|
55
|
+
elif url.path == "/v1/plans" and query.get("query") == "down":
|
|
56
|
+
status, body = 503, {"error": "down for a minute"}
|
|
57
|
+
elif url.path == "/v1/plans":
|
|
58
|
+
status, body = 200, {"total": 1, "offset": 0, "plans": [PLAN]}
|
|
59
|
+
elif url.path == "/v1/providers/bright-data":
|
|
60
|
+
status, body = 200, {"provider": "Bright Data", "slug": "bright-data",
|
|
61
|
+
"apis": [{"api": "Employee email", "slug": "email-finder", "rank": 7, "bestPage": "b",
|
|
62
|
+
"plans": [{**PLAN, "rank": 9}, {**PLAN, "rank": 7, "plan": "Pro"}]}]}
|
|
63
|
+
else:
|
|
64
|
+
status, body = 404, {"error": "no provider has the slug nope"}
|
|
65
|
+
_send(self, status, body, headers)
|
|
66
|
+
return Handler
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@pytest.fixture()
|
|
70
|
+
def stub(monkeypatch):
|
|
71
|
+
state = State()
|
|
72
|
+
server = ThreadingHTTPServer(("127.0.0.1", 0), _handler(state))
|
|
73
|
+
threading.Thread(target=server.serve_forever, daemon=True).start()
|
|
74
|
+
state.url = f"http://127.0.0.1:{server.server_address[1]}"
|
|
75
|
+
monkeypatch.setattr(_api, "BASE_URL", state.url + "/v1")
|
|
76
|
+
yield state
|
|
77
|
+
server.shutdown()
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Each tool on the live API, https://api.datacircle.dev/v1: run with DATACIRCLE_LIVE=1."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
|
|
8
|
+
from llama_cpp_datacircle import _api, call, call_all, run
|
|
9
|
+
|
|
10
|
+
pytestmark = pytest.mark.skipif(os.environ.get("DATACIRCLE_LIVE") != "1", reason="DATACIRCLE_LIVE=1 calls the live API")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def test_live(monkeypatch):
|
|
14
|
+
monkeypatch.setattr(_api, "BASE_URL", "https://api.datacircle.dev/v1")
|
|
15
|
+
apis = json.loads(run("datacircle_list_apis", {"query": "email finder", "limit": 3}))
|
|
16
|
+
assert apis["total"] >= 1 and apis["apis"][0]["slug"] and len(apis["apis"]) <= 3
|
|
17
|
+
best = json.loads(run("datacircle_best_plans", {"slug": "email-finder", "limit": 3}))
|
|
18
|
+
assert 1 <= len(best["plans"]) <= 3 and all(plan["provider"] and plan.get("page") for plan in best["plans"])
|
|
19
|
+
plans = json.loads(run("datacircle_search_plans", {"api": "email-finder", "sort": "price", "limit": 2}))
|
|
20
|
+
assert plans["total"] >= 1 and len(plans["plans"]) <= 2
|
|
21
|
+
slug = _api.slug(best["plans"][0]["provider"])
|
|
22
|
+
provider = json.loads(run("datacircle_provider", {"slug": best["plans"][0]["provider"]}))
|
|
23
|
+
assert provider["slug"] == slug and provider["apis"] and "plans" in provider["apis"][0]
|
|
24
|
+
refused = json.loads(run("datacircle_best_plans", {"slug": "no-such-api"}))
|
|
25
|
+
assert "answered 404" in refused["error"] and "email-finder" in refused["error"]
|
|
26
|
+
message = call({"id": "c", "function": {"name": "datacircle_provider", "arguments": json.dumps({"slug": slug})}})
|
|
27
|
+
assert json.loads(message["content"])["slug"] == slug
|
|
28
|
+
written = '<tool_call>\n{"name": "datacircle_list_apis", "arguments": {}}\n</tool_call>'
|
|
29
|
+
assert json.loads(call_all({"role": "assistant", "content": written})[0]["content"])["total"] > 100
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""The tools in Llama.create_chat_completion on a real GGUF model, on the stand-in API (conftest.py): run with
|
|
2
|
+
LLAMA_CPP_MODEL=<a .gguf whose chat template takes tools, like Qwen 2.5 or 3> and llama-cpp-python installed.
|
|
3
|
+
LLAMA_CPP_THREADS sets its threads, 4 when left out."""
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
|
|
8
|
+
import pytest
|
|
9
|
+
|
|
10
|
+
from llama_cpp_datacircle import call, call_all, datacircle_tools, tool_calls
|
|
11
|
+
|
|
12
|
+
MODEL = os.environ.get("LLAMA_CPP_MODEL")
|
|
13
|
+
pytestmark = pytest.mark.skipif(not MODEL, reason="LLAMA_CPP_MODEL=<model.gguf> runs a real model")
|
|
14
|
+
QUESTION = "Use the datacircle_best_plans tool with the slug email-finder: which provider is ranked first?"
|
|
15
|
+
ADD = {"type": "function", "function": {"name": "add_two_numbers", "description": "Adds two whole numbers.", "parameters": {
|
|
16
|
+
"type": "object", "properties": {"a": {"type": "integer"}, "b": {"type": "integer"}}, "required": ["a", "b"]}}}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def llama(**options):
|
|
20
|
+
from llama_cpp import Llama
|
|
21
|
+
return Llama(model_path=MODEL, n_ctx=4096, n_threads=int(os.environ.get("LLAMA_CPP_THREADS", "4")), seed=1,
|
|
22
|
+
verbose=False, **options)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@pytest.fixture(scope="module")
|
|
26
|
+
def own():
|
|
27
|
+
return llama()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def test_own_chat_template(stub, own):
|
|
31
|
+
"""The model's own template: it writes its calls in its text, tool_calls() reads them, its template shows it the
|
|
32
|
+
answers, and it answers from them."""
|
|
33
|
+
messages = [{"role": "user", "content": QUESTION}]
|
|
34
|
+
tools = [*datacircle_tools(), ADD]
|
|
35
|
+
reply = own.create_chat_completion(messages=messages, tools=tools, temperature=0, max_tokens=512)
|
|
36
|
+
calls = tool_calls(reply)
|
|
37
|
+
assert any(c["function"]["name"] == "datacircle_best_plans" for c in calls), reply["choices"][0]["message"]
|
|
38
|
+
messages.append(reply["choices"][0]["message"])
|
|
39
|
+
for tool_call in calls:
|
|
40
|
+
messages.append(call(tool_call) or {"role": "tool", "tool_call_id": tool_call["id"], "content": "3"})
|
|
41
|
+
assert any("Hunter" in m["content"] for m in messages if m["role"] == "tool")
|
|
42
|
+
answer = own.create_chat_completion(messages=messages, tools=tools, temperature=0, max_tokens=512)
|
|
43
|
+
text = answer["choices"][0]["message"]["content"]
|
|
44
|
+
assert "Hunter" in text and not tool_calls(answer), text
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def test_tool_choice(stub, own):
|
|
48
|
+
"""A tool named in tool_choice: llama-cpp-python's grammar holds the model to its schema and gives its tool_calls."""
|
|
49
|
+
choice = {"type": "function", "function": {"name": "datacircle_best_plans"}}
|
|
50
|
+
reply = own.create_chat_completion(messages=[{"role": "user", "content": QUESTION}], tools=datacircle_tools(),
|
|
51
|
+
tool_choice=choice, temperature=0, max_tokens=256)
|
|
52
|
+
made = call_all(reply)
|
|
53
|
+
assert reply["choices"][0]["message"]["tool_calls"] and len(made) == 1
|
|
54
|
+
assert json.loads(made[0]["content"]).get("plans") or "error" in json.loads(made[0]["content"])
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def test_chatml_function_calling(stub):
|
|
58
|
+
"""chat_format="chatml-function-calling": llama-cpp-python reads the calls into tool_calls, call_all() runs them."""
|
|
59
|
+
model = llama(chat_format="chatml-function-calling")
|
|
60
|
+
messages = [{"role": "system", "content": "You answer with the tools."}, {"role": "user", "content": QUESTION}]
|
|
61
|
+
reply = model.create_chat_completion(messages=messages, tools=datacircle_tools(), tool_choice="auto", temperature=0,
|
|
62
|
+
max_tokens=256)
|
|
63
|
+
native = reply["choices"][0]["message"].get("tool_calls") or []
|
|
64
|
+
assert [c["function"]["name"] for c in native][:1] == ["datacircle_best_plans"], reply["choices"][0]["message"]
|
|
65
|
+
made = call_all(reply)
|
|
66
|
+
assert made and made[0]["tool_call_id"] == native[0]["id"] and "Hunter" in made[0]["content"]
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""tool_calls() and call_all() on each shape of reply llama-cpp-python gives, on the stand-in API (conftest.py)."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from types import SimpleNamespace
|
|
5
|
+
|
|
6
|
+
from llama_cpp_datacircle import call, call_all, tool_calls
|
|
7
|
+
|
|
8
|
+
ARGS = '{"slug": "email-finder", "limit": 1}'
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def response(message):
|
|
12
|
+
"""create_chat_completion's response around a message."""
|
|
13
|
+
return {"id": "chatcmpl-1", "object": "chat.completion", "created": 1, "model": "m",
|
|
14
|
+
"choices": [{"index": 0, "message": message, "logprobs": None, "finish_reason": "stop"}]}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def test_native_tool_calls(stub):
|
|
18
|
+
# chatml-function-calling's shape: content None, the tool calls and a function_call for the first.
|
|
19
|
+
native = [{"id": "call__0_datacircle_best_plans_cmpl-1", "type": "function",
|
|
20
|
+
"function": {"name": "datacircle_best_plans", "arguments": ARGS}},
|
|
21
|
+
{"id": "call__1_add_cmpl-1", "type": "function", "function": {"name": "add", "arguments": "{}"}}]
|
|
22
|
+
message = {"role": "assistant", "content": None, "function_call": native[0]["function"], "tool_calls": native}
|
|
23
|
+
assert tool_calls(response(message)) == native == tool_calls(message)
|
|
24
|
+
made = call_all(response(message))
|
|
25
|
+
assert [m["tool_call_id"] for m in made] == ["call__0_datacircle_best_plans_cmpl-1"]
|
|
26
|
+
assert json.loads(made[0]["content"])["plans"][0]["provider"] == "Hunter"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def test_hermes_blocks(stub):
|
|
30
|
+
# Qwen 2.5 and 3: <tool_call> blocks in the text, a Qwen 3 thought before them.
|
|
31
|
+
text = ('<think>\nI could write <tool_call> here.\n</think>\n\n'
|
|
32
|
+
'<tool_call>\n{"name": "datacircle_best_plans", "arguments": {"slug": "email-finder", "limit": 1}}\n</tool_call>\n'
|
|
33
|
+
'<tool_call>\n{"name": "add", "arguments": {"a": 1, "b": 2}}\n</tool_call>\n'
|
|
34
|
+
'<tool_call>\n{"name": "datacircle_provider", "arguments": not json}\n</tool_call>')
|
|
35
|
+
message = {"role": "assistant", "content": text}
|
|
36
|
+
calls = tool_calls(response(message))
|
|
37
|
+
assert [(c["function"]["name"], json.loads(c["function"]["arguments"])) for c in calls] == [
|
|
38
|
+
("datacircle_best_plans", {"slug": "email-finder", "limit": 1}), ("add", {"a": 1, "b": 2})]
|
|
39
|
+
assert calls[0]["id"].startswith("call_") and calls[0]["id"] != calls[1]["id"]
|
|
40
|
+
assert tool_calls(message) == calls # the same ids each time
|
|
41
|
+
made = call_all(message)
|
|
42
|
+
assert [m["tool_call_id"] for m in made] == [calls[0]["id"]]
|
|
43
|
+
assert json.loads(made[0]["content"])["plans"][0]["provider"] == "Hunter"
|
|
44
|
+
# A block the model never closed, and arguments as JSON text.
|
|
45
|
+
open_block = '<tool_call>\n{"name": "datacircle_best_plans", "arguments": "{\\"slug\\": \\"email-finder\\"}"}'
|
|
46
|
+
assert json.loads(tool_calls({"content": open_block})[0]["function"]["arguments"]) == {"slug": "email-finder"}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def test_llama_json(stub):
|
|
50
|
+
# Llama 3.2: the reply is the call's JSON, with "parameters", after <|python_tag|> or alone.
|
|
51
|
+
for text in ['{"name": "datacircle_best_plans", "parameters": {"slug": "email-finder", "limit": 1}}',
|
|
52
|
+
'{"name": "datacircle_best_plans", "parameters": {"slug": "email-finder", "limit": "1"}}',
|
|
53
|
+
'<|python_tag|>{"type": "function", "name": "datacircle_best_plans", "parameters": ' + ARGS + '}',
|
|
54
|
+
' [{"name": "datacircle_best_plans", "parameters": ' + ARGS + '}] ']:
|
|
55
|
+
made = call_all({"role": "assistant", "content": text})
|
|
56
|
+
assert len(made) == 1 and json.loads(made[0]["content"])["plans"][0]["provider"] == "Hunter"
|
|
57
|
+
# Llama 3.2's calls side by side, joined by ';' (Llama-3.2-1B-Instruct beside an app's own tool, 2026-12-01).
|
|
58
|
+
text = ('{"name": "datacircle_best_plans", "parameters": {"slug": "email-finder", "limit": "20"}}; '
|
|
59
|
+
'{"name": "datacircle_provider", "parameters": {"slug": "bright-data"}};{"name": "add_two_numbers", "parameters": '
|
|
60
|
+
'{"a": "17", "b": "25"}};')
|
|
61
|
+
assert [c["function"]["name"] for c in tool_calls({"content": text})] == [
|
|
62
|
+
"datacircle_best_plans", "datacircle_provider", "add_two_numbers"]
|
|
63
|
+
made = call_all({"content": text})
|
|
64
|
+
assert len(made) == 2 and json.loads(made[0]["content"])["plans"][0]["provider"] == "Hunter"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def test_answers_are_no_calls():
|
|
68
|
+
for text in ["The best one is Hunter.", '{"name": "Hunter", "score": 80}', '{"name": "x", "arguments": {}, "other": 1}',
|
|
69
|
+
"[1, 2]", "", "{broken", '<tool_call>\n</tool_call>', '{"name": "a", "arguments": {}}; then more',
|
|
70
|
+
'{"name": "Hunter", "score": 80}; {"name": "Snov", "score": 70}']:
|
|
71
|
+
assert tool_calls({"role": "assistant", "content": text}) == [], text
|
|
72
|
+
assert tool_calls(None) == [] and tool_calls({"choices": []}) == [] and tool_calls({"content": None}) == []
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def test_openai_client_objects(stub):
|
|
76
|
+
# llama-cpp-python's server through the OpenAI client: objects, not dicts.
|
|
77
|
+
function = SimpleNamespace(name="datacircle_best_plans", arguments=ARGS)
|
|
78
|
+
native = SimpleNamespace(id="call_9", type="function", function=function)
|
|
79
|
+
reply = SimpleNamespace(choices=[SimpleNamespace(message=SimpleNamespace(content=None, tool_calls=[native]))])
|
|
80
|
+
assert [m["tool_call_id"] for m in call_all(reply)] == ["call_9"] and call(native)["tool_call_id"] == "call_9"
|
|
81
|
+
text = '<tool_call>\n{"name": "datacircle_best_plans", "arguments": ' + ARGS + '}\n</tool_call>'
|
|
82
|
+
written = SimpleNamespace(choices=[SimpleNamespace(message=SimpleNamespace(content=text, tool_calls=None))])
|
|
83
|
+
assert json.loads(call_all(written)[0]["content"])["plans"][0]["provider"] == "Hunter"
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""Offline tests of the tools alone, on the stand-in API (conftest.py): every call, its cut, every refusal."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
|
|
7
|
+
import llama_cpp_datacircle
|
|
8
|
+
from llama_cpp_datacircle import TOOL_NAMES, call, call_all, datacircle_tools, run
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def test_definitions():
|
|
12
|
+
tools = datacircle_tools()
|
|
13
|
+
assert [tool["function"]["name"] for tool in tools] == TOOL_NAMES
|
|
14
|
+
assert all(tool["type"] == "function" and tool["function"]["description"] for tool in tools)
|
|
15
|
+
assert tools[1]["function"]["parameters"]["required"] == ["slug"]
|
|
16
|
+
assert [tool["function"]["name"] for tool in datacircle_tools(["datacircle_provider"])] == ["datacircle_provider"]
|
|
17
|
+
tools[0]["function"]["parameters"]["properties"].clear() # a copy of its own: the next call is whole
|
|
18
|
+
assert datacircle_tools()[0]["function"]["parameters"]["properties"]
|
|
19
|
+
allowed = {"type", "description", "enum", "minimum", "maximum", "properties", "required"}
|
|
20
|
+
for tool in tools:
|
|
21
|
+
for spec in tool["function"]["parameters"]["properties"].values():
|
|
22
|
+
assert set(spec) <= allowed
|
|
23
|
+
with pytest.raises(ValueError, match="no tool 'nope'"):
|
|
24
|
+
datacircle_tools(["nope"])
|
|
25
|
+
with pytest.raises(TypeError):
|
|
26
|
+
datacircle_tools("datacircle_provider")
|
|
27
|
+
assert llama_cpp_datacircle.__version__ == "0.1.0"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def test_each_tool(stub):
|
|
31
|
+
apis = json.loads(run("datacircle_list_apis", {"query": "email"}))
|
|
32
|
+
assert apis == {"total": 1, "apis": [{"api": "Employee email", "slug": "email-finder", "plans": 9, "providers": 3}]}
|
|
33
|
+
assert json.loads(run("datacircle_list_apis", "{}"))["total"] == 2
|
|
34
|
+
best = json.loads(run("datacircle_best_plans", '{"slug": "Email Finder", "limit": "1"}'))
|
|
35
|
+
assert best["plans"] == [{"api": "Employee email", "rank": 1, "provider": "Hunter", "plan": "Starter", "score": 80.1,
|
|
36
|
+
"perThousand": 4.9, "page": "https://datacircle.dev/x"}]
|
|
37
|
+
assert stub.seen[-1][:2] == ("/v1/apis/email-finder/best", {"limit": "1"})
|
|
38
|
+
assert stub.seen[-1][2] == "llama-cpp-python-datacircle/0.1.0"
|
|
39
|
+
plans = json.loads(run("datacircle_search_plans", {"api": "email-finder", "sort": "Price", "limit": 5, "offset": 0}))
|
|
40
|
+
assert plans["total"] == 1
|
|
41
|
+
assert stub.seen[-1][1] == {"api": "email-finder", "sort": "price", "limit": "5", "offset": "0"}
|
|
42
|
+
provider = json.loads(run("datacircle_provider", {"slug": "Bright Data", "unknown": 1}))
|
|
43
|
+
assert provider["apis"][0]["best"]["plan"] == "Pro" and provider["apis"][0]["plans"] == 2
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def test_refusals(stub):
|
|
47
|
+
assert "the slugs: email-finder, linkedin-profile" in json.loads(run("datacircle_best_plans", {"slug": "nope"}))["error"]
|
|
48
|
+
assert "Give an API's slug" in json.loads(run("datacircle_best_plans", {}))["error"]
|
|
49
|
+
assert "limit must be from 1 to 50" in json.loads(run("datacircle_best_plans", {"slug": "x", "limit": 99}))["error"]
|
|
50
|
+
assert "whole number" in json.loads(run("datacircle_search_plans", {"limit": 2.5}))["error"]
|
|
51
|
+
assert "sort must be" in json.loads(run("datacircle_search_plans", {"sort": "cheap"}))["error"]
|
|
52
|
+
assert "answered 503: down for a minute" in json.loads(run("datacircle_search_plans", {"query": "down"}))["error"]
|
|
53
|
+
assert "no JSON object" in json.loads(run("datacircle_provider", "{not json"))["error"]
|
|
54
|
+
assert "no JSON object" in json.loads(run("datacircle_provider", "[1]"))["error"]
|
|
55
|
+
assert "no provider" in json.loads(run("datacircle_provider", {"slug": "nope"}))["error"]
|
|
56
|
+
with pytest.raises(ValueError):
|
|
57
|
+
run("nope", {})
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def test_one_wait_on_429(stub):
|
|
61
|
+
assert json.loads(run("datacircle_search_plans", {"query": "busy"}))["total"] == 1
|
|
62
|
+
assert "429 twice" in json.loads(run("datacircle_search_plans", {"query": "always-busy"}))["error"]
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def test_out_of_reach(monkeypatch):
|
|
66
|
+
monkeypatch.setattr(llama_cpp_datacircle._api, "BASE_URL", "http://127.0.0.1:9/v1")
|
|
67
|
+
assert "could not be reached" in json.loads(run("datacircle_list_apis"))["error"]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
CALLS = [{"id": "call_0", "type": "function", "function": {"name": "datacircle_best_plans",
|
|
71
|
+
"arguments": '{"slug": "email-finder", "limit": 1}'}},
|
|
72
|
+
{"id": "call_1", "type": "function", "function": {"name": "add_two_numbers", "arguments": '{"a": 1}'}}]
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def test_call(stub):
|
|
76
|
+
message = call(CALLS[0])
|
|
77
|
+
assert message["role"] == "tool" and message["tool_call_id"] == "call_0"
|
|
78
|
+
assert json.loads(message["content"])["plans"][0]["provider"] == "Hunter"
|
|
79
|
+
assert call(CALLS[1]) is None
|
|
80
|
+
assert [m["tool_call_id"] for m in call_all({"role": "assistant", "tool_calls": CALLS})] == ["call_0"]
|
|
81
|
+
assert call_all(CALLS) == call_all({"tool_calls": CALLS}) and call_all(None) == [] and call_all({}) == []
|