langchain-getabrain 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,6 @@
1
+ __pycache__/
2
+ *.pyc
3
+ .venv/
4
+ dist/
5
+ .pytest_cache/
6
+ .env
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 GetABrain.ai
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,129 @@
1
+ Metadata-Version: 2.5
2
+ Name: langchain-getabrain
3
+ Version: 0.1.0
4
+ Summary: LangChain tools for GetABrain: ask verified humans a question from an agent.
5
+ Project-URL: Homepage, https://www.getabrain.ai
6
+ Project-URL: Documentation, https://github.com/Guitarmaniac24/langchain-getabrain#readme
7
+ Project-URL: Source, https://github.com/Guitarmaniac24/langchain-getabrain
8
+ Project-URL: API docs, https://www.getabrain.ai/docs
9
+ Author-email: GetABrain <hello@getabrain.ai>
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: agents,getabrain,human-in-the-loop,langchain,tools
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Requires-Python: >=3.11
17
+ Requires-Dist: getabrain>=0.2.1
18
+ Requires-Dist: langchain-core<2.0,>=1.0
19
+ Description-Content-Type: text/markdown
20
+
21
+ # langchain-getabrain
22
+
23
+ LangChain tools for [GetABrain](https://www.getabrain.ai), an API that lets an agent ask
24
+ verified people in the US a question and get structured answers back.
25
+
26
+ Two tools:
27
+
28
+ | Tool | Name the model sees | What it does |
29
+ |---|---|---|
30
+ | `GetABrainAskTool` | `getabrain_ask_human` | Sends a question, waits up to `max_wait_seconds` for answers, returns them. If nobody has answered yet it returns `status: "pending"` and a `query_id`. |
31
+ | `GetABrainGetAnswersTool` | `getabrain_get_answers` | Reads the answers to an earlier question by `query_id`. Free and read-only. |
32
+
33
+ People take minutes to hours to answer, so a `pending` result is normal. The question stays
34
+ open and the second tool picks up the answers later.
35
+
36
+ ## Install
37
+
38
+ ```bash
39
+ pip install -U langchain-getabrain
40
+ ```
41
+
42
+ ## Credentials
43
+
44
+ Create an account and API key at https://www.getabrain.ai/requestor/signup (or see the
45
+ [quick start](https://www.getabrain.ai/docs/quickstart)), then:
46
+
47
+ ```bash
48
+ export GETABRAIN_API_KEY="gab_k_..."
49
+ export GETABRAIN_API_SECRET="gab_s_..."
50
+ ```
51
+
52
+ **Cost:** with a live key, every answer is paid from your GetABrain balance. With a
53
+ **test-mode key** (`POST /api/v1/requestor/keys {"mode": "test"}`), answers are simulated by
54
+ an AI stand-in, never reach people, and come back marked `"simulated": true` with a notice.
55
+ Build and test with a test-mode key first.
56
+
57
+ ## Use it directly
58
+
59
+ ```python
60
+ from langchain_getabrain import GetABrainAskTool, GetABrainGetAnswersTool
61
+
62
+ ask = GetABrainAskTool(max_wait_seconds=60)
63
+ print(ask.invoke({
64
+ "question": "Which name is easier to remember?",
65
+ "query_type": "multiple_choice",
66
+ "options": ["Quillo", "Brightdesk"],
67
+ "num_responses": 3,
68
+ }))
69
+ ```
70
+
71
+ The result is a JSON string:
72
+
73
+ ```json
74
+ {"query_id": "...", "status": "answered", "answers_received": 3, "answers_requested": 3,
75
+ "answers": [{"selected_ids": ["2"], "selected_options": ["Brightdesk"]}, "..."],
76
+ "test_mode": false}
77
+ ```
78
+
79
+ ## Use it in an agent
80
+
81
+ ```python
82
+ from langchain.agents import create_agent
83
+ from langchain_getabrain import GetABrainAskTool, GetABrainGetAnswersTool
84
+
85
+ agent = create_agent(
86
+ model="anthropic:claude-sonnet-4-5",
87
+ tools=[GetABrainAskTool(), GetABrainGetAnswersTool()],
88
+ system_prompt="When a decision needs human judgment, ask a person with getabrain_ask_human.",
89
+ )
90
+ agent.invoke({"messages": [{"role": "user", "content": "Is our headline 'Ship faster' clear to a normal person?"}]})
91
+ ```
92
+
93
+ ## Arguments the model fills
94
+
95
+ | Argument | Type | Notes |
96
+ |---|---|---|
97
+ | `question` | str | Required. |
98
+ | `query_type` | `yes_no` \| `multiple_choice` \| `rating_scale` \| `text` | Default `yes_no`. `rating_scale` is 1 to 5. |
99
+ | `options` | list[str] | Required for `multiple_choice` (2 or more). |
100
+ | `context` | str | Optional background shown to the person. |
101
+ | `num_responses` | int | How many different people answer. Default 1. |
102
+
103
+ ## Settings you set in code
104
+
105
+ | Setting | Default | Notes |
106
+ |---|---|---|
107
+ | `max_wait_seconds` | 60 | How long one call waits before returning `pending`. |
108
+ | `poll_interval_seconds` | 5 | Time between status checks. |
109
+ | `max_responses` | 5 | Upper limit on `num_responses` per call, a spend guard. |
110
+ | `speed` | `None` | `relaxed` / `standard` / `fast` / `rush`: higher pays people more per answer. |
111
+ | `api_key`, `api_secret`, `base_url` | env vars | `GETABRAIN_API_KEY`, `GETABRAIN_API_SECRET`, `GETABRAIN_BASE_URL`. |
112
+ | `client` | `None` | Pass a ready `getabrain.GetABrain` client instead. |
113
+
114
+ Other query types (image comparison, ranking, A/B tests, video and audio review) are available
115
+ through the [`getabrain` Python SDK](https://pypi.org/project/getabrain/) and the
116
+ [API docs](https://www.getabrain.ai/docs/api).
117
+
118
+ ## Development
119
+
120
+ ```bash
121
+ uv sync --group test
122
+ uv run pytest
123
+ ```
124
+
125
+ Unit tests mock HTTP and make no network calls.
126
+
127
+ ## License
128
+
129
+ MIT
@@ -0,0 +1,109 @@
1
+ # langchain-getabrain
2
+
3
+ LangChain tools for [GetABrain](https://www.getabrain.ai), an API that lets an agent ask
4
+ verified people in the US a question and get structured answers back.
5
+
6
+ Two tools:
7
+
8
+ | Tool | Name the model sees | What it does |
9
+ |---|---|---|
10
+ | `GetABrainAskTool` | `getabrain_ask_human` | Sends a question, waits up to `max_wait_seconds` for answers, returns them. If nobody has answered yet it returns `status: "pending"` and a `query_id`. |
11
+ | `GetABrainGetAnswersTool` | `getabrain_get_answers` | Reads the answers to an earlier question by `query_id`. Free and read-only. |
12
+
13
+ People take minutes to hours to answer, so a `pending` result is normal. The question stays
14
+ open and the second tool picks up the answers later.
15
+
16
+ ## Install
17
+
18
+ ```bash
19
+ pip install -U langchain-getabrain
20
+ ```
21
+
22
+ ## Credentials
23
+
24
+ Create an account and API key at https://www.getabrain.ai/requestor/signup (or see the
25
+ [quick start](https://www.getabrain.ai/docs/quickstart)), then:
26
+
27
+ ```bash
28
+ export GETABRAIN_API_KEY="gab_k_..."
29
+ export GETABRAIN_API_SECRET="gab_s_..."
30
+ ```
31
+
32
+ **Cost:** with a live key, every answer is paid from your GetABrain balance. With a
33
+ **test-mode key** (`POST /api/v1/requestor/keys {"mode": "test"}`), answers are simulated by
34
+ an AI stand-in, never reach people, and come back marked `"simulated": true` with a notice.
35
+ Build and test with a test-mode key first.
36
+
37
+ ## Use it directly
38
+
39
+ ```python
40
+ from langchain_getabrain import GetABrainAskTool, GetABrainGetAnswersTool
41
+
42
+ ask = GetABrainAskTool(max_wait_seconds=60)
43
+ print(ask.invoke({
44
+ "question": "Which name is easier to remember?",
45
+ "query_type": "multiple_choice",
46
+ "options": ["Quillo", "Brightdesk"],
47
+ "num_responses": 3,
48
+ }))
49
+ ```
50
+
51
+ The result is a JSON string:
52
+
53
+ ```json
54
+ {"query_id": "...", "status": "answered", "answers_received": 3, "answers_requested": 3,
55
+ "answers": [{"selected_ids": ["2"], "selected_options": ["Brightdesk"]}, "..."],
56
+ "test_mode": false}
57
+ ```
58
+
59
+ ## Use it in an agent
60
+
61
+ ```python
62
+ from langchain.agents import create_agent
63
+ from langchain_getabrain import GetABrainAskTool, GetABrainGetAnswersTool
64
+
65
+ agent = create_agent(
66
+ model="anthropic:claude-sonnet-4-5",
67
+ tools=[GetABrainAskTool(), GetABrainGetAnswersTool()],
68
+ system_prompt="When a decision needs human judgment, ask a person with getabrain_ask_human.",
69
+ )
70
+ agent.invoke({"messages": [{"role": "user", "content": "Is our headline 'Ship faster' clear to a normal person?"}]})
71
+ ```
72
+
73
+ ## Arguments the model fills
74
+
75
+ | Argument | Type | Notes |
76
+ |---|---|---|
77
+ | `question` | str | Required. |
78
+ | `query_type` | `yes_no` \| `multiple_choice` \| `rating_scale` \| `text` | Default `yes_no`. `rating_scale` is 1 to 5. |
79
+ | `options` | list[str] | Required for `multiple_choice` (2 or more). |
80
+ | `context` | str | Optional background shown to the person. |
81
+ | `num_responses` | int | How many different people answer. Default 1. |
82
+
83
+ ## Settings you set in code
84
+
85
+ | Setting | Default | Notes |
86
+ |---|---|---|
87
+ | `max_wait_seconds` | 60 | How long one call waits before returning `pending`. |
88
+ | `poll_interval_seconds` | 5 | Time between status checks. |
89
+ | `max_responses` | 5 | Upper limit on `num_responses` per call, a spend guard. |
90
+ | `speed` | `None` | `relaxed` / `standard` / `fast` / `rush`: higher pays people more per answer. |
91
+ | `api_key`, `api_secret`, `base_url` | env vars | `GETABRAIN_API_KEY`, `GETABRAIN_API_SECRET`, `GETABRAIN_BASE_URL`. |
92
+ | `client` | `None` | Pass a ready `getabrain.GetABrain` client instead. |
93
+
94
+ Other query types (image comparison, ranking, A/B tests, video and audio review) are available
95
+ through the [`getabrain` Python SDK](https://pypi.org/project/getabrain/) and the
96
+ [API docs](https://www.getabrain.ai/docs/api).
97
+
98
+ ## Development
99
+
100
+ ```bash
101
+ uv sync --group test
102
+ uv run pytest
103
+ ```
104
+
105
+ Unit tests mock HTTP and make no network calls.
106
+
107
+ ## License
108
+
109
+ MIT
@@ -0,0 +1,12 @@
1
+ """LangChain integration for GetABrain: ask verified humans a question."""
2
+
3
+ from importlib import metadata
4
+
5
+ from langchain_getabrain.tools import GetABrainAskTool, GetABrainGetAnswersTool
6
+
7
+ try:
8
+ __version__ = metadata.version(__package__ or "langchain-getabrain")
9
+ except metadata.PackageNotFoundError:
10
+ __version__ = ""
11
+
12
+ __all__ = ["GetABrainAskTool", "GetABrainGetAnswersTool", "__version__"]
File without changes
@@ -0,0 +1,294 @@
1
+ """LangChain tools that ask verified humans a question through GetABrain."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ from typing import Any, Literal, Optional
8
+
9
+ from getabrain import GetABrain, GetABrainError
10
+ from getabrain import TimeoutError as GetABrainTimeoutError
11
+ from langchain_core.callbacks import CallbackManagerForToolRun
12
+ from langchain_core.tools import BaseTool, ToolException
13
+ from pydantic import BaseModel, ConfigDict, Field, PrivateAttr
14
+
15
+ QueryType = Literal["yes_no", "multiple_choice", "rating_scale", "text"]
16
+ Speed = Literal["relaxed", "standard", "fast", "rush"]
17
+
18
+ _TEST_MODE_NOTICE = (
19
+ "Test-mode key: these answers are simulated by an AI stand-in, not real people."
20
+ )
21
+ _PENDING_HINT = (
22
+ "Real people are answering; this can take minutes to hours. The question stays "
23
+ "open. Call getabrain_get_answers with this query_id later to read the answers."
24
+ )
25
+
26
+
27
+ def _title_from(question: str) -> str:
28
+ title = " ".join(question.split())
29
+ if len(title) > 255:
30
+ title = title[:252] + "..."
31
+ if len(title) < 5:
32
+ title = (title + " (question)").strip()
33
+ return title
34
+
35
+
36
+ def build_content_data(
37
+ question: str,
38
+ query_type: str,
39
+ options: Optional[list[str]] = None,
40
+ context: Optional[str] = None,
41
+ ) -> dict[str, Any]:
42
+ """Build the GetABrain ``content_data`` payload for a supported query type.
43
+
44
+ Raises:
45
+ ValueError: If the arguments do not fit the query type.
46
+ """
47
+ if query_type not in ("yes_no", "multiple_choice", "rating_scale", "text"):
48
+ raise ValueError(f"Unsupported query_type: {query_type!r}.")
49
+ content: dict[str, Any] = {"question": question}
50
+ if context:
51
+ content["context"] = context
52
+ if query_type == "multiple_choice":
53
+ if not options or len(options) < 2:
54
+ raise ValueError("multiple_choice needs at least 2 options.")
55
+ content["options"] = [
56
+ {"id": str(i + 1), "text": text} for i, text in enumerate(options)
57
+ ]
58
+ elif options:
59
+ raise ValueError("options are only used with query_type='multiple_choice'.")
60
+ if query_type == "rating_scale":
61
+ content.update({"scale_type": "1-5", "scale_min": 1, "scale_max": 5})
62
+ return content
63
+
64
+
65
+ def summarize_query(query: dict[str, Any], *, done: bool) -> dict[str, Any]:
66
+ """Turn a GetABrain query object into a compact result for an agent."""
67
+ test_mode = query.get("test_mode") is True
68
+ options = {
69
+ str(o.get("id")): o.get("text")
70
+ for o in (query.get("content_data") or {}).get("options") or []
71
+ if isinstance(o, dict)
72
+ }
73
+ answers: list[dict[str, Any]] = []
74
+ for response in query.get("responses") or []:
75
+ answer = dict(response.get("response_data") or {})
76
+ ids = answer.get("selected_ids")
77
+ if options and isinstance(ids, list):
78
+ answer["selected_options"] = [options.get(str(i), i) for i in ids]
79
+ if response.get("simulated") is True:
80
+ answer["simulated"] = True
81
+ test_mode = True
82
+ answers.append(answer)
83
+ result: dict[str, Any] = {
84
+ "query_id": query.get("id"),
85
+ "status": "answered" if done else "pending",
86
+ "query_status": query.get("status"),
87
+ "answers_received": len(answers),
88
+ "answers_requested": query.get("required_responses"),
89
+ "answers": answers,
90
+ "test_mode": test_mode,
91
+ }
92
+ if test_mode:
93
+ result["notice"] = _TEST_MODE_NOTICE
94
+ if not done:
95
+ result["hint"] = _PENDING_HINT
96
+ return result
97
+
98
+
99
+ class GetABrainAskInput(BaseModel):
100
+ """Input for :class:`GetABrainAskTool`."""
101
+
102
+ question: str = Field(
103
+ ..., description="The question for the human, written so a stranger can answer it."
104
+ )
105
+ query_type: QueryType = Field(
106
+ default="yes_no",
107
+ description=(
108
+ "Answer format: 'yes_no', 'multiple_choice' (needs options), "
109
+ "'rating_scale' (1 to 5), or 'text' (a short written answer)."
110
+ ),
111
+ )
112
+ options: Optional[list[str]] = Field(
113
+ default=None,
114
+ description="Answer choices for multiple_choice (2 or more). Leave empty otherwise.",
115
+ )
116
+ context: Optional[str] = Field(
117
+ default=None,
118
+ description="Optional background the human needs to answer well.",
119
+ )
120
+ num_responses: int = Field(
121
+ default=1,
122
+ ge=1,
123
+ description="How many different people should answer (default 1).",
124
+ )
125
+
126
+
127
+ class GetABrainGetAnswersInput(BaseModel):
128
+ """Input for :class:`GetABrainGetAnswersTool`."""
129
+
130
+ query_id: str = Field(..., description="The query_id returned by getabrain_ask_human.")
131
+
132
+
133
+ class _GetABrainToolBase(BaseTool):
134
+ """Shared client handling for the GetABrain tools."""
135
+
136
+ model_config = ConfigDict(arbitrary_types_allowed=True)
137
+
138
+ api_key: Optional[str] = None
139
+ """GetABrain API key. Defaults to the ``GETABRAIN_API_KEY`` env var."""
140
+ api_secret: Optional[str] = None
141
+ """GetABrain API secret. Defaults to the ``GETABRAIN_API_SECRET`` env var."""
142
+ base_url: Optional[str] = None
143
+ """API base URL. Defaults to ``GETABRAIN_BASE_URL`` or the production API."""
144
+ client: Optional[GetABrain] = None
145
+ """A ready ``getabrain.GetABrain`` client. Overrides the credentials above."""
146
+ handle_tool_error: bool = True
147
+
148
+ _client: Optional[GetABrain] = PrivateAttr(default=None)
149
+
150
+ def _get_client(self) -> GetABrain:
151
+ if self.client is not None:
152
+ return self.client
153
+ if self._client is None:
154
+ key = self.api_key or os.environ.get("GETABRAIN_API_KEY")
155
+ secret = self.api_secret or os.environ.get("GETABRAIN_API_SECRET")
156
+ if not key or not secret:
157
+ raise ToolException(
158
+ "Set GETABRAIN_API_KEY and GETABRAIN_API_SECRET "
159
+ "(or pass api_key and api_secret)."
160
+ )
161
+ self._client = GetABrain(
162
+ api_key=key,
163
+ api_secret=secret,
164
+ base_url=self.base_url or os.environ.get("GETABRAIN_BASE_URL"),
165
+ )
166
+ return self._client
167
+
168
+
169
+ class GetABrainAskTool(_GetABrainToolBase):
170
+ """Ask verified humans a question and wait a bounded time for their answers.
171
+
172
+ Setup:
173
+ Install ``langchain-getabrain`` and set your keys:
174
+
175
+ .. code-block:: bash
176
+
177
+ pip install -U langchain-getabrain
178
+ export GETABRAIN_API_KEY="gab_k_..."
179
+ export GETABRAIN_API_SECRET="gab_s_..."
180
+
181
+ Instantiate:
182
+ .. code-block:: python
183
+
184
+ from langchain_getabrain import GetABrainAskTool
185
+
186
+ tool = GetABrainAskTool(max_wait_seconds=120)
187
+
188
+ Invoke directly:
189
+ .. code-block:: python
190
+
191
+ tool.invoke({"question": "Is this headline clear: 'Ship faster'?"})
192
+
193
+ A live key charges your GetABrain balance for each answer. A test-mode key
194
+ returns simulated answers (marked ``simulated``) and never reaches people.
195
+ """
196
+
197
+ name: str = "getabrain_ask_human"
198
+ description: str = (
199
+ "Ask real, verified people a question and get their answers. Use it for "
200
+ "judgment calls, taste, approvals, or checks a model should not answer "
201
+ "itself. Returns status 'answered' with the answers, or 'pending' with a "
202
+ "query_id if people have not answered within the wait time; then use "
203
+ "getabrain_get_answers later. With a live key each answer costs money "
204
+ "from the GetABrain balance."
205
+ )
206
+ args_schema: type[BaseModel] = GetABrainAskInput
207
+
208
+ max_wait_seconds: float = 60.0
209
+ """How long one call waits for answers before returning ``pending``."""
210
+ poll_interval_seconds: float = 5.0
211
+ """Seconds between status checks while waiting."""
212
+ max_responses: int = 5
213
+ """Upper limit on ``num_responses`` an agent may request in one call."""
214
+ speed: Optional[Speed] = None
215
+ """Pay level per answer (relaxed/standard/fast/rush). ``None`` = API default."""
216
+
217
+ def _run(
218
+ self,
219
+ question: str,
220
+ query_type: QueryType = "yes_no",
221
+ options: Optional[list[str]] = None,
222
+ context: Optional[str] = None,
223
+ num_responses: int = 1,
224
+ run_manager: Optional[CallbackManagerForToolRun] = None,
225
+ ) -> str:
226
+ if num_responses > self.max_responses:
227
+ raise ToolException(
228
+ f"num_responses is {num_responses}; this tool allows at most "
229
+ f"{self.max_responses}."
230
+ )
231
+ try:
232
+ content = build_content_data(question, query_type, options, context)
233
+ except ValueError as exc:
234
+ raise ToolException(str(exc)) from exc
235
+ body: dict[str, Any] = {
236
+ "type": query_type,
237
+ "title": _title_from(question),
238
+ "content_data": content,
239
+ "required_responses": num_responses,
240
+ }
241
+ if self.speed:
242
+ body["speed"] = self.speed
243
+ client = self._get_client()
244
+ try:
245
+ created = client.queries.create(**body)
246
+ query_id = created.get("id") or created.get("query_id")
247
+ if not query_id:
248
+ raise ToolException(f"GetABrain did not return a query id: {created}")
249
+ try:
250
+ client.queries.wait_for_responses(
251
+ query_id,
252
+ min_responses=num_responses,
253
+ timeout_s=self.max_wait_seconds,
254
+ poll_interval_s=self.poll_interval_seconds,
255
+ )
256
+ except GetABrainTimeoutError:
257
+ pass
258
+ query = client.queries.get(query_id)
259
+ except GetABrainError as exc:
260
+ raise ToolException(f"GetABrain error ({exc.status}): {exc.message}") from exc
261
+ done = (query.get("completed_responses") or 0) >= num_responses or query.get(
262
+ "status"
263
+ ) in ("completed", "cancelled", "failed", "expired")
264
+ return json.dumps(summarize_query(query, done=done))
265
+
266
+
267
+ class GetABrainGetAnswersTool(_GetABrainToolBase):
268
+ """Read the current answers to a GetABrain question by its ``query_id``.
269
+
270
+ Free and read-only. Use it after :class:`GetABrainAskTool` returned
271
+ ``pending``.
272
+ """
273
+
274
+ name: str = "getabrain_get_answers"
275
+ description: str = (
276
+ "Read the answers people have given so far to an earlier "
277
+ "getabrain_ask_human question, by query_id. Free and read-only."
278
+ )
279
+ args_schema: type[BaseModel] = GetABrainGetAnswersInput
280
+
281
+ def _run(
282
+ self,
283
+ query_id: str,
284
+ run_manager: Optional[CallbackManagerForToolRun] = None,
285
+ ) -> str:
286
+ try:
287
+ query = self._get_client().queries.get(query_id)
288
+ except GetABrainError as exc:
289
+ raise ToolException(f"GetABrain error ({exc.status}): {exc.message}") from exc
290
+ required = query.get("required_responses") or 1
291
+ done = (query.get("completed_responses") or 0) >= required or query.get(
292
+ "status"
293
+ ) in ("completed", "cancelled", "failed", "expired")
294
+ return json.dumps(summarize_query(query, done=done))
@@ -0,0 +1,38 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "langchain-getabrain"
7
+ version = "0.1.0"
8
+ description = "LangChain tools for GetABrain: ask verified humans a question from an agent."
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = "MIT"
12
+ authors = [{ name = "GetABrain", email = "hello@getabrain.ai" }]
13
+ keywords = ["langchain", "getabrain", "human-in-the-loop", "agents", "tools"]
14
+ dependencies = ["langchain-core>=1.0,<2.0", "getabrain>=0.2.1"]
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "License :: OSI Approved :: MIT License",
18
+ "Intended Audience :: Developers",
19
+ ]
20
+
21
+ [project.urls]
22
+ Homepage = "https://www.getabrain.ai"
23
+ Documentation = "https://github.com/Guitarmaniac24/langchain-getabrain#readme"
24
+ Source = "https://github.com/Guitarmaniac24/langchain-getabrain"
25
+ "API docs" = "https://www.getabrain.ai/docs"
26
+
27
+ [dependency-groups]
28
+ test = ["pytest>=8", "langchain-tests>=1.0"]
29
+
30
+ [tool.hatch.build.targets.wheel]
31
+ packages = ["langchain_getabrain"]
32
+
33
+ [tool.hatch.build.targets.sdist]
34
+ include = ["langchain_getabrain", "tests", "README.md", "LICENSE"]
35
+
36
+ [tool.pytest.ini_options]
37
+ testpaths = ["tests"]
38
+ asyncio_default_fixture_loop_scope = "function"
File without changes
File without changes
@@ -0,0 +1,35 @@
1
+ """LangChain standard unit tests for the GetABrain tools."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from langchain_tests.unit_tests import ToolsUnitTests
6
+
7
+ from langchain_getabrain import GetABrainAskTool, GetABrainGetAnswersTool
8
+
9
+
10
+ class TestGetABrainAskToolStandard(ToolsUnitTests):
11
+ @property
12
+ def tool_constructor(self) -> type[GetABrainAskTool]:
13
+ return GetABrainAskTool
14
+
15
+ @property
16
+ def tool_constructor_params(self) -> dict:
17
+ return {"api_key": "gab_k_test", "api_secret": "gab_s_test"}
18
+
19
+ @property
20
+ def tool_invoke_params_example(self) -> dict:
21
+ return {"question": "Is this headline clear?", "query_type": "yes_no"}
22
+
23
+
24
+ class TestGetABrainGetAnswersToolStandard(ToolsUnitTests):
25
+ @property
26
+ def tool_constructor(self) -> type[GetABrainGetAnswersTool]:
27
+ return GetABrainGetAnswersTool
28
+
29
+ @property
30
+ def tool_constructor_params(self) -> dict:
31
+ return {"api_key": "gab_k_test", "api_secret": "gab_s_test"}
32
+
33
+ @property
34
+ def tool_invoke_params_example(self) -> dict:
35
+ return {"query_id": "q_1"}
@@ -0,0 +1,195 @@
1
+ """Unit tests for the GetABrain LangChain tools (HTTP mocked, no network)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any
7
+
8
+ import httpx
9
+ import pytest
10
+ from getabrain import GetABrain
11
+
12
+ from langchain_getabrain import GetABrainAskTool, GetABrainGetAnswersTool
13
+
14
+
15
+ class FakeApi:
16
+ """A tiny in-memory stand-in for the GetABrain requestor API."""
17
+
18
+ def __init__(self, *, answers_after_polls: int = 0, test_mode: bool = False) -> None:
19
+ self.created: list[dict[str, Any]] = []
20
+ self.gets = 0
21
+ self.answers_after_polls = answers_after_polls
22
+ self.test_mode = test_mode
23
+ self.status_code = 201
24
+ self.error_body: dict[str, Any] | None = None
25
+
26
+ def handler(self, request: httpx.Request) -> httpx.Response:
27
+ assert request.headers["X-API-Key"] == "gab_k_test"
28
+ assert request.headers["X-API-Secret"] == "gab_s_test"
29
+ if request.method == "POST" and request.url.path.endswith("/requestor/queries"):
30
+ if self.error_body is not None:
31
+ return httpx.Response(self.status_code, json=self.error_body)
32
+ self.created.append(json.loads(request.content))
33
+ return httpx.Response(201, json={"id": "q_1", "status": "active"})
34
+ if request.method == "GET" and request.url.path.endswith("/requestor/queries/q_1"):
35
+ self.gets += 1
36
+ body = self.created[0] if self.created else {"type": "yes_no", "required_responses": 1, "content_data": {}}
37
+ ready = self.gets > self.answers_after_polls
38
+ n = body["required_responses"]
39
+ responses = []
40
+ if ready:
41
+ for i in range(n):
42
+ if body["type"] == "multiple_choice":
43
+ data: dict[str, Any] = {"selected_ids": ["2"]}
44
+ elif body["type"] == "rating_scale":
45
+ data = {"rating": 4}
46
+ else:
47
+ data = {"answer": "yes"}
48
+ responses.append(
49
+ {"id": f"r_{i}", "response_data": data, "simulated": self.test_mode}
50
+ )
51
+ return httpx.Response(
52
+ 200,
53
+ json={
54
+ "id": "q_1",
55
+ "type": body["type"],
56
+ "status": "completed" if ready else "active",
57
+ "required_responses": n,
58
+ "completed_responses": len(responses),
59
+ "content_data": body["content_data"],
60
+ "responses": responses,
61
+ "test_mode": self.test_mode,
62
+ },
63
+ )
64
+ return httpx.Response(404, json={"error": "not_found", "message": "nope"})
65
+
66
+
67
+ def make_client(api: FakeApi) -> GetABrain:
68
+ return GetABrain(
69
+ api_key="gab_k_test",
70
+ api_secret="gab_s_test",
71
+ transport=httpx.MockTransport(api.handler),
72
+ sleep=lambda _s: None,
73
+ )
74
+
75
+
76
+ def make_ask(api: FakeApi, **kwargs: Any) -> GetABrainAskTool:
77
+ kwargs.setdefault("poll_interval_seconds", 0.0)
78
+ return GetABrainAskTool(client=make_client(api), **kwargs)
79
+
80
+
81
+ def test_yes_no_answered() -> None:
82
+ api = FakeApi()
83
+ out = json.loads(make_ask(api).invoke({"question": "Is the sky blue on a clear day?"}))
84
+ assert out["status"] == "answered"
85
+ assert out["query_id"] == "q_1"
86
+ assert out["answers"] == [{"answer": "yes"}]
87
+ assert out["test_mode"] is False
88
+ assert "notice" not in out
89
+ sent = api.created[0]
90
+ assert sent["type"] == "yes_no"
91
+ assert sent["required_responses"] == 1
92
+ assert sent["content_data"] == {"question": "Is the sky blue on a clear day?"}
93
+ assert "bid_amount_cents" not in sent
94
+
95
+
96
+ def test_multiple_choice_maps_ids_back_to_text() -> None:
97
+ api = FakeApi()
98
+ out = json.loads(
99
+ make_ask(api).invoke(
100
+ {
101
+ "question": "Which name is easier to say?",
102
+ "query_type": "multiple_choice",
103
+ "options": ["Zorblax", "Nimbus"],
104
+ "num_responses": 2,
105
+ }
106
+ )
107
+ )
108
+ assert api.created[0]["content_data"]["options"] == [
109
+ {"id": "1", "text": "Zorblax"},
110
+ {"id": "2", "text": "Nimbus"},
111
+ ]
112
+ assert out["answers_received"] == 2
113
+ assert out["answers"][0]["selected_options"] == ["Nimbus"]
114
+
115
+
116
+ def test_rating_scale_sets_scale() -> None:
117
+ api = FakeApi()
118
+ out = json.loads(
119
+ make_ask(api).invoke({"question": "Rate this tagline", "query_type": "rating_scale"})
120
+ )
121
+ content = api.created[0]["content_data"]
122
+ assert (content["scale_type"], content["scale_min"], content["scale_max"]) == ("1-5", 1, 5)
123
+ assert out["answers"] == [{"rating": 4}]
124
+
125
+
126
+ def test_context_and_speed_are_sent() -> None:
127
+ api = FakeApi()
128
+ make_ask(api, speed="fast").invoke(
129
+ {"question": "Does this read as rude?", "context": "A reply to a customer."}
130
+ )
131
+ assert api.created[0]["content_data"]["context"] == "A reply to a customer."
132
+ assert api.created[0]["speed"] == "fast"
133
+
134
+
135
+ def test_pending_when_wait_runs_out() -> None:
136
+ api = FakeApi(answers_after_polls=10_000)
137
+ out = json.loads(make_ask(api, max_wait_seconds=0).invoke({"question": "Is this funny?"}))
138
+ assert out["status"] == "pending"
139
+ assert out["query_id"] == "q_1"
140
+ assert "getabrain_get_answers" in out["hint"]
141
+
142
+
143
+ def test_get_answers_later() -> None:
144
+ api = FakeApi(answers_after_polls=10_000)
145
+ make_ask(api, max_wait_seconds=0).invoke({"question": "Is this funny?"})
146
+ api.answers_after_polls = 0
147
+ getter = GetABrainGetAnswersTool(client=make_client(api))
148
+ out = json.loads(getter.invoke({"query_id": "q_1"}))
149
+ assert out["status"] == "answered"
150
+ assert out["answers"] == [{"answer": "yes"}]
151
+
152
+
153
+ def test_test_mode_answers_are_marked_simulated() -> None:
154
+ api = FakeApi(test_mode=True)
155
+ out = json.loads(make_ask(api).invoke({"question": "Is this a test?"}))
156
+ assert out["test_mode"] is True
157
+ assert out["answers"][0]["simulated"] is True
158
+ assert "simulated" in out["notice"]
159
+
160
+
161
+ def test_multiple_choice_without_options_is_a_tool_error() -> None:
162
+ api = FakeApi()
163
+ out = make_ask(api).invoke({"question": "Pick one", "query_type": "multiple_choice"})
164
+ assert "at least 2 options" in out
165
+ assert api.created == []
166
+
167
+
168
+ def test_num_responses_cap() -> None:
169
+ api = FakeApi()
170
+ out = make_ask(api, max_responses=3).invoke({"question": "Is it ok?", "num_responses": 4})
171
+ assert "at most 3" in out
172
+ assert api.created == []
173
+
174
+
175
+ def test_api_error_is_returned_to_the_agent() -> None:
176
+ api = FakeApi()
177
+ api.status_code = 402
178
+ api.error_body = {"error": "insufficient_balance", "message": "Balance too low"}
179
+ out = make_ask(api).invoke({"question": "Is it ok?"})
180
+ assert "402" in out and "Balance too low" in out
181
+
182
+
183
+ def test_missing_credentials(monkeypatch: pytest.MonkeyPatch) -> None:
184
+ monkeypatch.delenv("GETABRAIN_API_KEY", raising=False)
185
+ monkeypatch.delenv("GETABRAIN_API_SECRET", raising=False)
186
+ out = GetABrainAskTool().invoke({"question": "Is it ok?"})
187
+ assert "GETABRAIN_API_KEY" in out
188
+
189
+
190
+ def test_long_and_short_questions_make_valid_titles() -> None:
191
+ api = FakeApi()
192
+ make_ask(api).invoke({"question": "x" * 400})
193
+ make_ask(api).invoke({"question": "Ok?"})
194
+ assert len(api.created[0]["title"]) == 255
195
+ assert 5 <= len(api.created[1]["title"]) <= 255