langchain-verdo 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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Aethon Digital FZCO
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,124 @@
1
+ Metadata-Version: 2.4
2
+ Name: langchain-verdo
3
+ Version: 0.1.0
4
+ Summary: LangChain tools for Verdo: structured team decisions with deadlines, routing and webhooks
5
+ Author: Verdo
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://verdo.ink
8
+ Project-URL: Documentation, https://verdo.ink/agents
9
+ Keywords: langchain,verdo,decisions,approvals,human-in-the-loop,agents
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Topic :: Software Development :: Libraries
13
+ Requires-Python: >=3.9
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: langchain-core<2.0,>=0.3.0
17
+ Requires-Dist: httpx>=0.25.0
18
+ Provides-Extra: test
19
+ Requires-Dist: pytest>=8; extra == "test"
20
+ Requires-Dist: pytest-asyncio>=0.23; extra == "test"
21
+ Requires-Dist: respx>=0.21; extra == "test"
22
+ Dynamic: license-file
23
+
24
+ # langchain-verdo
25
+
26
+ LangChain tools for [Verdo](https://verdo.ink): structured team decisions with deadlines, routing and webhooks.
27
+
28
+ Use it when your agent needs a person to approve, pick or sign off on something, and needs a structured result rather than a discussion. **The agent proposes; a person decides.** No tool invites people, approves, rejects or settles a decision.
29
+
30
+ ## Install
31
+
32
+ ```bash
33
+ pip install langchain-verdo
34
+ ```
35
+
36
+ ## Set up
37
+
38
+ Create a **full-access** API key in Verdo (Settings > API keys). It starts with `vdok_`.
39
+
40
+ ```bash
41
+ export VERDO_API_KEY=vdok_...
42
+ ```
43
+
44
+ Or pass `api_key=` to the toolkit or to any tool. The key is held as a `SecretStr`, so it doesn't appear in reprs, logs or traces.
45
+
46
+ ## Use
47
+
48
+ ```python
49
+ from langchain_verdo import VerdoToolkit
50
+
51
+ tools = VerdoToolkit().get_tools()
52
+ ```
53
+
54
+ With an agent:
55
+
56
+ ```python
57
+ from langchain.agents import create_agent
58
+
59
+ agent = create_agent(model, tools=tools) # any tool-calling chat model
60
+ agent.invoke({"messages": [("user", "Ask the team whether we ship the new onboarding this sprint.")]})
61
+ ```
62
+
63
+ Or call a tool directly:
64
+
65
+ ```python
66
+ import json
67
+ from langchain_verdo import CreateDecisionTool, CheckDecisionTool
68
+
69
+ created = json.loads(CreateDecisionTool().invoke({
70
+ "title": "Ship the redesigned onboarding this sprint?",
71
+ "options": ["Ship it", "One more round of testing", "Descope"],
72
+ "tags": ["engineering"], # a routing rule on this tag assigns its approver
73
+ "idempotency_key": "onboarding-sprint-47",
74
+ "source_agent": "sprint-planner",
75
+ }))
76
+ print(created["url"]) # send this to the person who decides
77
+
78
+ status = json.loads(CheckDecisionTool().invoke({"id": created["id"]}))
79
+ print(status["status"], status["outcome"])
80
+ ```
81
+
82
+ ## Tools
83
+
84
+ | Tool | What it does |
85
+ |---|---|
86
+ | `verdo_create_decision` | Proposes a decision. It invites nobody: the decision opens in the Verdo dashboard, and tags can route it to an approver configured in Verdo. With an `idempotency_key`, a retry returns the same open decision (`created: false`). |
87
+ | `verdo_check_decision` | Status, outcome once decided, votes per option, owner, dashboard link, `request_fingerprint`, `notification_status`, `routing_rule_label`. |
88
+ | `verdo_list_decisions` | Up to 25 decisions, filtered by title words, status, tags, `source_agent` or notification status. |
89
+ | `verdo_search_decisions` | Past decided decisions by title words, newest first. |
90
+ | `verdo_get_precedent` | One past decision's record, with related decisions. |
91
+ | `verdo_cancel_decision` | Withdraws a draft or open decision this key created. |
92
+ | `verdo_edit_decision` | Revises a draft or open decision this key created. A change voids the votes cast so far. |
93
+
94
+ Every tool returns a JSON string. Past decisions come back with `execution_authorized: false`: they're records, not consent to repeat them.
95
+
96
+ Async is supported (`ainvoke`).
97
+
98
+ ## Errors
99
+
100
+ A failed call raises `VerdoAPIError` (a `ToolException`) with a sentence the agent can act on, such as a rate limit with its retry time or a draft-only key that can't create. Set `handle_tool_error=True` on a tool to return that sentence to the agent instead of raising it.
101
+
102
+ ## Webhooks
103
+
104
+ Instead of polling `verdo_check_decision`, you can subscribe a public https URL. Make one subscription per event: `decision.settled`, `decision.rejected`, `decision.cancelled`, `decision.expired` or `decision.escalated`.
105
+
106
+ ```bash
107
+ curl -X POST https://verdo.ink/api/v1/webhooks/subscribe \
108
+ -H "Authorization: Bearer $VERDO_API_KEY" -H "Content-Type: application/json" \
109
+ -d '{"event_type":"decision.settled","url":"https://your-server.example/webhook"}'
110
+ ```
111
+
112
+ The response includes the `signing_secret`, and it's shown only once. Check every delivery's `X-Verdo-Signature` (HMAC-SHA256 over the `X-Verdo-Timestamp` and the body) before you trust it.
113
+
114
+ ## Development
115
+
116
+ ```bash
117
+ pip install -e ".[test]"
118
+ pytest tests/ --ignore=tests/integration_tests
119
+ VERDO_API_KEY=vdok_... pytest tests/integration_tests # live; creates and cancels decisions
120
+ ```
121
+
122
+ ## License
123
+
124
+ MIT
@@ -0,0 +1,101 @@
1
+ # langchain-verdo
2
+
3
+ LangChain tools for [Verdo](https://verdo.ink): structured team decisions with deadlines, routing and webhooks.
4
+
5
+ Use it when your agent needs a person to approve, pick or sign off on something, and needs a structured result rather than a discussion. **The agent proposes; a person decides.** No tool invites people, approves, rejects or settles a decision.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pip install langchain-verdo
11
+ ```
12
+
13
+ ## Set up
14
+
15
+ Create a **full-access** API key in Verdo (Settings > API keys). It starts with `vdok_`.
16
+
17
+ ```bash
18
+ export VERDO_API_KEY=vdok_...
19
+ ```
20
+
21
+ Or pass `api_key=` to the toolkit or to any tool. The key is held as a `SecretStr`, so it doesn't appear in reprs, logs or traces.
22
+
23
+ ## Use
24
+
25
+ ```python
26
+ from langchain_verdo import VerdoToolkit
27
+
28
+ tools = VerdoToolkit().get_tools()
29
+ ```
30
+
31
+ With an agent:
32
+
33
+ ```python
34
+ from langchain.agents import create_agent
35
+
36
+ agent = create_agent(model, tools=tools) # any tool-calling chat model
37
+ agent.invoke({"messages": [("user", "Ask the team whether we ship the new onboarding this sprint.")]})
38
+ ```
39
+
40
+ Or call a tool directly:
41
+
42
+ ```python
43
+ import json
44
+ from langchain_verdo import CreateDecisionTool, CheckDecisionTool
45
+
46
+ created = json.loads(CreateDecisionTool().invoke({
47
+ "title": "Ship the redesigned onboarding this sprint?",
48
+ "options": ["Ship it", "One more round of testing", "Descope"],
49
+ "tags": ["engineering"], # a routing rule on this tag assigns its approver
50
+ "idempotency_key": "onboarding-sprint-47",
51
+ "source_agent": "sprint-planner",
52
+ }))
53
+ print(created["url"]) # send this to the person who decides
54
+
55
+ status = json.loads(CheckDecisionTool().invoke({"id": created["id"]}))
56
+ print(status["status"], status["outcome"])
57
+ ```
58
+
59
+ ## Tools
60
+
61
+ | Tool | What it does |
62
+ |---|---|
63
+ | `verdo_create_decision` | Proposes a decision. It invites nobody: the decision opens in the Verdo dashboard, and tags can route it to an approver configured in Verdo. With an `idempotency_key`, a retry returns the same open decision (`created: false`). |
64
+ | `verdo_check_decision` | Status, outcome once decided, votes per option, owner, dashboard link, `request_fingerprint`, `notification_status`, `routing_rule_label`. |
65
+ | `verdo_list_decisions` | Up to 25 decisions, filtered by title words, status, tags, `source_agent` or notification status. |
66
+ | `verdo_search_decisions` | Past decided decisions by title words, newest first. |
67
+ | `verdo_get_precedent` | One past decision's record, with related decisions. |
68
+ | `verdo_cancel_decision` | Withdraws a draft or open decision this key created. |
69
+ | `verdo_edit_decision` | Revises a draft or open decision this key created. A change voids the votes cast so far. |
70
+
71
+ Every tool returns a JSON string. Past decisions come back with `execution_authorized: false`: they're records, not consent to repeat them.
72
+
73
+ Async is supported (`ainvoke`).
74
+
75
+ ## Errors
76
+
77
+ A failed call raises `VerdoAPIError` (a `ToolException`) with a sentence the agent can act on, such as a rate limit with its retry time or a draft-only key that can't create. Set `handle_tool_error=True` on a tool to return that sentence to the agent instead of raising it.
78
+
79
+ ## Webhooks
80
+
81
+ Instead of polling `verdo_check_decision`, you can subscribe a public https URL. Make one subscription per event: `decision.settled`, `decision.rejected`, `decision.cancelled`, `decision.expired` or `decision.escalated`.
82
+
83
+ ```bash
84
+ curl -X POST https://verdo.ink/api/v1/webhooks/subscribe \
85
+ -H "Authorization: Bearer $VERDO_API_KEY" -H "Content-Type: application/json" \
86
+ -d '{"event_type":"decision.settled","url":"https://your-server.example/webhook"}'
87
+ ```
88
+
89
+ The response includes the `signing_secret`, and it's shown only once. Check every delivery's `X-Verdo-Signature` (HMAC-SHA256 over the `X-Verdo-Timestamp` and the body) before you trust it.
90
+
91
+ ## Development
92
+
93
+ ```bash
94
+ pip install -e ".[test]"
95
+ pytest tests/ --ignore=tests/integration_tests
96
+ VERDO_API_KEY=vdok_... pytest tests/integration_tests # live; creates and cancels decisions
97
+ ```
98
+
99
+ ## License
100
+
101
+ MIT
@@ -0,0 +1,29 @@
1
+ """LangChain tools for Verdo: structured team decisions, with routing and webhooks."""
2
+
3
+ from langchain_verdo._api import VerdoAPIError, VerdoClient
4
+ from langchain_verdo.toolkit import VerdoToolkit
5
+ from langchain_verdo.tools import (
6
+ CancelDecisionTool,
7
+ CheckDecisionTool,
8
+ CreateDecisionTool,
9
+ EditDecisionTool,
10
+ GetPrecedentTool,
11
+ ListDecisionsTool,
12
+ SearchDecisionsTool,
13
+ )
14
+
15
+ __version__ = "0.1.0"
16
+
17
+ __all__ = [
18
+ "CancelDecisionTool",
19
+ "CheckDecisionTool",
20
+ "CreateDecisionTool",
21
+ "EditDecisionTool",
22
+ "GetPrecedentTool",
23
+ "ListDecisionsTool",
24
+ "SearchDecisionsTool",
25
+ "VerdoAPIError",
26
+ "VerdoClient",
27
+ "VerdoToolkit",
28
+ "__version__",
29
+ ]
@@ -0,0 +1,138 @@
1
+ """Shared HTTP client for the Verdo REST API (httpx, sync and async).
2
+
3
+ The tools call the same routes as the verdo-mcp package:
4
+
5
+ - ``/zapier/decisions`` (create, read, list, search, precedent)
6
+ - ``/v1/decisions/{id}/cancel`` and ``/v1/decisions/{id}/edit`` (the caller's own decisions)
7
+
8
+ No route here invites, notifies, approves, rejects or settles: a person decides in Verdo.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from typing import Any, Dict, Optional
14
+
15
+ import httpx
16
+ from langchain_core.tools import ToolException
17
+
18
+ DEFAULT_API_BASE = "https://verdo.ink/api"
19
+ DEFAULT_TIMEOUT = 30.0
20
+
21
+ # Remediation for the error codes an agent can act on (mirrors verdo-mcp).
22
+ _HINTS: Dict[str, str] = {
23
+ "workspace_read_only": "This workspace's plan has lapsed (read-only). The workspace owner can reactivate it at verdo.ink/dashboard/settings/billing.",
24
+ "upgrade_required": "This feature needs a Pro or Business plan. The workspace owner can upgrade at verdo.ink/dashboard/settings/billing.",
25
+ "draft_only_key": "This API key is draft-only. Creating, cancelling and editing decisions need a full-access key (verdo.ink/dashboard/settings > API keys).",
26
+ "invalid or missing API key": "The API key is invalid, revoked or missing. Create one at verdo.ink/dashboard/settings > API keys and pass it as api_key or VERDO_API_KEY.",
27
+ }
28
+
29
+
30
+ class VerdoAPIError(ToolException):
31
+ """A Verdo API call failed. ``str(err)`` is a sentence an agent can act on."""
32
+
33
+ def __init__(
34
+ self,
35
+ action: str,
36
+ status_code: int,
37
+ code: Optional[str] = None,
38
+ message: Optional[str] = None,
39
+ retry_after_seconds: Optional[float] = None,
40
+ ) -> None:
41
+ self.action = action
42
+ self.status_code = status_code
43
+ self.code = code
44
+ self.retry_after_seconds = retry_after_seconds
45
+ if status_code >= 500:
46
+ text = f"Could not {action}: Verdo returned an internal error ({status_code}). This is not the caller's fault; try again in 30 seconds."
47
+ else:
48
+ detail = _HINTS.get(code or "") or _HINTS.get(message or "") or message or code or "unknown error"
49
+ text = f"Could not {action} (HTTP {status_code}): {detail}"
50
+ if status_code == 429:
51
+ wait = f" Retry in {retry_after_seconds:g}s." if retry_after_seconds is not None else " Retry later."
52
+ text = f"Could not {action}: rate limited (HTTP 429).{wait}"
53
+ super().__init__(text)
54
+
55
+
56
+ def _raise_for(action: str, response: httpx.Response) -> None:
57
+ if response.is_success:
58
+ return
59
+ try:
60
+ body = response.json()
61
+ except ValueError:
62
+ body = {}
63
+ if not isinstance(body, dict):
64
+ body = {}
65
+ retry: Optional[float] = None
66
+ raw_retry = body.get("retry_after_seconds", response.headers.get("retry-after"))
67
+ if raw_retry is not None:
68
+ try:
69
+ retry = float(raw_retry)
70
+ except (TypeError, ValueError):
71
+ retry = None
72
+ code = body.get("error")
73
+ message = body.get("message")
74
+ raise VerdoAPIError(
75
+ action,
76
+ response.status_code,
77
+ code=str(code) if code is not None else None,
78
+ message=str(message) if message is not None else None,
79
+ retry_after_seconds=retry,
80
+ )
81
+
82
+
83
+ def _json(response: httpx.Response) -> Dict[str, Any]:
84
+ try:
85
+ data = response.json()
86
+ except ValueError:
87
+ return {}
88
+ return data if isinstance(data, dict) else {}
89
+
90
+
91
+ class VerdoClient:
92
+ """Thin client: auth header, base URL, timeouts and agent-friendly errors."""
93
+
94
+ def __init__(self, api_key: str, api_base: str = DEFAULT_API_BASE, timeout: float = DEFAULT_TIMEOUT) -> None:
95
+ if not api_key:
96
+ raise ValueError("A Verdo API key is required (vdok_...). Pass api_key or set VERDO_API_KEY.")
97
+ self._api_key = api_key
98
+ self.api_base = api_base.rstrip("/")
99
+ self.timeout = timeout
100
+
101
+ def __repr__(self) -> str: # never show the key
102
+ return f"VerdoClient(api_base={self.api_base!r})"
103
+
104
+ def _headers(self) -> Dict[str, str]:
105
+ return {
106
+ "Authorization": f"Bearer {self._api_key}",
107
+ "Content-Type": "application/json",
108
+ "User-Agent": "langchain-verdo",
109
+ }
110
+
111
+ def _url(self, path: str) -> str:
112
+ return f"{self.api_base}{path}"
113
+
114
+ # ---- sync ----
115
+
116
+ def get(self, path: str, action: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
117
+ r = httpx.get(self._url(path), params=params, headers=self._headers(), timeout=self.timeout)
118
+ _raise_for(action, r)
119
+ return _json(r)
120
+
121
+ def post(self, path: str, action: str, data: Dict[str, Any]) -> Dict[str, Any]:
122
+ r = httpx.post(self._url(path), json=data, headers=self._headers(), timeout=self.timeout)
123
+ _raise_for(action, r)
124
+ return _json(r)
125
+
126
+ # ---- async ----
127
+
128
+ async def aget(self, path: str, action: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
129
+ async with httpx.AsyncClient(timeout=self.timeout) as client:
130
+ r = await client.get(self._url(path), params=params, headers=self._headers())
131
+ _raise_for(action, r)
132
+ return _json(r)
133
+
134
+ async def apost(self, path: str, action: str, data: Dict[str, Any]) -> Dict[str, Any]:
135
+ async with httpx.AsyncClient(timeout=self.timeout) as client:
136
+ r = await client.post(self._url(path), json=data, headers=self._headers())
137
+ _raise_for(action, r)
138
+ return _json(r)
@@ -0,0 +1,45 @@
1
+ from typing import List
2
+
3
+ from langchain_core.tools import BaseTool, BaseToolkit
4
+ from pydantic import Field, SecretStr
5
+
6
+ from langchain_verdo.tools import (
7
+ CancelDecisionTool,
8
+ CheckDecisionTool,
9
+ CreateDecisionTool,
10
+ EditDecisionTool,
11
+ GetPrecedentTool,
12
+ ListDecisionsTool,
13
+ SearchDecisionsTool,
14
+ )
15
+ from langchain_verdo.tools._base import _env_base, _env_key
16
+
17
+
18
+ class VerdoToolkit(BaseToolkit):
19
+ """All seven Verdo tools, sharing one API key.
20
+
21
+ The agent proposes; a person decides. No tool invites, notifies, approves, rejects or
22
+ settles a decision.
23
+
24
+ Example:
25
+ .. code-block:: python
26
+
27
+ from langchain_verdo import VerdoToolkit
28
+
29
+ tools = VerdoToolkit().get_tools() # reads VERDO_API_KEY
30
+ """
31
+
32
+ api_key: SecretStr = Field(default_factory=_env_key)
33
+ api_base: str = Field(default_factory=_env_base)
34
+
35
+ def get_tools(self) -> List[BaseTool]:
36
+ kw = {"api_key": self.api_key, "api_base": self.api_base}
37
+ return [
38
+ CreateDecisionTool(**kw),
39
+ CheckDecisionTool(**kw),
40
+ ListDecisionsTool(**kw),
41
+ SearchDecisionsTool(**kw),
42
+ GetPrecedentTool(**kw),
43
+ CancelDecisionTool(**kw),
44
+ EditDecisionTool(**kw),
45
+ ]
@@ -0,0 +1,24 @@
1
+ from langchain_verdo.tools.cancel_decision import CancelDecisionInput, CancelDecisionTool
2
+ from langchain_verdo.tools.check_decision import CheckDecisionInput, CheckDecisionTool
3
+ from langchain_verdo.tools.create_decision import CreateDecisionInput, CreateDecisionTool
4
+ from langchain_verdo.tools.edit_decision import EditDecisionInput, EditDecisionTool
5
+ from langchain_verdo.tools.get_precedent import GetPrecedentInput, GetPrecedentTool
6
+ from langchain_verdo.tools.list_decisions import ListDecisionsInput, ListDecisionsTool
7
+ from langchain_verdo.tools.search_decisions import SearchDecisionsInput, SearchDecisionsTool
8
+
9
+ __all__ = [
10
+ "CancelDecisionInput",
11
+ "CancelDecisionTool",
12
+ "CheckDecisionInput",
13
+ "CheckDecisionTool",
14
+ "CreateDecisionInput",
15
+ "CreateDecisionTool",
16
+ "EditDecisionInput",
17
+ "EditDecisionTool",
18
+ "GetPrecedentInput",
19
+ "GetPrecedentTool",
20
+ "ListDecisionsInput",
21
+ "ListDecisionsTool",
22
+ "SearchDecisionsInput",
23
+ "SearchDecisionsTool",
24
+ ]
@@ -0,0 +1,73 @@
1
+ """Common base for the Verdo tools: credentials, base URL and the sync/async request path."""
2
+
3
+ import json
4
+ import os
5
+ from dataclasses import dataclass, field
6
+ from typing import Any, Dict, Optional
7
+ from urllib.parse import quote
8
+
9
+ from langchain_core.callbacks import AsyncCallbackManagerForToolRun, CallbackManagerForToolRun
10
+ from langchain_core.tools import BaseTool, ToolException
11
+ from pydantic import Field, SecretStr
12
+
13
+ from langchain_verdo._api import DEFAULT_API_BASE, VerdoClient
14
+
15
+
16
+ def _env_key() -> SecretStr:
17
+ return SecretStr(os.environ.get("VERDO_API_KEY", ""))
18
+
19
+
20
+ def _env_base() -> str:
21
+ return os.environ.get("VERDO_API_URL", DEFAULT_API_BASE)
22
+
23
+
24
+ def seg(value: str) -> str:
25
+ """One URL path segment (a decision ID), encoded."""
26
+ return quote(str(value), safe="")
27
+
28
+
29
+ @dataclass
30
+ class Request:
31
+ method: str # "GET" or "POST"
32
+ path: str
33
+ action: str # "create the decision": used in error messages
34
+ params: Optional[Dict[str, Any]] = None
35
+ body: Dict[str, Any] = field(default_factory=dict)
36
+
37
+
38
+ class VerdoBaseTool(BaseTool):
39
+ """Holds the API key (a SecretStr, so it never appears in reprs, logs or traces)."""
40
+
41
+ api_key: SecretStr = Field(default_factory=_env_key, description="Verdo API key (vdok_...). Defaults to VERDO_API_KEY.")
42
+ api_base: str = Field(default_factory=_env_base, description="Verdo API base URL. Defaults to VERDO_API_URL or https://verdo.ink/api.")
43
+
44
+ def _client(self) -> VerdoClient:
45
+ key = self.api_key.get_secret_value()
46
+ if not key:
47
+ raise ToolException("No Verdo API key. Pass api_key or set VERDO_API_KEY (create one at verdo.ink/dashboard/settings > API keys).")
48
+ return VerdoClient(key, self.api_base)
49
+
50
+ # Subclasses describe the call and shape the answer.
51
+ def _request(self, **kwargs: Any) -> Request: # pragma: no cover - abstract
52
+ raise NotImplementedError
53
+
54
+ def _shape(self, data: Dict[str, Any], **kwargs: Any) -> Dict[str, Any]:
55
+ return data
56
+
57
+ def _run(self, run_manager: Optional[CallbackManagerForToolRun] = None, **kwargs: Any) -> str:
58
+ req = self._request(**kwargs)
59
+ client = self._client()
60
+ if req.method == "GET":
61
+ data = client.get(req.path, req.action, params=req.params)
62
+ else:
63
+ data = client.post(req.path, req.action, req.body)
64
+ return json.dumps(self._shape(data, **kwargs))
65
+
66
+ async def _arun(self, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, **kwargs: Any) -> str:
67
+ req = self._request(**kwargs)
68
+ client = self._client()
69
+ if req.method == "GET":
70
+ data = await client.aget(req.path, req.action, params=req.params)
71
+ else:
72
+ data = await client.apost(req.path, req.action, req.body)
73
+ return json.dumps(self._shape(data, **kwargs))
@@ -0,0 +1,31 @@
1
+ from typing import Any, Dict, Optional, Type
2
+
3
+ from pydantic import BaseModel, Field
4
+
5
+ from langchain_verdo.tools._base import Request, VerdoBaseTool, seg
6
+
7
+
8
+ class CancelDecisionInput(BaseModel):
9
+ decision_id: str = Field(description="The decision id from verdo_create_decision")
10
+ reason: Optional[str] = Field(default=None, max_length=500, description="Why it is being withdrawn (shown to the people it was sent to)")
11
+
12
+
13
+ class CancelDecisionTool(VerdoBaseTool):
14
+ """Withdraw a draft or open decision this API key created. Decides nothing."""
15
+
16
+ name: str = "verdo_cancel_decision"
17
+ description: str = (
18
+ "Withdraw a draft or open Verdo decision that this API key created. It closes for good as cancelled, and "
19
+ "anyone it was sent to sees it was withdrawn. This does not decide anything: rejecting is the approver's "
20
+ "call, made in Verdo. Needs a full-access key."
21
+ )
22
+ args_schema: Type[BaseModel] = CancelDecisionInput
23
+
24
+ def _request(self, **kwargs: Any) -> Request:
25
+ body: Dict[str, Any] = {}
26
+ if kwargs.get("reason") is not None:
27
+ body["reason"] = kwargs["reason"]
28
+ return Request("POST", f"/v1/decisions/{seg(kwargs['decision_id'])}/cancel", "cancel the decision", body=body)
29
+
30
+ def _shape(self, data: Dict[str, Any], **kwargs: Any) -> Dict[str, Any]:
31
+ return {"id": data.get("id", kwargs["decision_id"]), "status": data.get("status")}
@@ -0,0 +1,43 @@
1
+ from typing import Any, Dict, Type
2
+
3
+ from pydantic import BaseModel, Field
4
+
5
+ from langchain_verdo.tools._base import Request, VerdoBaseTool, seg
6
+
7
+
8
+ class CheckDecisionInput(BaseModel):
9
+ id: str = Field(description="The decision id from verdo_create_decision")
10
+
11
+
12
+ class CheckDecisionTool(VerdoBaseTool):
13
+ """Read a decision's status and, once a person has decided, its outcome."""
14
+
15
+ name: str = "verdo_check_decision"
16
+ description: str = (
17
+ "Check a Verdo decision: its status (draft, active, decided, cancelled, rejected, ...), the outcome once a "
18
+ "person has decided, the vote count per option, the owner, the dashboard url, and the request_fingerprint "
19
+ "(compare it with the one verdo_create_decision returned), notification_status, routing_rule_label and "
20
+ "source_agent. Read-only."
21
+ )
22
+ args_schema: Type[BaseModel] = CheckDecisionInput
23
+
24
+ def _request(self, **kwargs: Any) -> Request:
25
+ return Request("GET", f"/zapier/decisions/{seg(kwargs['id'])}", "read the decision")
26
+
27
+ def _shape(self, data: Dict[str, Any], **kwargs: Any) -> Dict[str, Any]:
28
+ d = data.get("decision") or {}
29
+ return {
30
+ "id": d.get("decision_id", kwargs["id"]),
31
+ "title": d.get("title"),
32
+ "status": d.get("status"),
33
+ "outcome": d.get("outcome"),
34
+ "decided_at": d.get("decided_at"),
35
+ "owner": d.get("owner"),
36
+ "vote_breakdown": d.get("vote_breakdown", []),
37
+ "url": d.get("url"),
38
+ "request_fingerprint": d.get("request_fingerprint"),
39
+ "notification_status": d.get("notification_status"),
40
+ "routing_rule_label": d.get("routing_rule_label"),
41
+ "source_agent": d.get("source_agent"),
42
+ "idempotency_key": d.get("idempotency_key"),
43
+ }