crewai-veille 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,14 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ venv/
5
+ build/
6
+ dist/
7
+ *.egg-info/
8
+ .pytest_cache/
9
+ .mypy_cache/
10
+ .ruff_cache/
11
+ .coverage
12
+ htmlcov/
13
+ .env
14
+ .DS_Store
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Veille
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,75 @@
1
+ Metadata-Version: 2.5
2
+ Name: crewai-veille
3
+ Version: 0.1.0
4
+ Summary: CrewAI tools for Veille: check emails, domains, IP addresses, phone numbers, EU VAT numbers and IBANs for fraud and validity.
5
+ Project-URL: Homepage, https://www.veille.io
6
+ Project-URL: Documentation, https://github.com/veilleio/crewai-veille#readme
7
+ Project-URL: Repository, https://github.com/veilleio/crewai-veille
8
+ Project-URL: Issues, https://github.com/veilleio/crewai-veille/issues
9
+ Author-email: Veille <contact@veille.io>
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: agents,crewai,email-validation,fraud,iban,ip-reputation,phone-validation,tools,vat,veille
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Topic :: Internet :: WWW/HTTP
17
+ Classifier: Typing :: Typed
18
+ Requires-Python: <3.14,>=3.10
19
+ Requires-Dist: crewai>=0.150
20
+ Requires-Dist: httpx<1,>=0.27
21
+ Provides-Extra: test
22
+ Requires-Dist: pytest>=8.3; extra == 'test'
23
+ Requires-Dist: ruff<1,>=0.8; extra == 'test'
24
+ Description-Content-Type: text/markdown
25
+
26
+ # crewai-veille
27
+
28
+ [CrewAI](https://www.crewai.com) tools for [Veille](https://www.veille.io): check emails, domains, IP addresses, phone numbers, EU VAT numbers and IBANs for fraud and validity.
29
+
30
+ ## Installation
31
+
32
+ ```bash
33
+ pip install crewai-veille
34
+ export VEILLE_API_KEY="your-api-key"
35
+ ```
36
+
37
+ Get an API key at [app.veille.io](https://app.veille.io).
38
+
39
+ ## Tools
40
+
41
+ | Tool | What it does |
42
+ | --- | --- |
43
+ | `VeilleEmailCheckTool` | Check an email address through Veille. |
44
+ | `VeilleDomainCheckTool` | Check a domain through Veille. |
45
+ | `VeilleIPCheckTool` | Check an IP address through Veille. |
46
+ | `VeillePhoneCheckTool` | Check a phone number through Veille. |
47
+ | `VeilleVATCheckTool` | Validate an EU VAT number through Veille. |
48
+ | `VeilleIBANCheckTool` | Validate an IBAN through Veille. |
49
+
50
+ Each tool takes `api_key` (defaults to `VEILLE_API_KEY`), `base_url` and `timeout`, plus the settings shown in its docstring. Errors (invalid key, no credits, rate limit, timeout) come back to the agent as text, without the API key.
51
+
52
+ ```python
53
+ from crewai import Agent
54
+ from crewai_veille import VeilleEmailCheckTool, VeilleDomainCheckTool
55
+
56
+ agent = Agent(
57
+ role="Analyst",
58
+ goal="Answer with data from Veille",
59
+ backstory="You use Veille to check emails.",
60
+ tools=[VeilleEmailCheckTool(), VeilleDomainCheckTool()],
61
+ )
62
+
63
+ print(VeilleEmailCheckTool().run(**{"email": "john@example.com"}))
64
+ ```
65
+
66
+ ## Development
67
+
68
+ ```bash
69
+ pip install -e ".[test]"
70
+ pytest
71
+ ```
72
+
73
+ ## License
74
+
75
+ MIT
@@ -0,0 +1,50 @@
1
+ # crewai-veille
2
+
3
+ [CrewAI](https://www.crewai.com) tools for [Veille](https://www.veille.io): check emails, domains, IP addresses, phone numbers, EU VAT numbers and IBANs for fraud and validity.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pip install crewai-veille
9
+ export VEILLE_API_KEY="your-api-key"
10
+ ```
11
+
12
+ Get an API key at [app.veille.io](https://app.veille.io).
13
+
14
+ ## Tools
15
+
16
+ | Tool | What it does |
17
+ | --- | --- |
18
+ | `VeilleEmailCheckTool` | Check an email address through Veille. |
19
+ | `VeilleDomainCheckTool` | Check a domain through Veille. |
20
+ | `VeilleIPCheckTool` | Check an IP address through Veille. |
21
+ | `VeillePhoneCheckTool` | Check a phone number through Veille. |
22
+ | `VeilleVATCheckTool` | Validate an EU VAT number through Veille. |
23
+ | `VeilleIBANCheckTool` | Validate an IBAN through Veille. |
24
+
25
+ Each tool takes `api_key` (defaults to `VEILLE_API_KEY`), `base_url` and `timeout`, plus the settings shown in its docstring. Errors (invalid key, no credits, rate limit, timeout) come back to the agent as text, without the API key.
26
+
27
+ ```python
28
+ from crewai import Agent
29
+ from crewai_veille import VeilleEmailCheckTool, VeilleDomainCheckTool
30
+
31
+ agent = Agent(
32
+ role="Analyst",
33
+ goal="Answer with data from Veille",
34
+ backstory="You use Veille to check emails.",
35
+ tools=[VeilleEmailCheckTool(), VeilleDomainCheckTool()],
36
+ )
37
+
38
+ print(VeilleEmailCheckTool().run(**{"email": "john@example.com"}))
39
+ ```
40
+
41
+ ## Development
42
+
43
+ ```bash
44
+ pip install -e ".[test]"
45
+ pytest
46
+ ```
47
+
48
+ ## License
49
+
50
+ MIT
@@ -0,0 +1,59 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.26,<2"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "crewai-veille"
7
+ version = "0.1.0"
8
+ description = "CrewAI tools for Veille: check emails, domains, IP addresses, phone numbers, EU VAT numbers and IBANs for fraud and validity."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10,<3.14"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [
14
+ { name = "Veille", email = "contact@veille.io" },
15
+ ]
16
+ keywords = ["crewai", "veille", "tools", "agents", "email-validation", "fraud", "ip-reputation", "vat", "iban", "phone-validation"]
17
+ classifiers = [
18
+ "Intended Audience :: Developers",
19
+ "Operating System :: OS Independent",
20
+ "Programming Language :: Python :: 3 :: Only",
21
+ "Topic :: Internet :: WWW/HTTP",
22
+ "Typing :: Typed",
23
+ ]
24
+ dependencies = [
25
+ "crewai>=0.150",
26
+ "httpx>=0.27,<1",
27
+ ]
28
+
29
+ [project.optional-dependencies]
30
+ test = [
31
+ "pytest>=8.3",
32
+ "ruff>=0.8,<1",
33
+ ]
34
+
35
+ [project.urls]
36
+ Homepage = "https://www.veille.io"
37
+ Documentation = "https://github.com/veilleio/crewai-veille#readme"
38
+ Repository = "https://github.com/veilleio/crewai-veille"
39
+ Issues = "https://github.com/veilleio/crewai-veille/issues"
40
+
41
+ [tool.crewai]
42
+ type = "tool"
43
+
44
+ [tool.hatch.build.targets.wheel]
45
+ packages = ["src/crewai_veille"]
46
+
47
+ [tool.hatch.build.targets.sdist]
48
+ include = ["/src", "/tests", "/LICENSE", "/README.md", "/pyproject.toml"]
49
+
50
+ [tool.pytest.ini_options]
51
+ addopts = "-ra"
52
+ testpaths = ["tests"]
53
+
54
+ [tool.ruff]
55
+ target-version = "py310"
56
+ line-length = 120
57
+
58
+ [tool.ruff.lint]
59
+ select = ["E4", "E7", "E9", "F", "I", "UP", "B"]
@@ -0,0 +1,33 @@
1
+ """CrewAI tools for Veille."""
2
+
3
+ from crewai_veille._client import VeilleError
4
+ from crewai_veille.tools import (
5
+ VeilleDomainCheckTool,
6
+ VeilleDomainCheckToolSchema,
7
+ VeilleEmailCheckTool,
8
+ VeilleEmailCheckToolSchema,
9
+ VeilleIBANCheckTool,
10
+ VeilleIBANCheckToolSchema,
11
+ VeilleIPCheckTool,
12
+ VeilleIPCheckToolSchema,
13
+ VeillePhoneCheckTool,
14
+ VeillePhoneCheckToolSchema,
15
+ VeilleVATCheckTool,
16
+ VeilleVATCheckToolSchema,
17
+ )
18
+
19
+ __all__ = [
20
+ "VeilleDomainCheckTool",
21
+ "VeilleDomainCheckToolSchema",
22
+ "VeilleEmailCheckTool",
23
+ "VeilleEmailCheckToolSchema",
24
+ "VeilleError",
25
+ "VeilleIBANCheckTool",
26
+ "VeilleIBANCheckToolSchema",
27
+ "VeilleIPCheckTool",
28
+ "VeilleIPCheckToolSchema",
29
+ "VeillePhoneCheckTool",
30
+ "VeillePhoneCheckToolSchema",
31
+ "VeilleVATCheckTool",
32
+ "VeilleVATCheckToolSchema",
33
+ ]
@@ -0,0 +1,140 @@
1
+ """HTTP client for the Veille API (https://www.veille.io)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from typing import Any
7
+
8
+ import httpx
9
+
10
+ DEFAULT_BASE_URL = "https://api.veille.io"
11
+ DEFAULT_TIMEOUT = 60.0
12
+ USER_AGENT = "crewai-veille"
13
+ ENV = "VEILLE_API_KEY"
14
+
15
+ _ERROR_DETAIL_LIMIT = 300
16
+
17
+
18
+ class VeilleError(Exception):
19
+ """A Veille request failed. The message never contains the API key."""
20
+
21
+ def __init__(self, message: str, status_code: int | None = None) -> None:
22
+ super().__init__(message)
23
+ self.status_code = status_code
24
+
25
+
26
+ def resolve_api_key(value: str | None) -> str:
27
+ """Return ``value`` or ``VEILLE_API_KEY``, stripped. Raises if neither is set."""
28
+ key = (value or os.environ.get(ENV) or "").strip()
29
+ if not key:
30
+ raise VeilleError(f"Set {ENV} or pass api_key. Get a key at https://app.veille.io")
31
+ return key
32
+
33
+
34
+ def required(value: Any, name: str) -> str:
35
+ """Return ``value`` stripped, or raise if it is empty."""
36
+ text = str(value or "").strip()
37
+ if not text:
38
+ raise VeilleError(f"{name} is empty.")
39
+ return text
40
+
41
+
42
+ def clean(values: dict[str, Any]) -> dict[str, Any]:
43
+ """Drop unset values; send booleans as true/false."""
44
+ out: dict[str, Any] = {}
45
+ for key, value in values.items():
46
+ if value is None or value == "":
47
+ continue
48
+ out[key] = ("true" if value else "false") if isinstance(value, bool) else value
49
+ return out
50
+
51
+
52
+ def _redact(text: str, api_key: str) -> str:
53
+ return text.replace(api_key, "***") if api_key else text
54
+
55
+
56
+ def _error(response: httpx.Response, api_key: str) -> VeilleError:
57
+ detail = ""
58
+ try:
59
+ body = response.json()
60
+ except ValueError:
61
+ detail = response.text.strip()
62
+ else:
63
+ if isinstance(body, dict):
64
+ error = body.get("error") or body.get("message") or ""
65
+ if isinstance(error, dict):
66
+ error = error.get("message") or ""
67
+ detail = str(error)
68
+ detail = _redact(detail, api_key)[:_ERROR_DETAIL_LIMIT]
69
+ status = response.status_code
70
+ # Veille answers a rate limit with HTTP 401 and a "Rate limit exceeded" message.
71
+ if status == 429 or (status == 401 and "rate limit" in detail.lower()):
72
+ label = "Veille rate limit exceeded"
73
+ elif status == 401:
74
+ label = "Veille rejected the API key"
75
+ elif status == 402:
76
+ label = "Veille account is out of credits"
77
+ else:
78
+ label = "Veille API error"
79
+ return VeilleError(f"{label} (HTTP {status})" + (f": {detail}" if detail else ""), status)
80
+
81
+
82
+ def _headers(api_key: str) -> dict[str, str]:
83
+ headers = {"Accept": "application/json", "User-Agent": USER_AGENT}
84
+ headers["x-api-key"] = api_key
85
+ return headers
86
+
87
+
88
+ def _decode(response: httpx.Response, api_key: str) -> Any:
89
+ if not response.is_success:
90
+ raise _error(response, api_key)
91
+ try:
92
+ return response.json()
93
+ except ValueError as exc:
94
+ raise VeilleError("Veille returned a response that is not JSON.") from exc
95
+
96
+
97
+ def request(
98
+ method: str,
99
+ path: str,
100
+ *,
101
+ params: dict[str, Any] | None = None,
102
+ json: dict[str, Any] | None = None,
103
+ api_key: str,
104
+ base_url: str = DEFAULT_BASE_URL,
105
+ timeout: float = DEFAULT_TIMEOUT,
106
+ ) -> Any:
107
+ """Call ``path`` and return the decoded JSON body."""
108
+ try:
109
+ with httpx.Client(timeout=timeout) as client:
110
+ response = client.request(
111
+ method, f"{base_url.rstrip('/')}{path}", params=params, json=json, headers=_headers(api_key)
112
+ )
113
+ except httpx.TimeoutException as exc:
114
+ raise VeilleError(f"Veille did not answer within {timeout:g} seconds.") from exc
115
+ except httpx.HTTPError as exc:
116
+ raise VeilleError(f"Could not reach Veille: {_redact(str(exc), api_key)}") from exc
117
+ return _decode(response, api_key)
118
+
119
+
120
+ async def arequest(
121
+ method: str,
122
+ path: str,
123
+ *,
124
+ params: dict[str, Any] | None = None,
125
+ json: dict[str, Any] | None = None,
126
+ api_key: str,
127
+ base_url: str = DEFAULT_BASE_URL,
128
+ timeout: float = DEFAULT_TIMEOUT,
129
+ ) -> Any:
130
+ """Async version of :func:`request`."""
131
+ try:
132
+ async with httpx.AsyncClient(timeout=timeout) as client:
133
+ response = await client.request(
134
+ method, f"{base_url.rstrip('/')}{path}", params=params, json=json, headers=_headers(api_key)
135
+ )
136
+ except httpx.TimeoutException as exc:
137
+ raise VeilleError(f"Veille did not answer within {timeout:g} seconds.") from exc
138
+ except httpx.HTTPError as exc:
139
+ raise VeilleError(f"Could not reach Veille: {_redact(str(exc), api_key)}") from exc
140
+ return _decode(response, api_key)
@@ -0,0 +1,182 @@
1
+ """Veille tools for CrewAI agents."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any
7
+
8
+ from crewai.tools import BaseTool, EnvVar
9
+ from pydantic import BaseModel, Field
10
+
11
+ from crewai_veille import _client
12
+
13
+
14
+ class _VeilleTool(BaseTool):
15
+ """Shared settings and request handling for the Veille tools. Errors come back as text."""
16
+
17
+ api_key: str | None = Field(default=None, description="Veille API key. Defaults to VEILLE_API_KEY.")
18
+ base_url: str = _client.DEFAULT_BASE_URL
19
+ timeout: float = _client.DEFAULT_TIMEOUT
20
+ env_vars: list[EnvVar] = Field(
21
+ default_factory=lambda: [EnvVar(name="VEILLE_API_KEY", description="API key for Veille", required=True)]
22
+ )
23
+
24
+ def _output(self, data: Any) -> Any:
25
+ return data
26
+
27
+ def _send(self, method: str, path: str, params: dict[str, Any] | None, body: dict[str, Any] | None) -> Any:
28
+ api_key = _client.resolve_api_key(self.api_key)
29
+ return _client.request(
30
+ method,
31
+ path,
32
+ params=_client.clean(params) if params else None,
33
+ json=body,
34
+ api_key=api_key,
35
+ base_url=self.base_url,
36
+ timeout=self.timeout,
37
+ )
38
+
39
+ @staticmethod
40
+ def _text(data: Any) -> str:
41
+ return data if isinstance(data, str) else json.dumps(data, ensure_ascii=False)
42
+
43
+
44
+ class VeilleEmailCheckToolSchema(BaseModel):
45
+ """Input for VeilleEmailCheckTool."""
46
+
47
+ email: str = Field(default=..., description="The email address to check.")
48
+
49
+
50
+ class VeilleEmailCheckTool(_VeilleTool):
51
+ """Check an email address through Veille."""
52
+
53
+ name: str = "Check an email address with Veille"
54
+ description: str = "Check an email address with Veille: disposable or temporary provider, role account, alias, typo suggestion, MX, SPF and DMARC records, and a 0-100 risk score. Input is the email address."
55
+ args_schema: type[BaseModel] = VeilleEmailCheckToolSchema
56
+ qualify: bool = False
57
+ """Also check that the inbox exists over SMTP and detect catch-all domains (5 credits instead of 3)."""
58
+
59
+ def _request(self, email: str) -> tuple[str, str, dict[str, Any] | None, dict[str, Any] | None]:
60
+ path = "/v1/intelligence/emailq" if self.qualify else "/v1/intelligence/email"
61
+ return "GET", path, {"query": _client.required(email, "email")}, None
62
+
63
+ def _run(self, email: str, **kwargs: Any) -> str:
64
+ try:
65
+ return self._text(self._output(self._send(*self._request(email))))
66
+ except _client.VeilleError as exc:
67
+ return str(exc)
68
+
69
+
70
+ class VeilleDomainCheckToolSchema(BaseModel):
71
+ """Input for VeilleDomainCheckTool."""
72
+
73
+ domain: str = Field(default=..., description="The domain name, such as example.com.")
74
+
75
+
76
+ class VeilleDomainCheckTool(_VeilleTool):
77
+ """Check a domain through Veille."""
78
+
79
+ name: str = "Check a domain with Veille"
80
+ description: str = "Check a domain with Veille: MX, SPF and DMARC records, mail providers, WHOIS registrar and dates, domain age, and whether it is disposable or a relay. Input is the domain name."
81
+ args_schema: type[BaseModel] = VeilleDomainCheckToolSchema
82
+
83
+ def _request(self, domain: str) -> tuple[str, str, dict[str, Any] | None, dict[str, Any] | None]:
84
+ return "GET", "/v1/intelligence/domain", {"query": _client.required(domain, "domain")}, None
85
+
86
+ def _run(self, domain: str, **kwargs: Any) -> str:
87
+ try:
88
+ return self._text(self._output(self._send(*self._request(domain))))
89
+ except _client.VeilleError as exc:
90
+ return str(exc)
91
+
92
+
93
+ class VeilleIPCheckToolSchema(BaseModel):
94
+ """Input for VeilleIPCheckTool."""
95
+
96
+ ip: str = Field(default=..., description="The IPv4 or IPv6 address.")
97
+
98
+
99
+ class VeilleIPCheckTool(_VeilleTool):
100
+ """Check an IP address through Veille."""
101
+
102
+ name: str = "Check an IP address with Veille"
103
+ description: str = "Check an IP address with Veille: location, network owner, whether it is a VPN, proxy, Tor exit node, data center or known abuser, and a 0-100 threat score. Input is the IP address."
104
+ args_schema: type[BaseModel] = VeilleIPCheckToolSchema
105
+
106
+ def _request(self, ip: str) -> tuple[str, str, dict[str, Any] | None, dict[str, Any] | None]:
107
+ return "GET", "/v1/intelligence/ip", {"query": _client.required(ip, "ip")}, None
108
+
109
+ def _run(self, ip: str, **kwargs: Any) -> str:
110
+ try:
111
+ return self._text(self._output(self._send(*self._request(ip))))
112
+ except _client.VeilleError as exc:
113
+ return str(exc)
114
+
115
+
116
+ class VeillePhoneCheckToolSchema(BaseModel):
117
+ """Input for VeillePhoneCheckTool."""
118
+
119
+ phone: str = Field(default=..., description="The phone number in international format, such as +33612345678.")
120
+
121
+
122
+ class VeillePhoneCheckTool(_VeilleTool):
123
+ """Check a phone number through Veille."""
124
+
125
+ name: str = "Check a phone number with Veille"
126
+ description: str = "Check a phone number with Veille: validity, country, carrier, line type, whether it is virtual, disposable or reported as spam, and a 0-100 risk score. Input is the number in international format, such as +33612345678."
127
+ args_schema: type[BaseModel] = VeillePhoneCheckToolSchema
128
+
129
+ def _request(self, phone: str) -> tuple[str, str, dict[str, Any] | None, dict[str, Any] | None]:
130
+ return "GET", "/v1/intelligence/phone", {"query": _client.required(phone, "phone")}, None
131
+
132
+ def _run(self, phone: str, **kwargs: Any) -> str:
133
+ try:
134
+ return self._text(self._output(self._send(*self._request(phone))))
135
+ except _client.VeilleError as exc:
136
+ return str(exc)
137
+
138
+
139
+ class VeilleVATCheckToolSchema(BaseModel):
140
+ """Input for VeilleVATCheckTool."""
141
+
142
+ vat_number: str = Field(default=..., description="The VAT number with its country prefix, such as FR40303265045.")
143
+
144
+
145
+ class VeilleVATCheckTool(_VeilleTool):
146
+ """Validate an EU VAT number through Veille."""
147
+
148
+ name: str = "Check an EU VAT number with Veille"
149
+ description: str = "Validate a European VAT number in the EU VIES database with Veille and get the company name and address registered under it. Input is the VAT number with its country prefix, such as FR40303265045."
150
+ args_schema: type[BaseModel] = VeilleVATCheckToolSchema
151
+
152
+ def _request(self, vat_number: str) -> tuple[str, str, dict[str, Any] | None, dict[str, Any] | None]:
153
+ return "GET", "/v1/vat", {"query": _client.required(vat_number, "vat_number")}, None
154
+
155
+ def _run(self, vat_number: str, **kwargs: Any) -> str:
156
+ try:
157
+ return self._text(self._output(self._send(*self._request(vat_number))))
158
+ except _client.VeilleError as exc:
159
+ return str(exc)
160
+
161
+
162
+ class VeilleIBANCheckToolSchema(BaseModel):
163
+ """Input for VeilleIBANCheckTool."""
164
+
165
+ iban: str = Field(default=..., description="The IBAN to validate.")
166
+
167
+
168
+ class VeilleIBANCheckTool(_VeilleTool):
169
+ """Validate an IBAN through Veille."""
170
+
171
+ name: str = "Check an IBAN with Veille"
172
+ description: str = "Validate an IBAN with Veille and get its country, bank name, BIC and whether it is in the SEPA zone. Input is the IBAN."
173
+ args_schema: type[BaseModel] = VeilleIBANCheckToolSchema
174
+
175
+ def _request(self, iban: str) -> tuple[str, str, dict[str, Any] | None, dict[str, Any] | None]:
176
+ return "GET", "/v1/vat/iban", {"query": _client.required(iban, "iban")}, None
177
+
178
+ def _run(self, iban: str, **kwargs: Any) -> str:
179
+ try:
180
+ return self._text(self._output(self._send(*self._request(iban))))
181
+ except _client.VeilleError as exc:
182
+ return str(exc)
@@ -0,0 +1,155 @@
1
+ """Offline tests for crewai_veille (httpx.MockTransport)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections.abc import Callable
7
+
8
+ import httpx
9
+ import pytest
10
+
11
+ import crewai_veille as pkg
12
+ from crewai_veille import _client
13
+
14
+ API_KEY = "test-veille-key-placeholder" # pragma: allowlist secret
15
+ BASE = "https://api.veille.io"
16
+ CASES = [
17
+ {
18
+ "cls": "VeilleEmailCheckTool",
19
+ "config": {"qualify": True},
20
+ "sample": {"email": "john@example.com"},
21
+ "method": "GET",
22
+ "path": "/v1/intelligence/emailq",
23
+ "params": {"query": "john@example.com"},
24
+ "body": None,
25
+ "response": {"ok": True},
26
+ "result": {"ok": True},
27
+ },
28
+ {
29
+ "cls": "VeilleDomainCheckTool",
30
+ "config": {},
31
+ "sample": {"domain": "example.com"},
32
+ "method": "GET",
33
+ "path": "/v1/intelligence/domain",
34
+ "params": {"query": "example.com"},
35
+ "body": None,
36
+ "response": {"ok": True},
37
+ "result": {"ok": True},
38
+ },
39
+ {
40
+ "cls": "VeilleIPCheckTool",
41
+ "config": {},
42
+ "sample": {"ip": "8.8.8.8"},
43
+ "method": "GET",
44
+ "path": "/v1/intelligence/ip",
45
+ "params": {"query": "8.8.8.8"},
46
+ "body": None,
47
+ "response": {"ok": True},
48
+ "result": {"ok": True},
49
+ },
50
+ {
51
+ "cls": "VeillePhoneCheckTool",
52
+ "config": {},
53
+ "sample": {"phone": "+33612345678"},
54
+ "method": "GET",
55
+ "path": "/v1/intelligence/phone",
56
+ "params": {"query": "+33612345678"},
57
+ "body": None,
58
+ "response": {"ok": True},
59
+ "result": {"ok": True},
60
+ },
61
+ {
62
+ "cls": "VeilleVATCheckTool",
63
+ "config": {},
64
+ "sample": {"vat_number": "FR40303265045"},
65
+ "method": "GET",
66
+ "path": "/v1/vat",
67
+ "params": {"query": "FR40303265045"},
68
+ "body": None,
69
+ "response": {"ok": True},
70
+ "result": {"ok": True},
71
+ },
72
+ {
73
+ "cls": "VeilleIBANCheckTool",
74
+ "config": {},
75
+ "sample": {"iban": "FR7630006000011234567890189"},
76
+ "method": "GET",
77
+ "path": "/v1/vat/iban",
78
+ "params": {"query": "FR7630006000011234567890189"},
79
+ "body": None,
80
+ "response": {"ok": True},
81
+ "result": {"ok": True},
82
+ },
83
+ ]
84
+
85
+ Handler = Callable[[httpx.Request], httpx.Response]
86
+
87
+
88
+ @pytest.fixture
89
+ def mock_http(monkeypatch: pytest.MonkeyPatch) -> Callable[[Handler], list[httpx.Request]]:
90
+ def install(handler: Handler) -> list[httpx.Request]:
91
+ seen: list[httpx.Request] = []
92
+
93
+ def record(request: httpx.Request) -> httpx.Response:
94
+ seen.append(request)
95
+ return handler(request)
96
+
97
+ transport = httpx.MockTransport(record)
98
+ real_client, real_async = httpx.Client, httpx.AsyncClient
99
+ monkeypatch.setattr(_client.httpx, "Client", lambda **kw: real_client(transport=transport, **kw))
100
+ monkeypatch.setattr(_client.httpx, "AsyncClient", lambda **kw: real_async(transport=transport, **kw))
101
+ return seen
102
+
103
+ return install
104
+
105
+
106
+ def _params(request: httpx.Request) -> dict[str, str]:
107
+ return dict(request.url.params)
108
+
109
+
110
+ def _body(request: httpx.Request) -> object:
111
+ return json.loads(request.content) if request.content else None
112
+
113
+
114
+ @pytest.mark.parametrize("case", CASES, ids=[c["cls"] for c in CASES])
115
+ def test_request_and_result(mock_http, case) -> None:
116
+ seen = mock_http(lambda request: httpx.Response(200, json=case["response"]))
117
+ tool = getattr(pkg, case["cls"])(api_key=API_KEY, **case["config"])
118
+
119
+ result = tool.run(**case["sample"])
120
+
121
+ request = seen[0]
122
+ assert request.method == case["method"]
123
+ assert request.url.copy_with(query=None) == httpx.URL(BASE + case["path"])
124
+ assert _params(request) == (case["params"] or {})
125
+ assert _body(request) == case["body"]
126
+ expected = case["result"]
127
+ assert result == (expected if isinstance(expected, str) else json.dumps(expected, ensure_ascii=False))
128
+
129
+
130
+ @pytest.mark.parametrize(
131
+ ("status", "body", "message"),
132
+ [
133
+ (401, {"error": f"Invalid key {API_KEY}"}, "Veille rejected the API key (HTTP 401): Invalid key ***"),
134
+ (402, {"error": "No credits"}, "Veille account is out of credits (HTTP 402): No credits"),
135
+ ],
136
+ )
137
+ def test_errors_come_back_as_text(mock_http, status, body, message) -> None:
138
+ mock_http(lambda request: httpx.Response(status, json=body))
139
+ assert (
140
+ pkg.VeilleEmailCheckTool(api_key=API_KEY, **{"qualify": True}).run(**{"email": "john@example.com"}) == message
141
+ )
142
+
143
+
144
+ def test_missing_key_sends_no_request(mock_http, monkeypatch: pytest.MonkeyPatch) -> None:
145
+ monkeypatch.delenv("VEILLE_API_KEY", raising=False)
146
+ seen = mock_http(lambda request: httpx.Response(200, json={}))
147
+ assert "VEILLE_API_KEY" in pkg.VeilleEmailCheckTool(**{"qualify": True}).run(**{"email": "john@example.com"})
148
+ assert seen == []
149
+
150
+
151
+ def test_declares_its_env_var() -> None:
152
+ for name in pkg.__all__:
153
+ tool_cls = getattr(pkg, name)
154
+ if name.endswith("Tool"):
155
+ assert [env.name for env in tool_cls().env_vars] == ["VEILLE_API_KEY"]