pipecat-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.
@@ -0,0 +1,4 @@
1
+ dist/
2
+ __pycache__/
3
+ *.pyc
4
+ .venv/
@@ -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,94 @@
1
+ Metadata-Version: 2.5
2
+ Name: pipecat-datacircle
3
+ Version: 0.1.0
4
+ Summary: Pipecat function 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/pipecat-datacircle
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: api,api-pricing,b2b-data,datacircle,function-calling,gtm,pipecat,pipecat-ai,tools,voice-agents
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Software Development :: Libraries
14
+ Requires-Python: >=3.11
15
+ Requires-Dist: pipecat-ai>=1.4.0
16
+ Description-Content-Type: text/markdown
17
+
18
+ # pipecat-datacircle
19
+
20
+ Find the best GTM APIs. We benchmark all the GTM APIs and we put the results on our website.
21
+
22
+ Our website: https://datacircle.dev
23
+
24
+ This package gives [Pipecat](https://github.com/pipecat-ai/pipecat) four function tools that call Datacircle's public API, https://api.datacircle.dev/v1. You need no key and no account.
25
+
26
+ | Tool | Gives | Call |
27
+ | --- | --- | --- |
28
+ | `datacircle_list_apis` | Every GTM API on Datacircle, with the API's slug, number of plans, number of providers and best plan | `GET /apis` |
29
+ | `datacircle_best_plans` | One API's plans, sorted by score out of 100, best first. Each plan comes with a rank and a price per 1,000 calls | `GET /apis/{slug}/best` |
30
+ | `datacircle_search_plans` | Plans that match a provider or plan name, on all APIs or on one API. You can sort them by score, provider or price | `GET /plans` |
31
+ | `datacircle_provider` | The APIs a provider sells, and the provider's rank on each API | `GET /providers/{slug}` |
32
+
33
+ ## Install
34
+
35
+ ```bash
36
+ pip install pipecat-datacircle
37
+ ```
38
+
39
+ The package needs Pipecat 1.4 or later (`pipecat-ai`) and Python 3.11 or later.
40
+
41
+ ## Give the tools to your bot
42
+
43
+ ```python
44
+ import os
45
+
46
+ from pipecat.processors.aggregators.llm_context import LLMContext
47
+ from pipecat.processors.aggregators.llm_response_universal import LLMContextAggregatorPair
48
+ from pipecat.services.openai.llm import OpenAILLMService
49
+ from pipecat_datacircle import datacircle_tools_schema
50
+
51
+ llm = OpenAILLMService(api_key=os.environ["OPENAI_API_KEY"])
52
+ context = LLMContext(
53
+ [{"role": "user", "content": "Which email finder API is best for under $5 per 1,000?"}],
54
+ tools=datacircle_tools_schema(),
55
+ )
56
+ user_aggregator, assistant_aggregator = LLMContextAggregatorPair(context)
57
+ ```
58
+
59
+ Put `user_aggregator`, `llm` and `assistant_aggregator` in your pipeline as usual. Each tool's schema carries its handler, so the LLM service runs the tools with no `register_function` call. Pipecat turns the schemas into each provider's tools, so its other LLM services take them the same way.
60
+
61
+ To add the tools beside your own, list them: `LLMContext(messages, tools=[my_tool, *datacircle_functions()])`.
62
+
63
+ To give fewer tools, list their names: `datacircle_tools_schema(["datacircle_best_plans"])`.
64
+
65
+ ## Call a tool yourself
66
+
67
+ `run` gives what the model gets:
68
+
69
+ ```python
70
+ from pipecat_datacircle import run
71
+
72
+ print(run("datacircle_best_plans", {"slug": "email-finder", "limit": 3}))
73
+ ```
74
+
75
+ ## Tool output for the model
76
+
77
+ Each result is our API's answer as a dict. Pipecat gives it to the model as JSON. 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.
78
+
79
+ You can give a provider's name in place of a slug. The tool turns `Bright Data` into `bright-data`.
80
+
81
+ If the model passes an unknown slug, the result is `{"error": ...}` with the API's error message. For an unknown API slug, the message lists every valid slug, and the model can call the tool again. The tool checks each number from the model before the API call. If a number is out of range, the tool skips the API call and the model gets an error message.
82
+
83
+ ## Network
84
+
85
+ Each tool call makes one HTTPS GET request to https://api.datacircle.dev/v1 and nothing else, in a thread, so the pipeline keeps running. The request holds only the tool's own arguments. The API takes up to 60 calls a minute from one IP address. When the API asks the tool to wait, the tool waits up to a minute. The tool waits once per call at most. All plans are in one file at https://datacircle.dev/datacircle.json.
86
+
87
+ ## Links
88
+
89
+ - Datacircle: https://datacircle.dev
90
+ - The API: https://datacircle.dev/api
91
+ - The API's spec: https://api.datacircle.dev/v1/openapi.json
92
+ - What each key means: https://datacircle.dev/fields
93
+
94
+ MIT license.
@@ -0,0 +1,77 @@
1
+ # pipecat-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 [Pipecat](https://github.com/pipecat-ai/pipecat) four function tools that call Datacircle's public API, https://api.datacircle.dev/v1. You need no key and no account.
8
+
9
+ | Tool | Gives | Call |
10
+ | --- | --- | --- |
11
+ | `datacircle_list_apis` | Every GTM API on Datacircle, with the API's slug, number of plans, number of providers and best plan | `GET /apis` |
12
+ | `datacircle_best_plans` | One API's plans, sorted by score out of 100, best first. Each plan comes with a rank and a price per 1,000 calls | `GET /apis/{slug}/best` |
13
+ | `datacircle_search_plans` | Plans that match a provider or plan name, on all APIs or on one API. You can sort them by score, provider or price | `GET /plans` |
14
+ | `datacircle_provider` | The APIs a provider sells, and the provider's rank on each API | `GET /providers/{slug}` |
15
+
16
+ ## Install
17
+
18
+ ```bash
19
+ pip install pipecat-datacircle
20
+ ```
21
+
22
+ The package needs Pipecat 1.4 or later (`pipecat-ai`) and Python 3.11 or later.
23
+
24
+ ## Give the tools to your bot
25
+
26
+ ```python
27
+ import os
28
+
29
+ from pipecat.processors.aggregators.llm_context import LLMContext
30
+ from pipecat.processors.aggregators.llm_response_universal import LLMContextAggregatorPair
31
+ from pipecat.services.openai.llm import OpenAILLMService
32
+ from pipecat_datacircle import datacircle_tools_schema
33
+
34
+ llm = OpenAILLMService(api_key=os.environ["OPENAI_API_KEY"])
35
+ context = LLMContext(
36
+ [{"role": "user", "content": "Which email finder API is best for under $5 per 1,000?"}],
37
+ tools=datacircle_tools_schema(),
38
+ )
39
+ user_aggregator, assistant_aggregator = LLMContextAggregatorPair(context)
40
+ ```
41
+
42
+ Put `user_aggregator`, `llm` and `assistant_aggregator` in your pipeline as usual. Each tool's schema carries its handler, so the LLM service runs the tools with no `register_function` call. Pipecat turns the schemas into each provider's tools, so its other LLM services take them the same way.
43
+
44
+ To add the tools beside your own, list them: `LLMContext(messages, tools=[my_tool, *datacircle_functions()])`.
45
+
46
+ To give fewer tools, list their names: `datacircle_tools_schema(["datacircle_best_plans"])`.
47
+
48
+ ## Call a tool yourself
49
+
50
+ `run` gives what the model gets:
51
+
52
+ ```python
53
+ from pipecat_datacircle import run
54
+
55
+ print(run("datacircle_best_plans", {"slug": "email-finder", "limit": 3}))
56
+ ```
57
+
58
+ ## Tool output for the model
59
+
60
+ Each result is our API's answer as a dict. Pipecat gives it to the model as JSON. 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.
61
+
62
+ You can give a provider's name in place of a slug. The tool turns `Bright Data` into `bright-data`.
63
+
64
+ If the model passes an unknown slug, the result is `{"error": ...}` with the API's error message. For an unknown API slug, the message lists every valid slug, and the model can call the tool again. The tool checks each number from the model before the API call. If a number is out of range, the tool skips the API call and the model gets an error message.
65
+
66
+ ## Network
67
+
68
+ Each tool call makes one HTTPS GET request to https://api.datacircle.dev/v1 and nothing else, in a thread, so the pipeline keeps running. The request holds only the tool's own arguments. The API takes up to 60 calls a minute from one IP address. When the API asks the tool to wait, the tool waits up to a minute. The tool waits once per call at most. All plans are in one file at https://datacircle.dev/datacircle.json.
69
+
70
+ ## Links
71
+
72
+ - Datacircle: https://datacircle.dev
73
+ - The API: https://datacircle.dev/api
74
+ - The API's spec: https://api.datacircle.dev/v1/openapi.json
75
+ - What each key means: https://datacircle.dev/fields
76
+
77
+ MIT license.
@@ -0,0 +1,32 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "pipecat-datacircle"
7
+ version = "0.1.0"
8
+ description = "Pipecat function tools for the Datacircle API: find the best GTM APIs"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.11"
12
+ dependencies = ["pipecat-ai>=1.4.0"]
13
+ keywords = ["pipecat", "pipecat-ai", "function-calling", "tools", "voice-agents", "gtm", "api", "api-pricing", "b2b-data", "datacircle"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Operating System :: OS Independent",
17
+ "Topic :: Software Development :: Libraries",
18
+ ]
19
+
20
+ [project.urls]
21
+ Homepage = "https://datacircle.dev"
22
+ Documentation = "https://api.datacircle.dev/v1/openapi.json"
23
+ Repository = "https://github.com/waynehamadi/pipecat-datacircle"
24
+
25
+ [dependency-groups]
26
+ test = ["pytest>=8"]
27
+
28
+ [tool.hatch.build.targets.wheel]
29
+ packages = ["src/pipecat_datacircle"]
30
+
31
+ [tool.hatch.build.targets.sdist]
32
+ include = ["src", "tests", "README.md", "LICENSE", "pyproject.toml"]
@@ -0,0 +1,19 @@
1
+ """Pipecat function tools for Datacircle's open API (https://api.datacircle.dev/v1): find the best GTM APIs, no key."""
2
+
3
+ from pipecat_datacircle._api import BASE_URL, DatacircleError
4
+ from pipecat_datacircle.functions import (
5
+ HANDLERS,
6
+ TOOL_NAMES,
7
+ best_plans,
8
+ datacircle_function,
9
+ datacircle_functions,
10
+ datacircle_tools_schema,
11
+ list_apis,
12
+ provider,
13
+ run,
14
+ search_plans,
15
+ )
16
+
17
+ __version__ = "0.1.0"
18
+ __all__ = ["BASE_URL", "DatacircleError", "HANDLERS", "TOOL_NAMES", "best_plans", "datacircle_function",
19
+ "datacircle_functions", "datacircle_tools_schema", "list_apis", "provider", "run", "search_plans"]
@@ -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 = "pipecat-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 function's
25
+ handler gives the model its words as the call's result, {"error": ...}. status is the API's HTTP status, None when
26
+ it gave none; retryable, whether the same call may be answered later (the API out of reach, busy or failing)."""
27
+
28
+ def __init__(self, message: str, status: Optional[int] = None, retryable: bool = False):
29
+ super().__init__(message)
30
+ self.status = status
31
+ self.retryable = retryable
32
+
33
+
34
+ def brief(item: Dict[str, Any], keys: List[str] = PLAN_KEYS) -> Dict[str, Any]:
35
+ return {key: item[key] for key in keys if item.get(key) is not None}
36
+
37
+
38
+ def slug(value: Any) -> str:
39
+ """The API's rule for a slug: the name in lowercase letters and digits, the rest a hyphen."""
40
+ plain = unicodedata.normalize("NFKD", str(value or "").strip().lower())
41
+ plain = "".join(char for char in plain if not unicodedata.combining(char))
42
+ return re.sub(r"[^a-z0-9]+", "-", plain).strip("-")
43
+
44
+
45
+ def whole(name: str, value: Any, low: int, high: Optional[int] = None) -> Optional[int]:
46
+ """A whole number from low to high, or None when left out: a plain call may send one as text."""
47
+ if value is None or value == "":
48
+ return None
49
+ try:
50
+ number = float(value)
51
+ except (TypeError, ValueError):
52
+ number = float("nan")
53
+ if isinstance(value, bool) or not math.isfinite(number) or number != int(number):
54
+ raise DatacircleError(f"{name} must be a whole number, not {value!r}")
55
+ if number < low or (high is not None and number > high):
56
+ raise DatacircleError(f"{name} must be from {low} to {high}, not {int(number)}" if high is not None
57
+ else f"{name} must be {low} or more, not {int(number)}")
58
+ return int(number)
59
+
60
+
61
+ def _words(body: bytes) -> str:
62
+ """A refusal's words: the API's error, with every slug when the slug was unknown."""
63
+ text = body.decode("utf-8", "replace")
64
+ try:
65
+ parsed = json.loads(text)
66
+ if parsed.get("slugs"):
67
+ return f"{parsed['error']}; the slugs: {', '.join(parsed['slugs'])}"
68
+ return str(parsed.get("error", text))
69
+ except (ValueError, KeyError, TypeError, AttributeError):
70
+ return text
71
+
72
+
73
+ def get(path: str, params: Optional[Dict[str, Any]] = None) -> Any:
74
+ """The API's JSON answer, or a DatacircleError with its words: waits once when it answers 429."""
75
+ query = urllib.parse.urlencode({key: value for key, value in (params or {}).items() if value not in (None, "")})
76
+ url = f"{BASE_URL.rstrip('/')}{path}" + (f"?{query}" if query else "")
77
+ request = urllib.request.Request(url, headers={"Accept": "application/json", "User-Agent": USER_AGENT})
78
+ for attempt in range(2):
79
+ try:
80
+ with urllib.request.urlopen(request, timeout=TIMEOUT) as answer:
81
+ body = answer.read()
82
+ except urllib.error.HTTPError as error:
83
+ body = error.read()
84
+ if error.code == 429 and not attempt:
85
+ try:
86
+ wait = int(error.headers.get("Retry-After") or 30)
87
+ except ValueError:
88
+ wait = 30
89
+ time.sleep(min(max(wait, 1), 60))
90
+ continue
91
+ if error.code == 429:
92
+ raise DatacircleError("Datacircle's API answered 429 twice: wait a minute and call again", 429, True) from None
93
+ raise DatacircleError(f"Datacircle's API answered {error.code}: {_words(body)[:3000]}", error.code,
94
+ error.code >= 500) from None
95
+ except (urllib.error.URLError, OSError) as error:
96
+ raise DatacircleError(f"Datacircle's API could not be reached: {getattr(error, 'reason', error)}",
97
+ retryable=True) from None
98
+ try:
99
+ return json.loads(body)
100
+ except ValueError as error:
101
+ raise DatacircleError(f"Datacircle's API gave no JSON: {error}") from None
@@ -0,0 +1,183 @@
1
+ """Pipecat function tools on Datacircle's open API, https://api.datacircle.dev/v1: no key, no account.
2
+
3
+ Each tool is a FunctionSchema that carries its handler: advertised in an LLMContext's tools, the LLM service registers
4
+ the handler by itself, with no register_function call. A handler makes one HTTPS GET, off the event loop, and gives
5
+ the model the API's answer as its result. A refusal (an unknown slug, an argument out of range, the API out of reach)
6
+ is the result {"error": the API's words}, so the model can call again. Pipecat checks no argument against a schema, so
7
+ each tool checks its own before any call.
8
+ """
9
+
10
+ import asyncio
11
+ import json
12
+ import urllib.parse
13
+ from typing import Any, Callable, Dict, List, Optional
14
+
15
+ try:
16
+ from pipecat.adapters.llm.schemas.function_schema import FunctionSchema
17
+ from pipecat.adapters.llm.schemas.tools_schema import ToolsSchema
18
+ except ImportError: # pipecat-ai before 1.14
19
+ from pipecat.adapters.schemas.function_schema import FunctionSchema
20
+ from pipecat.adapters.schemas.tools_schema import ToolsSchema
21
+
22
+ from pipecat_datacircle import _api
23
+
24
+
25
+ def _best(plans: Any) -> Optional[Dict[str, Any]]:
26
+ """A provider's best plan on an API: its lowest rank, a plan with no score having none."""
27
+ ranked = sorted(plans, key=lambda plan: plan.get("rank") if isinstance(plan.get("rank"), (int, float)) else float("inf"))
28
+ return _api.brief(ranked[0], ["plan", "score", "perThousand", "page"]) if ranked else None
29
+
30
+
31
+ def list_apis(query: Optional[str] = None, limit: Optional[int] = None) -> Dict[str, Any]:
32
+ count = _api.whole("limit", limit, 1, 200) or 20
33
+ apis = _api.get("/apis")
34
+ words = [word for word in str(query or "").lower().replace("-", " ").split() if word]
35
+ held = []
36
+ for index, api in enumerate(apis):
37
+ name = f"{api.get('api', '')} {str(api.get('slug', '')).replace('-', ' ')}".lower()
38
+ matched = sum(word in name for word in words)
39
+ if matched or not words:
40
+ held.append((-matched, index, api))
41
+ found = [_api.brief(api, _api.API_KEYS) for _, _, api in sorted(held, key=lambda h: h[:2])]
42
+ return {"total": len(found), "apis": found[:count]}
43
+
44
+
45
+ def best_plans(slug: Optional[str] = None, limit: Optional[int] = None) -> Dict[str, Any]:
46
+ made = _api.slug(slug)
47
+ if not made:
48
+ raise _api.DatacircleError("Give an API's slug, like 'email-finder': datacircle_list_apis gives every slug")
49
+ answer = _api.get(f"/apis/{urllib.parse.quote(made)}/best", {"limit": _api.whole("limit", limit, 1, 50)})
50
+ return {**answer, "plans": [_api.brief(plan) for plan in answer.get("plans") or []]}
51
+
52
+
53
+ def search_plans(api: Optional[str] = None, query: Optional[str] = None, sort: Optional[str] = None,
54
+ limit: Optional[int] = None, offset: Optional[int] = None) -> Dict[str, Any]:
55
+ order = str(sort).strip().lower() if sort not in (None, "") else None
56
+ if order is not None and order not in ("score", "provider", "price"):
57
+ raise _api.DatacircleError(f"sort must be score, provider or price, not {sort!r}")
58
+ params = {"api": api, "query": query, "sort": order, "limit": _api.whole("limit", limit, 1, 50),
59
+ "offset": _api.whole("offset", offset, 0)}
60
+ answer = _api.get("/plans", params)
61
+ return {**answer, "plans": [_api.brief(plan) for plan in answer.get("plans") or []]}
62
+
63
+
64
+ def provider(slug: Optional[str] = None) -> Dict[str, Any]:
65
+ made = _api.slug(slug)
66
+ if not made:
67
+ raise _api.DatacircleError("Give a provider's slug or name, like 'bright-data' or 'Bright Data'")
68
+ answer = _api.get(f"/providers/{urllib.parse.quote(made)}")
69
+ apis = [{**_api.brief(entry, ["api", "slug", "rank", "bestPage"]), "plans": len(entry.get("plans") or []),
70
+ "best": _best(entry.get("plans") or [])} for entry in answer.get("apis") or []]
71
+ return {**answer, "apis": apis}
72
+
73
+
74
+ _PRICE = "perThousand is a plan's price of 1,000 items in dollars, pay the plan's whole price in its currency."
75
+ _LIMIT = {"type": "integer", "minimum": 1, "maximum": 50, "description": "How many plans to give, 1 to 50. 10 when left out."}
76
+
77
+ # Each tool: its description, its parameters (JSON schema properties), the ones it needs, and its function.
78
+ _TOOLS: Dict[str, Any] = {
79
+ "datacircle_list_apis": (
80
+ "Lists the GTM APIs on Datacircle's sheet (https://datacircle.dev), with each API's slug, how many plans and "
81
+ "providers it has and its best plan. Call it first to find an API's slug. Gives total, the APIs found, and "
82
+ "apis, up to limit of them.",
83
+ {
84
+ "query": {"type": "string", "description": "Words of the API's name or slug, like 'email' or 'linkedin "
85
+ "profile': the APIs that hold the most of them come first. The "
86
+ "sheet's order when left out."},
87
+ "limit": {"type": "integer", "minimum": 1, "maximum": 200,
88
+ "description": "How many APIs to give, 1 to 200. 20 when left out: the sheet has about 160."},
89
+ },
90
+ [],
91
+ list_apis,
92
+ ),
93
+ "datacircle_best_plans": (
94
+ "Gives an API's plans best first by their score out of 100 on Datacircle's benchmark (https://datacircle.dev), "
95
+ "each with its rank, provider, plan, $ per 1,000 calls and its page: the best providers of an API. " + _PRICE,
96
+ {
97
+ "slug": {"type": "string", "description": "The API's slug, like 'email-finder' or 'linkedin-profile', as "
98
+ "datacircle_list_apis gives it."},
99
+ "limit": _LIMIT,
100
+ },
101
+ ["slug"],
102
+ best_plans,
103
+ ),
104
+ "datacircle_search_plans": (
105
+ "Searches every plan on Datacircle's sheet (https://datacircle.dev), or one API's, by provider or plan name, "
106
+ "sorted by score, provider or price. Gives total, offset and up to limit plans. " + _PRICE,
107
+ {
108
+ "api": {"type": "string", "description": "Only this API's plans: its name or slug, like 'email-finder'. A "
109
+ "provider's name goes in query, never here. Every API when left out."},
110
+ "query": {"type": "string", "description": "Words that must all appear in the provider's or plan's name, "
111
+ "like 'bright data'."},
112
+ "sort": {"type": "string", "enum": ["score", "provider", "price"],
113
+ "description": "score (best first, the default), provider (A to Z) or price ($ per 1,000, lowest first)."},
114
+ "limit": _LIMIT,
115
+ "offset": {"type": "integer", "minimum": 0, "description": "How many found plans to skip first. 0 when left out."},
116
+ },
117
+ [],
118
+ search_plans,
119
+ ),
120
+ "datacircle_provider": (
121
+ "Gives each API one provider sells and its rank on each on Datacircle's benchmark (https://datacircle.dev), "
122
+ "with its best plan there.",
123
+ {
124
+ "slug": {"type": "string", "description": "The provider's slug, like 'bright-data', or its name, like "
125
+ "'Bright Data': the name is made a slug."},
126
+ },
127
+ ["slug"],
128
+ provider,
129
+ ),
130
+ }
131
+ TOOL_NAMES = list(_TOOLS)
132
+
133
+
134
+ def run(name: str, arguments: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
135
+ """What a tool gives the model for these arguments: the API's answer, or {"error": its words}. Arguments the tool
136
+ doesn't take are left out."""
137
+ if name not in _TOOLS:
138
+ raise ValueError(f"Datacircle has no tool {name!r}: its tools are {', '.join(TOOL_NAMES)}")
139
+ _, properties, _, function = _TOOLS[name]
140
+ given = arguments if isinstance(arguments, dict) else {}
141
+ try:
142
+ return function(**{key: given.get(key) for key in properties})
143
+ except _api.DatacircleError as error:
144
+ return {"error": str(error)}
145
+
146
+
147
+ def _handler(name: str) -> Callable[[Any], Any]:
148
+ async def handler(params: Any) -> None:
149
+ await params.result_callback(await asyncio.to_thread(run, name, dict(params.arguments or {})))
150
+
151
+ handler.__name__ = handler.__qualname__ = name
152
+ handler.__doc__ = f"Pipecat's handler of {name}: the call's result is run({name!r}, its arguments)."
153
+ return handler
154
+
155
+
156
+ # One handler for each tool, the same object on every schema made: the LLM service rebinds a tool whose handler changed.
157
+ HANDLERS: Dict[str, Callable[[Any], Any]] = {name: _handler(name) for name in TOOL_NAMES}
158
+
159
+
160
+ def datacircle_function(name: str) -> FunctionSchema:
161
+ """One of the four tools, by its name: a FunctionSchema that carries its handler."""
162
+ if name not in _TOOLS:
163
+ raise ValueError(f"Datacircle has no tool {name!r}: its tools are {', '.join(TOOL_NAMES)}")
164
+ description, properties, required, _ = _TOOLS[name]
165
+ return FunctionSchema(name=name, description=description, properties=json.loads(json.dumps(properties)),
166
+ required=list(required), handler=HANDLERS[name])
167
+
168
+
169
+ def datacircle_functions(tool_names: Optional[List[str]] = None) -> List[FunctionSchema]:
170
+ """The tools as a list, for LLMContext(tools=[...]) beside tools of one's own, or a ToolsSchema of one's own.
171
+ tool_names keeps some of them only, in their order here; all four when left out."""
172
+ if isinstance(tool_names, str):
173
+ raise TypeError("tool_names is a list of names, like ['datacircle_best_plans']")
174
+ return [datacircle_function(name) for name in (TOOL_NAMES if tool_names is None else tool_names)]
175
+
176
+
177
+ def datacircle_tools_schema(tool_names: Optional[List[str]] = None) -> ToolsSchema:
178
+ """The tools as a ToolsSchema, for LLMContext(messages, tools=datacircle_tools_schema())."""
179
+ return ToolsSchema(standard_tools=datacircle_functions(tool_names))
180
+
181
+
182
+ __all__: List[str] = ["HANDLERS", "TOOL_NAMES", "best_plans", "datacircle_function", "datacircle_functions",
183
+ "datacircle_tools_schema", "list_apis", "provider", "run", "search_plans"]
@@ -0,0 +1,199 @@
1
+ """Offline tests: the tools against a local stand-in for the API on 127.0.0.1, by their own run, by each handler as an
2
+ LLM service calls it, as Pipecat's adapters turn them into each provider's tools, and advertised in an LLMContext."""
3
+
4
+ import asyncio
5
+ import importlib
6
+ import json
7
+ import threading
8
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
9
+ from typing import Any, Dict, List
10
+ from urllib.parse import parse_qs, urlparse
11
+
12
+ import pytest
13
+
14
+ from pipecat_datacircle import (
15
+ HANDLERS,
16
+ TOOL_NAMES,
17
+ DatacircleError,
18
+ datacircle_function,
19
+ datacircle_functions,
20
+ datacircle_tools_schema,
21
+ run,
22
+ )
23
+ from pipecat_datacircle import _api
24
+
25
+ try:
26
+ from pipecat.adapters.llm.schemas.function_schema import FunctionSchema
27
+ from pipecat.adapters.llm.schemas.tools_schema import ToolsSchema
28
+ except ImportError:
29
+ from pipecat.adapters.schemas.function_schema import FunctionSchema
30
+ from pipecat.adapters.schemas.tools_schema import ToolsSchema
31
+
32
+ PLAN = {"api": "Employee email", "rank": 1, "provider": "Hunter", "plan": "Starter", "score": 80.1, "perThousand": 4.9,
33
+ "page": "https://datacircle.dev/x", "terms": "long", "aggregators": ["a"]}
34
+ SEEN = []
35
+ BUSY = []
36
+
37
+
38
+ class Handler(BaseHTTPRequestHandler):
39
+ def log_message(self, *args):
40
+ pass
41
+
42
+ def do_GET(self):
43
+ url = urlparse(self.path)
44
+ query = {key: values[0] for key, values in parse_qs(url.query).items()}
45
+ SEEN.append((url.path, query, self.headers.get("User-Agent")))
46
+ headers = {}
47
+ if url.path == "/v1/plans" and query.get("query") == "busy" and not BUSY:
48
+ BUSY.append(1)
49
+ status, body, headers = 429, {"error": "slow down"}, {"Retry-After": "1"}
50
+ elif url.path == "/v1/apis":
51
+ status, body = 200, [{"api": "Employee email", "slug": "email-finder", "plans": 9, "providers": 3, "extra": 1},
52
+ {"api": "Employee profile", "slug": "linkedin-profile", "plans": 4, "providers": 2}]
53
+ elif url.path == "/v1/apis/email-finder/best":
54
+ status, body = 200, {"api": "Employee email", "slug": "email-finder", "total": 1, "plans": [PLAN]}
55
+ elif url.path.startswith("/v1/apis/"):
56
+ status, body = 404, {"error": "no API has the slug nope", "slugs": ["email-finder", "linkedin-profile"]}
57
+ elif url.path == "/v1/plans" and query.get("query") == "down":
58
+ status, body = 503, {"error": "down for a minute"}
59
+ elif url.path == "/v1/plans":
60
+ status, body = 200, {"total": 1, "offset": 0, "plans": [PLAN]}
61
+ elif url.path == "/v1/providers/bright-data":
62
+ status, body = 200, {"provider": "Bright Data", "slug": "bright-data", "website": "https://brightdata.com",
63
+ "apis": [{"api": "Employee email", "slug": "email-finder", "rank": 7, "sheetPage": "s",
64
+ "plans": [dict(PLAN, rank=9, plan="B"), dict(PLAN, rank=7, plan="A")]}]}
65
+ else:
66
+ status, body = 404, {"error": "no provider has this slug"}
67
+ data = json.dumps(body).encode()
68
+ self.send_response(status)
69
+ for key, value in {"Content-Type": "application/json", "Content-Length": str(len(data)), **headers}.items():
70
+ self.send_header(key, value)
71
+ self.end_headers()
72
+ self.wfile.write(data)
73
+
74
+
75
+ @pytest.fixture(scope="module", autouse=True)
76
+ def stand_in():
77
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
78
+ threading.Thread(target=server.serve_forever, daemon=True).start()
79
+ before = _api.BASE_URL
80
+ _api.BASE_URL = f"http://127.0.0.1:{server.server_address[1]}/v1"
81
+ yield
82
+ _api.BASE_URL = before
83
+ server.shutdown()
84
+
85
+
86
+ class Params:
87
+ """What an LLM service hands a handler, of it the arguments and the result callback."""
88
+
89
+ def __init__(self, name: str, arguments: Dict[str, Any]):
90
+ self.function_name, self.tool_call_id, self.arguments = name, "call_1", arguments
91
+ self.results: List[Any] = []
92
+
93
+ async def result_callback(self, result: Any, *, properties: Any = None) -> None:
94
+ self.results.append(result)
95
+
96
+
97
+ def handled(name: str, **arguments: Any) -> Any:
98
+ params = Params(name, arguments)
99
+ asyncio.run(HANDLERS[name](params))
100
+ assert len(params.results) == 1
101
+ return params.results[0]
102
+
103
+
104
+ def test_the_schemas():
105
+ schemas = datacircle_functions()
106
+ assert [s.name for s in schemas] == TOOL_NAMES and all(isinstance(s, FunctionSchema) for s in schemas)
107
+ for schema in schemas:
108
+ assert "https://datacircle.dev" in schema.description and schema.handler is HANDLERS[schema.name]
109
+ assert schema.to_default_dict()["parameters"]["type"] == "object"
110
+ assert datacircle_function("datacircle_best_plans").required == ["slug"]
111
+ assert datacircle_function("datacircle_provider").required == ["slug"]
112
+ assert datacircle_function("datacircle_list_apis").required == []
113
+ search = datacircle_function("datacircle_search_plans").properties
114
+ assert search["sort"]["enum"] == ["score", "provider", "price"]
115
+ assert search["limit"] == {"type": "integer", "minimum": 1, "maximum": 50,
116
+ "description": "How many plans to give, 1 to 50. 10 when left out."}
117
+ search["limit"]["maximum"] = 5 # each schema holds its own copy
118
+ assert datacircle_function("datacircle_search_plans").properties["limit"]["maximum"] == 50
119
+ tools = datacircle_tools_schema(["datacircle_provider", "datacircle_list_apis"])
120
+ assert isinstance(tools, ToolsSchema) and [s.name for s in tools.standard_tools] == ["datacircle_provider", "datacircle_list_apis"]
121
+ assert datacircle_tools_schema([]).standard_tools == []
122
+ with pytest.raises(ValueError, match="its tools are datacircle_list_apis"):
123
+ datacircle_functions(["datacircle_nope"])
124
+ with pytest.raises(TypeError):
125
+ datacircle_functions("datacircle_provider")
126
+
127
+
128
+ def test_each_tool_by_its_handler():
129
+ SEEN.clear()
130
+ assert handled("datacircle_list_apis", query="profile") == \
131
+ {"total": 1, "apis": [{"api": "Employee profile", "slug": "linkedin-profile", "plans": 4, "providers": 2}]}
132
+ assert handled("datacircle_list_apis", limit=1)["apis"][0]["slug"] == "email-finder"
133
+ best = handled("datacircle_best_plans", slug="Email Finder", limit=3)
134
+ assert best["plans"] == [{key: value for key, value in PLAN.items() if key not in ("terms", "aggregators")}]
135
+ found = handled("datacircle_search_plans", query="hunter", sort="price", limit=2)
136
+ assert found["total"] == 1 and "terms" not in found["plans"][0]
137
+ seller = handled("datacircle_provider", slug="Bright Data")
138
+ assert seller["apis"] == [{"api": "Employee email", "slug": "email-finder", "rank": 7, "plans": 2,
139
+ "best": {"plan": "A", "score": 80.1, "perThousand": 4.9, "page": "https://datacircle.dev/x"}}]
140
+ assert ("/v1/apis/email-finder/best", {"limit": "3"}, _api.USER_AGENT) in SEEN
141
+ assert ("/v1/plans", {"query": "hunter", "sort": "price", "limit": "2"}, _api.USER_AGENT) in SEEN
142
+ assert _api.USER_AGENT.startswith("pipecat-datacircle/")
143
+ assert handled("datacircle_best_plans", slug="email-finder", color="red")["total"] == 1 # an argument it doesn't take
144
+ assert json.loads(json.dumps(seller, ensure_ascii=False)) == seller # what the aggregator puts in the context
145
+
146
+
147
+ def test_refusals_in_the_apis_words():
148
+ words = handled("datacircle_best_plans", slug="nope")["error"]
149
+ assert "answered 404" in words and "email-finder, linkedin-profile" in words
150
+ assert "no provider has this slug" in handled("datacircle_provider", slug="nobody")["error"]
151
+ assert "answered 503" in handled("datacircle_search_plans", query="down")["error"]
152
+ assert "Give a provider's slug" in handled("datacircle_provider", slug=" ")["error"]
153
+ assert "Give an API's slug" in handled("datacircle_best_plans")["error"]
154
+ with pytest.raises(DatacircleError) as raised:
155
+ _api.get("/plans", {"query": "down"})
156
+ assert raised.value.status == 503 and raised.value.retryable
157
+
158
+
159
+ def test_arguments_out_of_range_never_reach_the_api():
160
+ SEEN.clear()
161
+ assert run("datacircle_search_plans", {"sort": "cheapest"}) == {"error": "sort must be score, provider or price, not 'cheapest'"}
162
+ assert run("datacircle_best_plans", {"slug": "email-finder", "limit": 80}) == {"error": "limit must be from 1 to 50, not 80"}
163
+ assert "offset must be a whole number" in run("datacircle_search_plans", {"offset": 1.5})["error"]
164
+ assert SEEN == []
165
+ assert run("datacircle_best_plans", {"slug": "email-finder", "limit": "2"})["total"] == 1 # a number sent as text
166
+ assert run("datacircle_list_apis", None)["total"] == 2
167
+ with pytest.raises(ValueError):
168
+ run("datacircle_nope", {})
169
+
170
+
171
+ def test_waits_once_on_429():
172
+ BUSY.clear()
173
+ assert handled("datacircle_search_plans", query="busy")["total"] == 1
174
+
175
+
176
+ def _adapter(module: str, name: str):
177
+ for prefix in ("pipecat.adapters.llm.services.", "pipecat.adapters.services."):
178
+ try:
179
+ return getattr(importlib.import_module(prefix + module), name)()
180
+ except ImportError:
181
+ continue
182
+ pytest.skip(f"{name} needs an extra of pipecat-ai")
183
+
184
+
185
+ @pytest.mark.parametrize("module,name", [("open_ai_adapter", "OpenAILLMAdapter"), ("anthropic_adapter", "AnthropicLLMAdapter"),
186
+ ("gemini_adapter", "GeminiLLMAdapter"), ("bedrock_adapter", "AWSBedrockLLMAdapter")])
187
+ def test_each_providers_tools(module, name):
188
+ tools = _adapter(module, name).to_provider_tools_format(datacircle_tools_schema())
189
+ text = json.dumps(tools, default=str)
190
+ assert all(tool_name in text for tool_name in TOOL_NAMES) and "email-finder" in text
191
+
192
+
193
+ def test_an_llm_context_takes_them():
194
+ from pipecat.processors.aggregators.llm_context import LLMContext
195
+
196
+ assert [s.name for s in LLMContext(tools=datacircle_tools_schema()).tools.standard_tools] == TOOL_NAMES
197
+ mine = FunctionSchema(name="what_time", description="The time.", properties={}, required=[])
198
+ listed = LLMContext(tools=[mine, *datacircle_functions()]).tools.standard_tools
199
+ assert [s.name for s in listed] == ["what_time", *TOOL_NAMES] and listed[1].handler is HANDLERS["datacircle_list_apis"]