langchain-doccheap 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,29 @@
1
+ """LangChain tools for the doc.cheap document-recognition API."""
2
+
3
+ from ._version import __version__
4
+ from .toolkit import DocCheapToolkit
5
+ from .tools import (
6
+ DocCheapDeleteScan,
7
+ DocCheapGetScan,
8
+ DocCheapGetUsage,
9
+ DocCheapListScans,
10
+ DocCheapScanDocument,
11
+ ListScansInput,
12
+ ScanDocumentInput,
13
+ ScanIdInput,
14
+ UsageInput,
15
+ )
16
+
17
+ __all__ = [
18
+ "DocCheapDeleteScan",
19
+ "DocCheapGetScan",
20
+ "DocCheapGetUsage",
21
+ "DocCheapListScans",
22
+ "DocCheapScanDocument",
23
+ "DocCheapToolkit",
24
+ "ListScansInput",
25
+ "ScanDocumentInput",
26
+ "ScanIdInput",
27
+ "UsageInput",
28
+ "__version__",
29
+ ]
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
File without changes
@@ -0,0 +1,56 @@
1
+ """All doc.cheap tools behind one client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from doc_cheap import API_KEY_ENV, Client
6
+ from langchain_core.tools import BaseTool, BaseToolkit
7
+ from langchain_core.utils import secret_from_env
8
+ from pydantic import ConfigDict, Field, PrivateAttr, SecretStr
9
+
10
+ from .tools import (
11
+ _USER_AGENT,
12
+ DocCheapDeleteScan,
13
+ DocCheapGetScan,
14
+ DocCheapGetUsage,
15
+ DocCheapListScans,
16
+ DocCheapScanDocument,
17
+ )
18
+
19
+
20
+ class DocCheapToolkit(BaseToolkit):
21
+ """The five doc.cheap tools, sharing one client and its connections.
22
+
23
+ The API key is the ``api_key`` argument, else the ``DOC_CHEAP_API_KEY``
24
+ environment variable. Pass ``include_delete=False`` to leave out the tool
25
+ that deletes stored results.
26
+ """
27
+
28
+ model_config = ConfigDict(arbitrary_types_allowed=True)
29
+
30
+ api_key: SecretStr | None = Field(default_factory=secret_from_env(API_KEY_ENV, default=None))
31
+ base_url: str | None = None
32
+ client: Client | None = Field(default=None, exclude=True)
33
+ include_delete: bool = True
34
+
35
+ _owned_client: Client | None = PrivateAttr(default=None)
36
+
37
+ def _shared_client(self) -> Client:
38
+ if self.client is not None:
39
+ return self.client
40
+ if self._owned_client is None:
41
+ key = self.api_key.get_secret_value() if self.api_key is not None else None
42
+ self._owned_client = Client(key, base_url=self.base_url, user_agent=_USER_AGENT)
43
+ return self._owned_client
44
+
45
+ def get_tools(self) -> list[BaseTool]:
46
+ """Returns the tools, all sending their requests through one client."""
47
+ client = self._shared_client()
48
+ tools: list[BaseTool] = [
49
+ DocCheapScanDocument(client=client),
50
+ DocCheapGetScan(client=client),
51
+ DocCheapListScans(client=client),
52
+ DocCheapGetUsage(client=client),
53
+ ]
54
+ if self.include_delete:
55
+ tools.append(DocCheapDeleteScan(client=client))
56
+ return tools
@@ -0,0 +1,207 @@
1
+ """LangChain tools that call the doc.cheap document-recognition API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any
7
+
8
+ from doc_cheap import API_KEY_ENV, Client, DocCheapError
9
+ from langchain_core.callbacks import CallbackManagerForToolRun
10
+ from langchain_core.tools import BaseTool, ToolException
11
+ from langchain_core.utils import secret_from_env
12
+ from pydantic import BaseModel, ConfigDict, Field, PrivateAttr, SecretStr, model_validator
13
+
14
+ from ._version import __version__
15
+
16
+ _USER_AGENT = f"langchain-doccheap/{__version__}"
17
+
18
+
19
+ def _to_json(value: Any) -> str:
20
+ # Tool output goes back to a chat model as text, so the API's JSON answer
21
+ # is passed through as JSON rather than as a Python repr.
22
+ return json.dumps(value, ensure_ascii=False)
23
+
24
+
25
+ class _DocCheapTool(BaseTool):
26
+ """Shared configuration of the doc.cheap tools.
27
+
28
+ The API key is the ``api_key`` argument, else the ``DOC_CHEAP_API_KEY``
29
+ environment variable. A ``client`` passed in is used as given and stays
30
+ the caller's to close; otherwise the tool creates one on first use.
31
+ """
32
+
33
+ model_config = ConfigDict(arbitrary_types_allowed=True)
34
+
35
+ api_key: SecretStr | None = Field(default_factory=secret_from_env(API_KEY_ENV, default=None))
36
+ """The doc.cheap API key; ``sk_sandbox_public`` works without an account."""
37
+
38
+ base_url: str | None = None
39
+ """The API address; the client's default when omitted."""
40
+
41
+ client: Client | None = Field(default=None, exclude=True)
42
+ """A ready ``doc_cheap.Client`` to send the requests through."""
43
+
44
+ _owned_client: Client | None = PrivateAttr(default=None)
45
+
46
+ def __init__(self, **kwargs: Any) -> None:
47
+ # An API error goes back to the model as the tool's answer, so an
48
+ # agent can react to it, unless the caller chose otherwise.
49
+ kwargs.setdefault("handle_tool_error", True)
50
+ super().__init__(**kwargs)
51
+
52
+ def _client(self) -> Client:
53
+ if self.client is not None:
54
+ return self.client
55
+ if self._owned_client is None:
56
+ key = self.api_key.get_secret_value() if self.api_key is not None else None
57
+ self._owned_client = Client(key, base_url=self.base_url, user_agent=_USER_AGENT)
58
+ return self._owned_client
59
+
60
+ def _call(self, operation: str, **kwargs: Any) -> str:
61
+ try:
62
+ result = getattr(self._client(), operation)(**kwargs)
63
+ except DocCheapError as err:
64
+ raise ToolException(f"doc.cheap error: {err}") from err
65
+ return _to_json(result)
66
+
67
+
68
+ class ScanDocumentInput(BaseModel):
69
+ """Arguments of :class:`DocCheapScanDocument`."""
70
+
71
+ image_path: str | None = Field(
72
+ default=None,
73
+ description="Path of a local JPEG or PNG file holding the document.",
74
+ )
75
+ image_base64: str | None = Field(
76
+ default=None,
77
+ description="The JPEG or PNG image as base64 text, with or without a data: prefix.",
78
+ )
79
+ reference: str | None = Field(
80
+ default=None,
81
+ max_length=128,
82
+ description="An optional label of your own, stored with the result.",
83
+ )
84
+ expect_country: str | None = Field(
85
+ default=None,
86
+ pattern=r"^[A-Z]{3}$",
87
+ description="Optional ISO 3166-1 alpha-3 code of the issuing country, e.g. GBR.",
88
+ )
89
+
90
+ @model_validator(mode="after")
91
+ def _one_image(self) -> ScanDocumentInput:
92
+ if (self.image_path is None) == (self.image_base64 is None):
93
+ raise ValueError("give exactly one of image_path or image_base64")
94
+ return self
95
+
96
+
97
+ class DocCheapScanDocument(_DocCheapTool):
98
+ """Reads a passport, national ID card or driving licence into JSON."""
99
+
100
+ name: str = "doc_cheap_scan_document"
101
+ description: str = (
102
+ "Reads a photo or scan of a passport, national ID card or driving licence "
103
+ "and returns the printed fields (name, date of birth, document number, "
104
+ "expiry, machine-readable zone) as JSON. Give image_path or image_base64. "
105
+ "One recognised document costs one credit; an image with no readable "
106
+ "document costs nothing and comes back with billed set to false."
107
+ )
108
+ args_schema: type[BaseModel] = ScanDocumentInput
109
+
110
+ def _run(
111
+ self,
112
+ image_path: str | None = None,
113
+ image_base64: str | None = None,
114
+ reference: str | None = None,
115
+ expect_country: str | None = None,
116
+ run_manager: CallbackManagerForToolRun | None = None,
117
+ ) -> str:
118
+ return self._call(
119
+ "recognize",
120
+ path=image_path,
121
+ image_base64=image_base64,
122
+ reference=reference,
123
+ expect_country=expect_country,
124
+ )
125
+
126
+
127
+ class ScanIdInput(BaseModel):
128
+ """Arguments of the tools that act on one stored scan."""
129
+
130
+ scan_id: str = Field(min_length=1, description="The id of a scan, as returned by a scan.")
131
+
132
+
133
+ class DocCheapGetScan(_DocCheapTool):
134
+ """Returns a stored scan result."""
135
+
136
+ name: str = "doc_cheap_get_scan"
137
+ description: str = (
138
+ "Returns a stored doc.cheap scan result by its id, as JSON. Results are "
139
+ "stored only for live keys with a retention window. Costs nothing."
140
+ )
141
+ args_schema: type[BaseModel] = ScanIdInput
142
+
143
+ def _run(self, scan_id: str, run_manager: CallbackManagerForToolRun | None = None) -> str:
144
+ return self._call("get_scan", scan_id=scan_id)
145
+
146
+
147
+ class ListScansInput(BaseModel):
148
+ """Arguments of :class:`DocCheapListScans`."""
149
+
150
+ limit: int | None = Field(
151
+ default=None, ge=1, le=100, description="How many results to return, 1 to 100."
152
+ )
153
+ cursor: str | None = Field(
154
+ default=None,
155
+ max_length=256,
156
+ description="The next_cursor value of the previous page, for the next page.",
157
+ )
158
+
159
+
160
+ class DocCheapListScans(_DocCheapTool):
161
+ """Lists stored scan results, newest first."""
162
+
163
+ name: str = "doc_cheap_list_scans"
164
+ description: str = (
165
+ "Lists stored doc.cheap scan results, newest first, as JSON with a "
166
+ "next_cursor for the next page. Costs nothing."
167
+ )
168
+ args_schema: type[BaseModel] = ListScansInput
169
+
170
+ def _run(
171
+ self,
172
+ limit: int | None = None,
173
+ cursor: str | None = None,
174
+ run_manager: CallbackManagerForToolRun | None = None,
175
+ ) -> str:
176
+ return self._call("list_scans", limit=limit, cursor=cursor)
177
+
178
+
179
+ class DocCheapDeleteScan(_DocCheapTool):
180
+ """Deletes a stored scan result."""
181
+
182
+ name: str = "doc_cheap_delete_scan"
183
+ description: str = (
184
+ "Deletes a stored doc.cheap scan result by its id. It cannot be undone. Costs nothing."
185
+ )
186
+ args_schema: type[BaseModel] = ScanIdInput
187
+
188
+ def _run(self, scan_id: str, run_manager: CallbackManagerForToolRun | None = None) -> str:
189
+ return self._call("delete_scan", scan_id=scan_id)
190
+
191
+
192
+ class UsageInput(BaseModel):
193
+ """The usage tool takes no arguments."""
194
+
195
+
196
+ class DocCheapGetUsage(_DocCheapTool):
197
+ """Returns the account's credits and scan counters."""
198
+
199
+ name: str = "doc_cheap_get_usage"
200
+ description: str = (
201
+ "Returns this month's free doc.cheap credits, the paid credits, the "
202
+ "credits spent and the scan counters, as JSON. Costs nothing."
203
+ )
204
+ args_schema: type[BaseModel] = UsageInput
205
+
206
+ def _run(self, run_manager: CallbackManagerForToolRun | None = None) -> str:
207
+ return self._call("usage")
@@ -0,0 +1,127 @@
1
+ Metadata-Version: 2.5
2
+ Name: langchain-doccheap
3
+ Version: 0.1.0
4
+ Summary: LangChain tools for doc.cheap: read passports, ID cards and driver's licences into JSON.
5
+ Project-URL: Homepage, https://doc.cheap
6
+ Project-URL: Documentation, https://doc.cheap/docs
7
+ Project-URL: Source, https://gitlab.com/doccheap/langchain-doccheap
8
+ Project-URL: Changelog, https://gitlab.com/doccheap/langchain-doccheap/-/blob/main/CHANGELOG.md
9
+ Author-email: Teoh Chin Heng <admin@doc.cheap>
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: doc.cheap,document-recognition,id-card,kyc,langchain,mrz,ocr,passport,tools
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
23
+ Classifier: Typing :: Typed
24
+ Requires-Python: >=3.10
25
+ Requires-Dist: doc-cheap<1,>=0.1.0
26
+ Requires-Dist: langchain-core<2,>=1.0
27
+ Provides-Extra: dev
28
+ Requires-Dist: langchain-tests<2,>=1.0; extra == 'dev'
29
+ Requires-Dist: mypy>=1.11; extra == 'dev'
30
+ Requires-Dist: pytest-cov>=5; extra == 'dev'
31
+ Requires-Dist: pytest>=8; extra == 'dev'
32
+ Requires-Dist: ruff>=0.6; extra == 'dev'
33
+ Provides-Extra: test
34
+ Requires-Dist: langchain-tests<2,>=1.0; extra == 'test'
35
+ Requires-Dist: pytest-cov>=5; extra == 'test'
36
+ Requires-Dist: pytest>=8; extra == 'test'
37
+ Description-Content-Type: text/markdown
38
+
39
+ # langchain-doccheap
40
+
41
+ [![PyPI](https://img.shields.io/pypi/v/langchain-doccheap.svg)](https://pypi.org/project/langchain-doccheap/)
42
+
43
+ [LangChain](https://python.langchain.com/) tools for
44
+ [doc.cheap](https://doc.cheap): an agent gives them a photo or scan of a
45
+ passport, national ID card or driving licence and gets back the printed fields –
46
+ name, date of birth, document number, expiry, the machine-readable zone – as
47
+ JSON.
48
+
49
+ One recognised document costs one credit, $0.01. Registering gives 100 free
50
+ documents every month. An unreadable image, an empty frame or an unsupported
51
+ document type costs nothing, and every answer says whether it was billed.
52
+
53
+ The package needs Python 3.10 or later. It is built on the
54
+ [doc-cheap](https://pypi.org/project/doc-cheap/) client and `langchain-core` 1.x.
55
+
56
+ ## Installation
57
+
58
+ ```sh
59
+ pip install langchain-doccheap
60
+ ```
61
+
62
+ ## The tools
63
+
64
+ | Tool | Name the model sees | What it does |
65
+ | --- | --- | --- |
66
+ | `DocCheapScanDocument` | `doc_cheap_scan_document` | Reads one JPEG or PNG image, from `image_path` or `image_base64`, with an optional `reference` label and `expect_country` (ISO 3166-1 alpha-3). |
67
+ | `DocCheapGetScan` | `doc_cheap_get_scan` | Returns a stored result by `scan_id`. |
68
+ | `DocCheapListScans` | `doc_cheap_list_scans` | Returns one page of stored results (`limit`, `cursor`). |
69
+ | `DocCheapDeleteScan` | `doc_cheap_delete_scan` | Deletes a stored result by `scan_id`. |
70
+ | `DocCheapGetUsage` | `doc_cheap_get_usage` | Returns this month's free credits, the paid credits, the credits spent and the scan counters. |
71
+
72
+ Every tool returns the API's answer as a JSON string. An API error – an unknown
73
+ scan, a used-up rate limit, a wrong key – comes back to the model as a short
74
+ text such as `doc.cheap error: 404 scan_not_found: …` instead of stopping the
75
+ agent; pass `handle_tool_error=False` to have it raised as a `ToolException`.
76
+
77
+ ## Quick start
78
+
79
+ ```python
80
+ from langchain_doccheap import DocCheapScanDocument
81
+
82
+ scan = DocCheapScanDocument(api_key="sk_sandbox_public")
83
+ print(scan.invoke({"image_path": "passport.jpg"}))
84
+ ```
85
+
86
+ With an agent, take all five tools from the toolkit. They share one client and
87
+ its connections:
88
+
89
+ ```python
90
+ from langchain.agents import create_agent
91
+ from langchain_doccheap import DocCheapToolkit
92
+
93
+ tools = DocCheapToolkit().get_tools() # reads DOC_CHEAP_API_KEY
94
+ agent = create_agent("openai:gpt-4.1-mini", tools)
95
+ agent.invoke({"messages": [{"role": "user", "content": "Read the passport in ./passport.jpg"}]})
96
+ ```
97
+
98
+ `DocCheapToolkit(include_delete=False)` leaves out the tool that deletes stored
99
+ results.
100
+
101
+ ## API keys
102
+
103
+ - **Live key** – `sk_live_…`, created in the
104
+ [doc.cheap cabinet](https://doc.cheap/docs/concepts/api-keys-and-sessions).
105
+ - **Sandbox key** – `sk_sandbox_public` works without an account. It gives 10
106
+ free recognised documents per address in all, and at most 10 requests per
107
+ address an hour, whatever their answer.
108
+
109
+ Without `api_key` the tools read the key from the `DOC_CHEAP_API_KEY`
110
+ environment variable. `base_url` (or `DOC_CHEAP_API_BASE`) points them at
111
+ another address. To control timeouts, proxies or connection pooling, build a
112
+ `doc_cheap.Client` yourself and pass it as `client=`; the tools leave it open.
113
+
114
+ **Stored results.** A result is stored only when the scan was made with a live
115
+ key under a non-zero retention window. Under the sandbox key nothing is stored,
116
+ so getting or deleting a scan answers `scan_not_found`.
117
+
118
+ ## Resources
119
+
120
+ - [doc.cheap documentation](https://doc.cheap/docs)
121
+ - [Your first recognition](https://doc.cheap/docs/start/first-recognition)
122
+ - [API reference](https://doc.cheap/docs/reference)
123
+ - [The doc-cheap Python client](https://pypi.org/project/doc-cheap/)
124
+
125
+ ## License
126
+
127
+ [MIT](LICENSE)
@@ -0,0 +1,9 @@
1
+ langchain_doccheap/__init__.py,sha256=r4dY1eUiYxrDAwF7_lCJBqDnEoB6wjQmTIYCdNsYlNg,620
2
+ langchain_doccheap/_version.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
3
+ langchain_doccheap/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ langchain_doccheap/toolkit.py,sha256=QvhSgoAR9oGnDi7aoFoKZM2zFnSZObJBzN7NPjrprF4,1969
5
+ langchain_doccheap/tools.py,sha256=Bjt_hzTyh2aeuxBi-heoMovK8AzaMSyOEO4QENVBdmo,7325
6
+ langchain_doccheap-0.1.0.dist-info/METADATA,sha256=r4sJ6q-0JR8nxtslU3axQLHW2ou8maoKRZ2V41TsMds,5413
7
+ langchain_doccheap-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
8
+ langchain_doccheap-0.1.0.dist-info/licenses/LICENSE,sha256=6cIUipszzlbgE6uIjGi_fU3qNMHyGdK6PSQ8NGw1Tno,1076
9
+ langchain_doccheap-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Document Cheap Inc.
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.