llama-cpp-python-datacircle 0.1.0__py3-none-any.whl

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.
@@ -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,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,8 @@
1
+ llama_cpp_datacircle/__init__.py,sha256=5PTD1P7Bv2ccT5YHZnk6CBRsHWFTVRhlljLs9BPAYU8,429
2
+ llama_cpp_datacircle/_api.py,sha256=3R1Ill-D6ULrEeF9-Yto1XvksuoKL7v_BPlLL7K4TRE,4877
3
+ llama_cpp_datacircle/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ llama_cpp_datacircle/tools.py,sha256=h6_k8iK7oLG1vhmBZoi9dAGHF8Ovpnv24tvdlbMATLU,15240
5
+ llama_cpp_python_datacircle-0.1.0.dist-info/METADATA,sha256=WeOuQCH34C7er9aL_zzdSpl5ijIrIyU7znKmM_RnTw4,7814
6
+ llama_cpp_python_datacircle-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
7
+ llama_cpp_python_datacircle-0.1.0.dist-info/licenses/LICENSE,sha256=dpgF7zGxeOd9IpQ9yUGa4a-cTj8fI6ulHnuilZEonCo,1067
8
+ llama_cpp_python_datacircle-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -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.