monkeybrain-broca 1.0.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.
broca/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ """Agent — autonomous query handler with capability discovery."""
2
+
3
+ from broca.agent import Agent, AgentResponse
4
+
5
+ __version__ = "1.0.0"
6
+
7
+ __all__ = ["Agent", "AgentResponse"]
broca/agent.py ADDED
@@ -0,0 +1,228 @@
1
+ """Agent — autonomous query handler with capability discovery.
2
+
3
+ The Agent:
4
+ 1. Discovers available capabilities
5
+ 2. Routes to the appropriate capability pipeline
6
+ 3. Executes the pipeline
7
+ 4. Returns the answer
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import time
13
+ from dataclasses import dataclass, field
14
+ from typing import Any
15
+ from uuid import uuid4
16
+
17
+ try:
18
+ from src.monkey_brain.kernel.pipeline import Pipeline, PipelineStep
19
+ from src.monkey_brain.kernel.execution_state import ExecutionState
20
+ from src.monkey_brain.kernel.rl.policy import BellmanPolicy
21
+ from src.monkey_brain.kernel.observer import Observer
22
+ from src.monkey_brain.kernel.learning import Learning
23
+ from src.monkey_brain.kernel.rl.transition import Transition
24
+ from src.monkey_brain.kernel.intents.intent_router import route_question
25
+ from src.monkey_brain.runtime.runtime import Runtime
26
+ from src.introspection.lemon import Lemon
27
+ from src.cerebellum.fallback_engine import FallbackEngine
28
+ except ImportError:
29
+ Pipeline = None
30
+ PipelineStep = None
31
+ ExecutionState = None
32
+ BellmanPolicy = None
33
+ Observer = None
34
+ Learning = None
35
+ Transition = None
36
+ route_question = None
37
+ Runtime = None
38
+ Lemon = None
39
+ FallbackEngine = None
40
+
41
+
42
+ @dataclass
43
+ class AgentResponse:
44
+ """Response from the Agent."""
45
+
46
+ question: str = ""
47
+ answer: str = ""
48
+ intent: str = ""
49
+ intent_confidence: float = 0.0
50
+ supported: bool = False
51
+ pipeline_id: str = ""
52
+ capabilities_used: list[str] = field(default_factory=list)
53
+ latency_ms: float = 0.0
54
+ success: bool = False
55
+ fallback_used: bool = False
56
+ fallback_details: dict[str, Any] = field(default_factory=dict)
57
+ metrics: dict[str, Any] = field(default_factory=dict)
58
+
59
+
60
+ class Agent:
61
+ """Autonomous query handler with capability discovery.
62
+
63
+ Responsibilities:
64
+ - Discover available capabilities
65
+ - Classify intent
66
+ - Route to capabilities
67
+ - Execute pipeline
68
+ - Return answer
69
+ """
70
+
71
+ def __init__(
72
+ self,
73
+ runtime: Runtime | None = None,
74
+ policy: BellmanPolicy | None = None,
75
+ observer: Observer | None = None,
76
+ learning: Learning | None = None,
77
+ lemon: Lemon | None = None,
78
+ ):
79
+ self._runtime = runtime
80
+ self._policy = policy or (BellmanPolicy() if BellmanPolicy else None)
81
+ self._observer = observer or (Observer() if Observer else None)
82
+ self._learning = learning or (Learning() if Learning else None)
83
+ self._lemon = lemon
84
+ self._fallback_engine = FallbackEngine(runtime) if FallbackEngine and runtime else None
85
+ self._llm_calls = 0
86
+ self._total_tokens = 0
87
+
88
+ def discover_capabilities(self) -> list[str]:
89
+ """Discover available capabilities in the runtime."""
90
+ if self._runtime and hasattr(self._runtime, '_capabilities'):
91
+ return list(self._runtime._capabilities.keys())
92
+ return []
93
+
94
+ def discover_workflows(self) -> dict[str, list[str]]:
95
+ """Discover workflow steps for each capability."""
96
+ workflows = {}
97
+ for cap_name in self.discover_capabilities():
98
+ workflows[cap_name] = [cap_name]
99
+ return workflows
100
+
101
+ async def handle(self, question: str) -> AgentResponse:
102
+ """Handle a question end-to-end."""
103
+ start = time.monotonic()
104
+
105
+ response = AgentResponse(question=question)
106
+
107
+ if self._lemon:
108
+ self._lemon.start_trace(f"agent:{question[:50]}")
109
+
110
+ try:
111
+ # 1. Discover capabilities
112
+ capabilities = self.discover_capabilities()
113
+ response.metrics['available_capabilities'] = capabilities
114
+
115
+ # 2. Route question using classifier
116
+ if route_question:
117
+ routing = route_question(question)
118
+ response.intent = routing.get("intent", "unknown")
119
+ response.intent_confidence = routing.get("confidence", 0)
120
+ response.supported = routing.get("supported", False)
121
+
122
+ # 3. Create pipeline
123
+ if Pipeline and PipelineStep:
124
+ pipeline = Pipeline(
125
+ steps=[
126
+ PipelineStep(capability_name="resolve_entity"),
127
+ PipelineStep(capability_name="retrieve"),
128
+ PipelineStep(capability_name="format"),
129
+ ]
130
+ )
131
+ else:
132
+ response.answer = "Pipeline not available"
133
+ response.latency_ms = (time.monotonic() - start) * 1000
134
+ return response
135
+
136
+ # 4. Policy selects pipeline
137
+ if self._policy and ExecutionState:
138
+ self._policy.select([pipeline], ExecutionState(question=question))
139
+
140
+ # 5. Execute pipeline
141
+ state = ExecutionState(question=question) if ExecutionState else None
142
+ if self._runtime:
143
+ exec_result = await self._runtime.execute(pipeline, state)
144
+ else:
145
+ response.answer = "Runtime not available"
146
+ response.latency_ms = (time.monotonic() - start) * 1000
147
+ return response
148
+
149
+ # 6. Build response
150
+ response.answer = exec_result.final_state.get("answer", "")
151
+ response.pipeline_id = pipeline.pipeline_id
152
+ response.capabilities_used = [s.capability_name for s in exec_result.steps]
153
+ response.success = exec_result.success
154
+ response.latency_ms = (time.monotonic() - start) * 1000
155
+
156
+ # 7. Check if answer needs fallback
157
+ if self._fallback_engine and (response.answer == "No records found." or not response.answer):
158
+ fallback_result = await self._fallback_engine.execute_fallback(
159
+ question=question,
160
+ original_answer=response.answer,
161
+ state=exec_result.final_state,
162
+ )
163
+
164
+ if fallback_result.enhanced_answer != response.answer:
165
+ response.answer = fallback_result.enhanced_answer
166
+ response.fallback_used = True
167
+ response.fallback_details = {
168
+ "documents_found": fallback_result.documents_found,
169
+ "web_results_found": fallback_result.web_results_found,
170
+ "replanned": fallback_result.replaned,
171
+ }
172
+
173
+ if fallback_result.documents_found > 0:
174
+ response.capabilities_used.append("document_search")
175
+ if fallback_result.web_results_found > 0:
176
+ response.capabilities_used.append("web_search")
177
+ if fallback_result.replaned:
178
+ response.capabilities_used.append("replan")
179
+
180
+ # 8. Update policy
181
+ if self._policy and Transition:
182
+ self._policy.update(Transition(
183
+ state=state.to_dict(),
184
+ action=pipeline.pipeline_id,
185
+ reward=0.95 if exec_result.success else 0.1,
186
+ next_state=exec_result.final_state,
187
+ done=True,
188
+ ))
189
+
190
+ # 9. Observe
191
+ if self._observer:
192
+ self._observer.observe(
193
+ capability="agent",
194
+ action="handle",
195
+ input_state=state.to_dict(),
196
+ output_state=exec_result.final_state,
197
+ reward=0.95 if exec_result.success else 0.1,
198
+ latency_ms=response.latency_ms,
199
+ )
200
+
201
+ response.metrics.update({
202
+ "intent_confidence": response.intent_confidence,
203
+ "supported": response.supported,
204
+ "capabilities_count": len(response.capabilities_used),
205
+ "policy_q_entries": len(self._policy._q_table) if self._policy else 0,
206
+ "fallback_used": response.fallback_used,
207
+ })
208
+
209
+ except Exception as e:
210
+ response.success = False
211
+ response.answer = f"Error: {e}"
212
+ response.latency_ms = (time.monotonic() - start) * 1000
213
+
214
+ if self._lemon:
215
+ self._lemon.finish_trace()
216
+
217
+ return response
218
+
219
+ def summary(self) -> dict:
220
+ return {
221
+ "llm_calls": self._llm_calls,
222
+ "total_tokens": self._total_tokens,
223
+ "capabilities_discovered": len(self.discover_capabilities()),
224
+ "observer": self._observer.summary() if self._observer else None,
225
+ "policy": self._policy.summary() if self._policy else None,
226
+ "learning": self._learning.summary() if self._learning else None,
227
+ "fallback": self._fallback_engine.summary() if self._fallback_engine else None,
228
+ }
@@ -0,0 +1,55 @@
1
+ Metadata-Version: 2.4
2
+ Name: monkeybrain-broca
3
+ Version: 1.0.0
4
+ Summary: MonkeyBrain Broca — Autonomous agent for the Cognitive Operating System
5
+ Author: Prashun Javeri
6
+ License: Proprietary
7
+ Keywords: ai,agent,cognitive-os,nlp,routing
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Programming Language :: Python :: 3.14
15
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
16
+ Requires-Python: >=3.11
17
+ Description-Content-Type: text/markdown
18
+ Provides-Extra: full
19
+ Requires-Dist: monkeybrain-cerebellum>=1.0.0; extra == "full"
20
+
21
+ # MonkeyBrain Broca
22
+
23
+ Autonomous agent for the MonkeyBrain Cognitive Operating System.
24
+
25
+ ## Features
26
+
27
+ - **Agent** — autonomous query handler with capability discovery
28
+ - **AgentResponse** — structured response with intent, confidence, and metrics
29
+ - **Capability discovery** — automatic discovery of available capabilities
30
+ - **Pipeline routing** — intent classification and pipeline selection
31
+ - **Fallback engine** — graceful degradation with document/web search
32
+ - **Policy learning** — Bellman Q-learning for pipeline optimization
33
+
34
+ ## Installation
35
+
36
+ ```bash
37
+ pip install monkeybrain-broca
38
+
39
+ # With full dependencies
40
+ pip install monkeybrain-broca[full]
41
+ ```
42
+
43
+ ## Quick Start
44
+
45
+ ```python
46
+ from broca import Agent, AgentResponse
47
+
48
+ agent = Agent(runtime=my_runtime)
49
+ response = await agent.handle("What is the status of line 1?")
50
+ print(response.answer)
51
+ ```
52
+
53
+ ## License
54
+
55
+ Proprietary
@@ -0,0 +1,6 @@
1
+ broca/__init__.py,sha256=4CdqXgNGkIzRt40Fyu7HefWSU4lWMqFNb-kPCCCO7gk,175
2
+ broca/agent.py,sha256=VQz1osbH-3WgqQtZI2T__z0pFZpW_DoAN1ZeA7CYkVY,8989
3
+ monkeybrain_broca-1.0.0.dist-info/METADATA,sha256=Q9yxMLKKQGdvoGoA9lpxXMAQnvWHq_VQ62B23dPkc5E,1670
4
+ monkeybrain_broca-1.0.0.dist-info/WHEEL,sha256=YLJXdYXQ2FQ0Uqn2J-6iEIC-3iOey8lH3xCtvFLkd8Q,91
5
+ monkeybrain_broca-1.0.0.dist-info/top_level.txt,sha256=L13-qEA8WKRhtjmMsUXVmeKqjHW8p8JsD7pajpeVC0o,6
6
+ monkeybrain_broca-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (81.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ broca