crewai-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,140 @@
1
+ Metadata-Version: 2.5
2
+ Name: crewai-getabrain
3
+ Version: 0.1.0
4
+ Summary: CrewAI tools for GetABrain: ask verified humans a question from a crew.
5
+ Project-URL: Homepage, https://www.getabrain.ai
6
+ Project-URL: Documentation, https://github.com/Guitarmaniac24/crewai-getabrain#readme
7
+ Project-URL: Source, https://github.com/Guitarmaniac24/crewai-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,crewai,getabrain,human-in-the-loop,tools
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Requires-Python: <3.14,>=3.10
17
+ Requires-Dist: crewai>=1.0
18
+ Requires-Dist: getabrain>=0.2.1
19
+ Description-Content-Type: text/markdown
20
+
21
+ # crewai-getabrain
22
+
23
+ CrewAI 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 crewai-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 crewai_getabrain import GetABrainAskTool, GetABrainGetAnswersTool
61
+
62
+ ask = GetABrainAskTool(max_wait_seconds=60)
63
+ print(ask.run(
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 a crew
80
+
81
+ ```python
82
+ from crewai import Agent, Crew, Task
83
+ from crewai_getabrain import GetABrainAskTool, GetABrainGetAnswersTool
84
+
85
+ checker = Agent(
86
+ role="Product checker",
87
+ goal="Settle judgment calls by asking real people instead of guessing",
88
+ backstory="You call getabrain_ask_human when a decision needs human judgment.",
89
+ tools=[GetABrainAskTool(), GetABrainGetAnswersTool()],
90
+ )
91
+ task = Task(
92
+ description="Find out whether the headline 'Ship faster' is clear to a normal person.",
93
+ expected_output="Yes or no, with what the person said.",
94
+ agent=checker,
95
+ )
96
+ print(Crew(agents=[checker], tasks=[task]).kickoff())
97
+ ```
98
+
99
+ A runnable version is in [`example.py`](example.py).
100
+
101
+ Errors (missing keys, bad arguments, API errors) come back to the agent as a string starting
102
+ with `Error:`.
103
+
104
+ ## Arguments the model fills
105
+
106
+ | Argument | Type | Notes |
107
+ |---|---|---|
108
+ | `question` | str | Required. |
109
+ | `query_type` | `yes_no` \| `multiple_choice` \| `rating_scale` \| `text` | Default `yes_no`. `rating_scale` is 1 to 5. |
110
+ | `options` | list[str] | Required for `multiple_choice` (2 or more). |
111
+ | `context` | str | Optional background shown to the person. |
112
+ | `num_responses` | int | How many different people answer. Default 1. |
113
+
114
+ ## Settings you set in code
115
+
116
+ | Setting | Default | Notes |
117
+ |---|---|---|
118
+ | `max_wait_seconds` | 60 | How long one call waits before returning `pending`. |
119
+ | `poll_interval_seconds` | 5 | Time between status checks. |
120
+ | `max_responses` | 5 | Upper limit on `num_responses` per call, a spend guard. |
121
+ | `speed` | `None` | `relaxed` / `standard` / `fast` / `rush`: higher pays people more per answer. |
122
+ | `api_key`, `api_secret`, `base_url` | env vars | `GETABRAIN_API_KEY`, `GETABRAIN_API_SECRET`, `GETABRAIN_BASE_URL`. |
123
+ | `client` | `None` | Pass a ready `getabrain.GetABrain` client instead. |
124
+
125
+ Other query types (image comparison, ranking, A/B tests, video and audio review) are available
126
+ through the [`getabrain` Python SDK](https://pypi.org/project/getabrain/) and the
127
+ [API docs](https://www.getabrain.ai/docs/api).
128
+
129
+ ## Development
130
+
131
+ ```bash
132
+ uv sync --group test
133
+ uv run pytest
134
+ ```
135
+
136
+ Unit tests mock HTTP and make no network calls.
137
+
138
+ ## License
139
+
140
+ MIT
@@ -0,0 +1,120 @@
1
+ # crewai-getabrain
2
+
3
+ CrewAI 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 crewai-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 crewai_getabrain import GetABrainAskTool, GetABrainGetAnswersTool
41
+
42
+ ask = GetABrainAskTool(max_wait_seconds=60)
43
+ print(ask.run(
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 a crew
60
+
61
+ ```python
62
+ from crewai import Agent, Crew, Task
63
+ from crewai_getabrain import GetABrainAskTool, GetABrainGetAnswersTool
64
+
65
+ checker = Agent(
66
+ role="Product checker",
67
+ goal="Settle judgment calls by asking real people instead of guessing",
68
+ backstory="You call getabrain_ask_human when a decision needs human judgment.",
69
+ tools=[GetABrainAskTool(), GetABrainGetAnswersTool()],
70
+ )
71
+ task = Task(
72
+ description="Find out whether the headline 'Ship faster' is clear to a normal person.",
73
+ expected_output="Yes or no, with what the person said.",
74
+ agent=checker,
75
+ )
76
+ print(Crew(agents=[checker], tasks=[task]).kickoff())
77
+ ```
78
+
79
+ A runnable version is in [`example.py`](example.py).
80
+
81
+ Errors (missing keys, bad arguments, API errors) come back to the agent as a string starting
82
+ with `Error:`.
83
+
84
+ ## Arguments the model fills
85
+
86
+ | Argument | Type | Notes |
87
+ |---|---|---|
88
+ | `question` | str | Required. |
89
+ | `query_type` | `yes_no` \| `multiple_choice` \| `rating_scale` \| `text` | Default `yes_no`. `rating_scale` is 1 to 5. |
90
+ | `options` | list[str] | Required for `multiple_choice` (2 or more). |
91
+ | `context` | str | Optional background shown to the person. |
92
+ | `num_responses` | int | How many different people answer. Default 1. |
93
+
94
+ ## Settings you set in code
95
+
96
+ | Setting | Default | Notes |
97
+ |---|---|---|
98
+ | `max_wait_seconds` | 60 | How long one call waits before returning `pending`. |
99
+ | `poll_interval_seconds` | 5 | Time between status checks. |
100
+ | `max_responses` | 5 | Upper limit on `num_responses` per call, a spend guard. |
101
+ | `speed` | `None` | `relaxed` / `standard` / `fast` / `rush`: higher pays people more per answer. |
102
+ | `api_key`, `api_secret`, `base_url` | env vars | `GETABRAIN_API_KEY`, `GETABRAIN_API_SECRET`, `GETABRAIN_BASE_URL`. |
103
+ | `client` | `None` | Pass a ready `getabrain.GetABrain` client instead. |
104
+
105
+ Other query types (image comparison, ranking, A/B tests, video and audio review) are available
106
+ through the [`getabrain` Python SDK](https://pypi.org/project/getabrain/) and the
107
+ [API docs](https://www.getabrain.ai/docs/api).
108
+
109
+ ## Development
110
+
111
+ ```bash
112
+ uv sync --group test
113
+ uv run pytest
114
+ ```
115
+
116
+ Unit tests mock HTTP and make no network calls.
117
+
118
+ ## License
119
+
120
+ MIT
@@ -0,0 +1,5 @@
1
+ """CrewAI tools for GetABrain: ask verified humans a question."""
2
+
3
+ from crewai_getabrain.tool import GetABrainAskTool, GetABrainGetAnswersTool
4
+
5
+ __all__ = ["GetABrainAskTool", "GetABrainGetAnswersTool"]
File without changes
@@ -0,0 +1,273 @@
1
+ """CrewAI tools that ask verified humans a question through GetABrain.
2
+
3
+ Environment variables:
4
+ GETABRAIN_API_KEY: GetABrain API key (gab_k_...).
5
+ GETABRAIN_API_SECRET: GetABrain API secret (gab_s_...).
6
+ GETABRAIN_BASE_URL: Optional API base URL override.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import os
13
+ from typing import Any, Literal
14
+
15
+ from crewai.tools import BaseTool, EnvVar
16
+ from getabrain import GetABrain, GetABrainError
17
+ from getabrain import TimeoutError as GetABrainTimeoutError
18
+ from pydantic import BaseModel, Field, PrivateAttr
19
+
20
+ QueryType = Literal["yes_no", "multiple_choice", "rating_scale", "text"]
21
+ Speed = Literal["relaxed", "standard", "fast", "rush"]
22
+
23
+ _TERMINAL = ("completed", "cancelled", "failed", "expired")
24
+ _TEST_MODE_NOTICE = (
25
+ "Test-mode key: these answers are simulated by an AI stand-in, not real people."
26
+ )
27
+ _PENDING_HINT = (
28
+ "Real people are answering; this can take minutes to hours. The question stays "
29
+ "open. Call getabrain_get_answers with this query_id later to read the answers."
30
+ )
31
+ _ENV_VARS = [
32
+ EnvVar(name="GETABRAIN_API_KEY", description="GetABrain API key.", required=True),
33
+ EnvVar(
34
+ name="GETABRAIN_API_SECRET", description="GetABrain API secret.", required=True
35
+ ),
36
+ EnvVar(
37
+ name="GETABRAIN_BASE_URL",
38
+ description="Optional API base URL override.",
39
+ required=False,
40
+ ),
41
+ ]
42
+
43
+
44
+ def _title_from(question: str) -> str:
45
+ title = " ".join(question.split())
46
+ if len(title) > 255:
47
+ title = title[:252] + "..."
48
+ if len(title) < 5:
49
+ title = (title + " (question)").strip()
50
+ return title
51
+
52
+
53
+ def build_content_data(
54
+ question: str,
55
+ query_type: str,
56
+ options: list[str] | None = None,
57
+ context: str | None = None,
58
+ ) -> dict[str, Any]:
59
+ """Build the GetABrain ``content_data`` payload for a supported query type.
60
+
61
+ Raises:
62
+ ValueError: If the arguments do not fit the query type.
63
+ """
64
+ if query_type not in ("yes_no", "multiple_choice", "rating_scale", "text"):
65
+ raise ValueError(f"Unsupported query_type: {query_type!r}.")
66
+ content: dict[str, Any] = {"question": question}
67
+ if context:
68
+ content["context"] = context
69
+ if query_type == "multiple_choice":
70
+ if not options or len(options) < 2:
71
+ raise ValueError("multiple_choice needs at least 2 options.")
72
+ content["options"] = [
73
+ {"id": str(i + 1), "text": text} for i, text in enumerate(options)
74
+ ]
75
+ elif options:
76
+ raise ValueError("options are only used with query_type='multiple_choice'.")
77
+ if query_type == "rating_scale":
78
+ content.update({"scale_type": "1-5", "scale_min": 1, "scale_max": 5})
79
+ return content
80
+
81
+
82
+ def summarize_query(query: dict[str, Any], *, done: bool) -> dict[str, Any]:
83
+ """Turn a GetABrain query object into a compact result for an agent."""
84
+ test_mode = query.get("test_mode") is True
85
+ options = {
86
+ str(o.get("id")): o.get("text")
87
+ for o in (query.get("content_data") or {}).get("options") or []
88
+ if isinstance(o, dict)
89
+ }
90
+ answers: list[dict[str, Any]] = []
91
+ for response in query.get("responses") or []:
92
+ answer = dict(response.get("response_data") or {})
93
+ ids = answer.get("selected_ids")
94
+ if options and isinstance(ids, list):
95
+ answer["selected_options"] = [options.get(str(i), i) for i in ids]
96
+ if response.get("simulated") is True:
97
+ answer["simulated"] = True
98
+ test_mode = True
99
+ answers.append(answer)
100
+ result: dict[str, Any] = {
101
+ "query_id": query.get("id"),
102
+ "status": "answered" if done else "pending",
103
+ "query_status": query.get("status"),
104
+ "answers_received": len(answers),
105
+ "answers_requested": query.get("required_responses"),
106
+ "answers": answers,
107
+ "test_mode": test_mode,
108
+ }
109
+ if test_mode:
110
+ result["notice"] = _TEST_MODE_NOTICE
111
+ if not done:
112
+ result["hint"] = _PENDING_HINT
113
+ return result
114
+
115
+
116
+ def _is_done(query: dict[str, Any], wanted: int) -> bool:
117
+ return (query.get("completed_responses") or 0) >= wanted or query.get(
118
+ "status"
119
+ ) in _TERMINAL
120
+
121
+
122
+ class GetABrainAskInput(BaseModel):
123
+ """Input schema for GetABrainAskTool."""
124
+
125
+ question: str = Field(
126
+ ...,
127
+ description="The question for the human, written so a stranger can answer it.",
128
+ )
129
+ query_type: QueryType = Field(
130
+ default="yes_no",
131
+ description=(
132
+ "Answer format: 'yes_no', 'multiple_choice' (needs options), "
133
+ "'rating_scale' (1 to 5), or 'text' (a short written answer)."
134
+ ),
135
+ )
136
+ options: list[str] | None = Field(
137
+ default=None,
138
+ description="Answer choices for multiple_choice (2 or more). Leave empty otherwise.",
139
+ )
140
+ context: str | None = Field(
141
+ default=None, description="Optional background the human needs to answer well."
142
+ )
143
+ num_responses: int = Field(
144
+ default=1, ge=1, description="How many different people should answer (default 1)."
145
+ )
146
+
147
+
148
+ class GetABrainGetAnswersInput(BaseModel):
149
+ """Input schema for GetABrainGetAnswersTool."""
150
+
151
+ query_id: str = Field(
152
+ ..., description="The query_id returned by getabrain_ask_human."
153
+ )
154
+
155
+
156
+ class _GetABrainToolBase(BaseTool):
157
+ """Shared client handling for the GetABrain tools."""
158
+
159
+ api_key: str | None = None
160
+ api_secret: str | None = None
161
+ base_url: str | None = None
162
+ client: GetABrain | None = None
163
+ env_vars: list[EnvVar] = Field(default_factory=lambda: list(_ENV_VARS))
164
+
165
+ _client: GetABrain | None = PrivateAttr(default=None)
166
+
167
+ def _get_client(self) -> GetABrain:
168
+ if self.client is not None:
169
+ return self.client
170
+ if self._client is None:
171
+ key = self.api_key or os.environ.get("GETABRAIN_API_KEY")
172
+ secret = self.api_secret or os.environ.get("GETABRAIN_API_SECRET")
173
+ if not key or not secret:
174
+ raise ValueError(
175
+ "Set GETABRAIN_API_KEY and GETABRAIN_API_SECRET "
176
+ "(or pass api_key and api_secret)."
177
+ )
178
+ self._client = GetABrain(
179
+ api_key=key,
180
+ api_secret=secret,
181
+ base_url=self.base_url or os.environ.get("GETABRAIN_BASE_URL"),
182
+ )
183
+ return self._client
184
+
185
+
186
+ class GetABrainAskTool(_GetABrainToolBase):
187
+ """Ask verified humans a question and wait a bounded time for their answers.
188
+
189
+ A live key charges the GetABrain balance for each answer. A test-mode key
190
+ returns simulated answers (marked ``simulated``) and never reaches people.
191
+ """
192
+
193
+ name: str = "getabrain_ask_human"
194
+ description: str = (
195
+ "Ask real, verified people a question and get their answers. Use it for "
196
+ "judgment calls, taste, approvals, or checks a model should not answer "
197
+ "itself. Returns status 'answered' with the answers, or 'pending' with a "
198
+ "query_id if people have not answered within the wait time; then use "
199
+ "getabrain_get_answers later. With a live key each answer costs money "
200
+ "from the GetABrain balance."
201
+ )
202
+ args_schema: type[BaseModel] = GetABrainAskInput
203
+
204
+ max_wait_seconds: float = 60.0
205
+ poll_interval_seconds: float = 5.0
206
+ max_responses: int = 5
207
+ speed: Speed | None = None
208
+
209
+ def _run(
210
+ self,
211
+ question: str,
212
+ query_type: QueryType = "yes_no",
213
+ options: list[str] | None = None,
214
+ context: str | None = None,
215
+ num_responses: int = 1,
216
+ ) -> str:
217
+ if num_responses > self.max_responses:
218
+ return (
219
+ f"Error: num_responses is {num_responses}; this tool allows at most "
220
+ f"{self.max_responses}."
221
+ )
222
+ try:
223
+ content = build_content_data(question, query_type, options, context)
224
+ client = self._get_client()
225
+ except ValueError as exc:
226
+ return f"Error: {exc}"
227
+ body: dict[str, Any] = {
228
+ "type": query_type,
229
+ "title": _title_from(question),
230
+ "content_data": content,
231
+ "required_responses": num_responses,
232
+ }
233
+ if self.speed:
234
+ body["speed"] = self.speed
235
+ try:
236
+ created = client.queries.create(**body)
237
+ query_id = created.get("id") or created.get("query_id")
238
+ if not query_id:
239
+ return f"Error: GetABrain did not return a query id: {created}"
240
+ try:
241
+ client.queries.wait_for_responses(
242
+ query_id,
243
+ min_responses=num_responses,
244
+ timeout_s=self.max_wait_seconds,
245
+ poll_interval_s=self.poll_interval_seconds,
246
+ )
247
+ except GetABrainTimeoutError:
248
+ pass
249
+ query = client.queries.get(query_id)
250
+ except GetABrainError as exc:
251
+ return f"Error: GetABrain error ({exc.status}): {exc.message}"
252
+ return json.dumps(summarize_query(query, done=_is_done(query, num_responses)))
253
+
254
+
255
+ class GetABrainGetAnswersTool(_GetABrainToolBase):
256
+ """Read the current answers to a GetABrain question by its ``query_id``."""
257
+
258
+ name: str = "getabrain_get_answers"
259
+ description: str = (
260
+ "Read the answers people have given so far to an earlier "
261
+ "getabrain_ask_human question, by query_id. Free and read-only."
262
+ )
263
+ args_schema: type[BaseModel] = GetABrainGetAnswersInput
264
+
265
+ def _run(self, query_id: str) -> str:
266
+ try:
267
+ query = self._get_client().queries.get(query_id)
268
+ except ValueError as exc:
269
+ return f"Error: {exc}"
270
+ except GetABrainError as exc:
271
+ return f"Error: GetABrain error ({exc.status}): {exc.message}"
272
+ wanted = query.get("required_responses") or 1
273
+ return json.dumps(summarize_query(query, done=_is_done(query, wanted)))
@@ -0,0 +1,64 @@
1
+ """Run a GetABrain tool directly, then hand the same tool to a CrewAI agent.
2
+
3
+ Environment variables:
4
+ GETABRAIN_API_KEY, GETABRAIN_API_SECRET: your GetABrain key pair. Use a
5
+ test-mode key while building: its answers are simulated, never reach
6
+ people, and come back marked "simulated": true.
7
+ OPENAI_API_KEY or MODEL: only needed for the crew part.
8
+ """
9
+
10
+ import os
11
+
12
+ from crewai import Agent, Crew, Process, Task
13
+
14
+ from crewai_getabrain import GetABrainAskTool, GetABrainGetAnswersTool
15
+
16
+
17
+ def direct_call(ask: GetABrainAskTool) -> None:
18
+ print("Direct call")
19
+ print(
20
+ ask.run(
21
+ question="Which name is easier to remember?",
22
+ query_type="multiple_choice",
23
+ options=["Quillo", "Brightdesk"],
24
+ )
25
+ )
26
+
27
+
28
+ def run_crew(ask: GetABrainAskTool, get_answers: GetABrainGetAnswersTool) -> None:
29
+ agent = Agent(
30
+ role="Product checker",
31
+ goal="Settle judgment calls by asking real people instead of guessing",
32
+ backstory=(
33
+ "You call getabrain_ask_human when a decision needs human judgment. "
34
+ "If the result is pending, you report the query_id."
35
+ ),
36
+ tools=[ask, get_answers],
37
+ verbose=True,
38
+ )
39
+ task = Task(
40
+ description="Find out whether the headline 'Ship faster' is clear to a normal person.",
41
+ expected_output="Yes or no, with what the person said.",
42
+ agent=agent,
43
+ )
44
+ crew = Crew(agents=[agent], tasks=[task], process=Process.sequential, verbose=True)
45
+ print("Crew result")
46
+ print(crew.kickoff())
47
+
48
+
49
+ def main() -> None:
50
+ ask = GetABrainAskTool(max_wait_seconds=60)
51
+ get_answers = GetABrainGetAnswersTool()
52
+ direct_call(ask)
53
+
54
+ if not os.environ.get("OPENAI_API_KEY") and not os.environ.get("MODEL"):
55
+ print()
56
+ print("Set OPENAI_API_KEY, or MODEL for another provider, to run the crew too.")
57
+ return
58
+
59
+ print()
60
+ run_crew(ask, get_answers)
61
+
62
+
63
+ if __name__ == "__main__":
64
+ main()
@@ -0,0 +1,37 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "crewai-getabrain"
7
+ version = "0.1.0"
8
+ description = "CrewAI tools for GetABrain: ask verified humans a question from a crew."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10,<3.14"
11
+ license = "MIT"
12
+ authors = [{ name = "GetABrain", email = "hello@getabrain.ai" }]
13
+ keywords = ["crewai", "getabrain", "human-in-the-loop", "agents", "tools"]
14
+ dependencies = ["crewai>=1.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/crewai-getabrain#readme"
24
+ Source = "https://github.com/Guitarmaniac24/crewai-getabrain"
25
+ "API docs" = "https://www.getabrain.ai/docs"
26
+
27
+ [dependency-groups]
28
+ test = ["pytest>=8"]
29
+
30
+ [tool.hatch.build.targets.wheel]
31
+ packages = ["crewai_getabrain"]
32
+
33
+ [tool.hatch.build.targets.sdist]
34
+ include = ["crewai_getabrain", "tests", "README.md", "LICENSE", "example.py"]
35
+
36
+ [tool.pytest.ini_options]
37
+ testpaths = ["tests"]
@@ -0,0 +1,196 @@
1
+ """Unit tests for the GetABrain CrewAI 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 crewai_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).run(**{"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).run(**{
100
+ "question": "Which name is easier to say?",
101
+ "query_type": "multiple_choice",
102
+ "options": ["Zorblax", "Nimbus"],
103
+ "num_responses": 2,
104
+ })
105
+ )
106
+ assert api.created[0]["content_data"]["options"] == [
107
+ {"id": "1", "text": "Zorblax"},
108
+ {"id": "2", "text": "Nimbus"},
109
+ ]
110
+ assert out["answers_received"] == 2
111
+ assert out["answers"][0]["selected_options"] == ["Nimbus"]
112
+
113
+
114
+ def test_rating_scale_sets_scale() -> None:
115
+ api = FakeApi()
116
+ out = json.loads(
117
+ make_ask(api).run(**{"question": "Rate this tagline", "query_type": "rating_scale"})
118
+ )
119
+ content = api.created[0]["content_data"]
120
+ assert (content["scale_type"], content["scale_min"], content["scale_max"]) == ("1-5", 1, 5)
121
+ assert out["answers"] == [{"rating": 4}]
122
+
123
+
124
+ def test_context_and_speed_are_sent() -> None:
125
+ api = FakeApi()
126
+ make_ask(api, speed="fast").run(**{"question": "Does this read as rude?", "context": "A reply to a customer."})
127
+ assert api.created[0]["content_data"]["context"] == "A reply to a customer."
128
+ assert api.created[0]["speed"] == "fast"
129
+
130
+
131
+ def test_pending_when_wait_runs_out() -> None:
132
+ api = FakeApi(answers_after_polls=10_000)
133
+ out = json.loads(make_ask(api, max_wait_seconds=0).run(**{"question": "Is this funny?"}))
134
+ assert out["status"] == "pending"
135
+ assert out["query_id"] == "q_1"
136
+ assert "getabrain_get_answers" in out["hint"]
137
+
138
+
139
+ def test_get_answers_later() -> None:
140
+ api = FakeApi(answers_after_polls=10_000)
141
+ make_ask(api, max_wait_seconds=0).run(**{"question": "Is this funny?"})
142
+ api.answers_after_polls = 0
143
+ getter = GetABrainGetAnswersTool(client=make_client(api))
144
+ out = json.loads(getter.run(**{"query_id": "q_1"}))
145
+ assert out["status"] == "answered"
146
+ assert out["answers"] == [{"answer": "yes"}]
147
+
148
+
149
+ def test_test_mode_answers_are_marked_simulated() -> None:
150
+ api = FakeApi(test_mode=True)
151
+ out = json.loads(make_ask(api).run(**{"question": "Is this a test?"}))
152
+ assert out["test_mode"] is True
153
+ assert out["answers"][0]["simulated"] is True
154
+ assert "simulated" in out["notice"]
155
+
156
+
157
+ def test_multiple_choice_without_options_is_a_tool_error() -> None:
158
+ api = FakeApi()
159
+ out = make_ask(api).run(**{"question": "Pick one", "query_type": "multiple_choice"})
160
+ assert "at least 2 options" in out
161
+ assert api.created == []
162
+
163
+
164
+ def test_num_responses_cap() -> None:
165
+ api = FakeApi()
166
+ out = make_ask(api, max_responses=3).run(**{"question": "Is it ok?", "num_responses": 4})
167
+ assert "at most 3" in out
168
+ assert api.created == []
169
+
170
+
171
+ def test_api_error_is_returned_to_the_agent() -> None:
172
+ api = FakeApi()
173
+ api.status_code = 402
174
+ api.error_body = {"error": "insufficient_balance", "message": "Balance too low"}
175
+ out = make_ask(api).run(**{"question": "Is it ok?"})
176
+ assert "402" in out and "Balance too low" in out
177
+
178
+
179
+ def test_missing_credentials(monkeypatch: pytest.MonkeyPatch) -> None:
180
+ monkeypatch.delenv("GETABRAIN_API_KEY", raising=False)
181
+ monkeypatch.delenv("GETABRAIN_API_SECRET", raising=False)
182
+ out = GetABrainAskTool().run(**{"question": "Is it ok?"})
183
+ assert "GETABRAIN_API_KEY" in out
184
+
185
+
186
+ def test_long_and_short_questions_make_valid_titles() -> None:
187
+ api = FakeApi()
188
+ make_ask(api).run(**{"question": "x" * 400})
189
+ make_ask(api).run(**{"question": "Ok?"})
190
+ assert len(api.created[0]["title"]) == 255
191
+ assert 5 <= len(api.created[1]["title"]) <= 255
192
+
193
+
194
+ def test_declares_env_vars() -> None:
195
+ names = [v.name for v in GetABrainAskTool().env_vars]
196
+ assert names[:2] == ["GETABRAIN_API_KEY", "GETABRAIN_API_SECRET"]