vrushket commited on
Commit
cb4e914
·
verified ·
1 Parent(s): 20d6a8a

Initial CogniHive demo upload

Browse files
Files changed (3) hide show
  1. README.md +214 -13
  2. app.py +451 -0
  3. requirements.txt +6 -0
README.md CHANGED
@@ -1,13 +1,214 @@
1
- ---
2
- title: Cognihive
3
- emoji: 📉
4
- colorFrom: blue
5
- colorTo: red
6
- sdk: gradio
7
- sdk_version: 6.2.0
8
- app_file: app.py
9
- pinned: false
10
- license: mit
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: CogniHive
3
+ emoji: "\U0001F41D"
4
+ colorFrom: yellow
5
+ colorTo: red
6
+ sdk: gradio
7
+ sdk_version: 4.44.0
8
+ app_file: app.py
9
+ pinned: true
10
+ license: mit
11
+ short_description: Transactive Memory for Multi-Agent AI
12
+ tags:
13
+ - multi-agent
14
+ - memory
15
+ - ai-agents
16
+ - transactive-memory
17
+ - crewai
18
+ - autogen
19
+ - langgraph
20
+ - collective-intelligence
21
+ - agent-orchestration
22
+ - llm
23
+ ---
24
+
25
+ <div align="center">
26
+
27
+ # 🐝 CogniHive
28
+
29
+ ### The World's First Transactive Memory for Multi-Agent AI
30
+
31
+ **"Mem0 gives one agent a brain. CogniHive gives your agent team a collective mind."**
32
+
33
+ [![GitHub stars](https://img.shields.io/github/stars/vrush/cognihive?style=social)](https://github.com/vrush/cognihive)
34
+ [![PyPI](https://img.shields.io/pypi/v/cognihive)](https://pypi.org/project/cognihive/)
35
+ [![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
36
+
37
+ </div>
38
+
39
+ ---
40
+
41
+ ## 🧠 The Problem No One Has Solved
42
+
43
+ Every multi-agent AI system today suffers from the same problem:
44
+
45
+ > **"Agents don't know what each other knows."**
46
+
47
+ This leads to:
48
+ - 🔄 **Redundant work** - Multiple agents research the same thing
49
+ - 💰 **Token explosion** - 15x more tokens wasted (Anthropic's research)
50
+ - 🎲 **Random routing** - Questions go to the wrong agent
51
+ - 🤷 **Lost expertise** - Agent A learns something, Agent B never finds out
52
+
53
+ ---
54
+
55
+ ## 💡 The Solution: Transactive Memory
56
+
57
+ In human teams, not everyone remembers everything. Instead, teams develop **"who knows what"** awareness:
58
+
59
+ - *"Sarah handles legal stuff"*
60
+ - *"Mike knows the technical details"*
61
+ - *"Ask Jennifer about customer history"*
62
+
63
+ This is called **Transactive Memory Systems (TMS)** — proven by 40 years of cognitive science research to be the #1 predictor of team performance.
64
+
65
+ **CogniHive is the FIRST implementation for AI agents.**
66
+
67
+ ---
68
+
69
+ ## 🎮 Try The Demo
70
+
71
+ ### Tab 1: Who Knows What
72
+ Enter any topic and instantly find which agent is the expert.
73
+
74
+ ### Tab 2: Ask & Route
75
+ Ask a question and watch it automatically route to the right expert.
76
+
77
+ ### Tab 3: Memory
78
+ Store and recall team knowledge with full provenance.
79
+
80
+ ### Tab 4: Agents
81
+ View the expertise matrix across your entire agent team.
82
+
83
+ ---
84
+
85
+ ## ⚡ Quick Start
86
+
87
+ ```bash
88
+ pip install cognihive
89
+ ```
90
+
91
+ ```python
92
+ from cognihive import Hive
93
+
94
+ # Create a hive
95
+ hive = Hive()
96
+
97
+ # Register specialized agents
98
+ hive.register_agent("coder", expertise=["python", "javascript"])
99
+ hive.register_agent("analyst", expertise=["sql", "data"])
100
+ hive.register_agent("writer", expertise=["docs", "tutorials"])
101
+
102
+ # Store team knowledge
103
+ hive.remember(
104
+ "Use connection pooling for 3x database throughput",
105
+ agent="analyst",
106
+ topics=["database", "performance"]
107
+ )
108
+
109
+ # THE KEY INNOVATION: "Who Knows What"
110
+ experts = hive.who_knows("database optimization")
111
+ # Returns: [("analyst", 0.92), ("coder", 0.45)]
112
+
113
+ # Automatic routing to experts
114
+ result = hive.ask("How do I improve query performance?")
115
+ print(f"Routed to: {result['expert']}") # → "analyst"
116
+ ```
117
+
118
+ ---
119
+
120
+ ## 🔗 Works With Your Stack
121
+
122
+ | Framework | Integration | Status |
123
+ |-----------|-------------|--------|
124
+ | **CrewAI** | `CrewAIHive` | ✅ Ready |
125
+ | **AutoGen** | `AutoGenHive` | ✅ Ready |
126
+ | **LangGraph** | `LangGraphHive` | ✅ Ready |
127
+
128
+ ```python
129
+ # CrewAI Example
130
+ from cognihive.integrations import CrewAIHive
131
+
132
+ hive = CrewAIHive()
133
+ researcher = Agent(role="Researcher", memory=hive.agent_memory("researcher"))
134
+ writer = Agent(role="Writer", memory=hive.agent_memory("writer"))
135
+ # Now they share transactive memory!
136
+ ```
137
+
138
+ ---
139
+
140
+ ## 📊 Why This Matters
141
+
142
+ | Metric | Without CogniHive | With CogniHive |
143
+ |--------|-------------------|----------------|
144
+ | Token usage | 15x baseline | 1x baseline |
145
+ | Query routing | Random/manual | Automatic |
146
+ | Team coordination | Chaos | Structured |
147
+ | Knowledge sharing | None | Full provenance |
148
+
149
+ ---
150
+
151
+ ## 🏗️ Architecture
152
+
153
+ ```
154
+ ┌─────────────────────────────────────────────────────┐
155
+ │ CogniHive Core │
156
+ │ ┌───────────────────────────────────────────────┐ │
157
+ │ │ TRANSACTIVE MEMORY INDEX │ │
158
+ │ │ "Who Knows What" - The Key Innovation │ │
159
+ │ │ │ │
160
+ │ │ Coder: python(0.9), api(0.7), testing(0.8)│ │
161
+ │ │ Analyst: sql(0.95), data(0.85) │ │
162
+ │ │ Writer: docs(0.9), tutorials(0.8) │ │
163
+ │ └───────────────────────────────────────────────┘ │
164
+ │ ↓ │
165
+ │ ┌───────────────────────────────────────────────┐ │
166
+ │ │ EXPERTISE ROUTER │ │
167
+ │ │ Query → Best Expert → Relevant Memories │ │
168
+ │ └───────────────────────────────────────────────┘ │
169
+ └─────────────────────────────────────────────────────┘
170
+ ```
171
+
172
+ ---
173
+
174
+ ## 🌟 Features
175
+
176
+ - **🔍 Who Knows What** - Instantly find domain experts
177
+ - **🎯 Smart Routing** - Auto-route queries to the right agent
178
+ - **🔐 Access Control** - Private, shared, and team memories
179
+ - **📝 Provenance** - Track where knowledge came from
180
+ - **⚔️ Conflict Resolution** - Handle contradicting information
181
+ - **🔌 Integrations** - CrewAI, AutoGen, LangGraph ready
182
+
183
+ ---
184
+
185
+ ## 📚 Research Background
186
+
187
+ CogniHive is backed by:
188
+
189
+ - **Wegner (1985)** - Original Transactive Memory Systems theory
190
+ - **Anthropic (2025)** - Multi-agent coordination research showing 15x token overhead
191
+ - **Stanford (2023)** - Generative Agents memory architecture
192
+ - **LLM-MAS Survey (2025)** - Identified "who knows what" as critical missing capability
193
+
194
+ ---
195
+
196
+ ## 🚀 Get Started
197
+
198
+ ```bash
199
+ pip install cognihive
200
+ ```
201
+
202
+ - [GitHub Repository](https://github.com/vrush/cognihive)
203
+ - [PyPI Package](https://pypi.org/project/cognihive/)
204
+ - [Documentation](https://github.com/vrush/cognihive#readme)
205
+
206
+ ---
207
+
208
+ <div align="center">
209
+
210
+ **Built for the multi-agent AI revolution** 🐝
211
+
212
+ *Star us on GitHub if you find this useful!*
213
+
214
+ </div>
app.py ADDED
@@ -0,0 +1,451 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ CogniHive Gradio Demo - HuggingFace Spaces
3
+
4
+ Interactive demo showcasing:
5
+ 1. Agent Network Visualization
6
+ 2. "Who Knows What" Queries
7
+ 3. Live Query Routing
8
+ 4. Memory Storage & Recall
9
+ """
10
+
11
+ import gradio as gr
12
+ from typing import List, Tuple, Dict, Any
13
+ import json
14
+
15
+ # Import CogniHive
16
+ from cognihive import Hive
17
+
18
+
19
+ # ============================================================================
20
+ # Global Hive Instance (shared across demo)
21
+ # ============================================================================
22
+
23
+ def create_demo_hive() -> Hive:
24
+ """Create a pre-populated demo hive."""
25
+ hive = Hive(name="demo")
26
+
27
+ # Register diverse agents
28
+ hive.register_agent(
29
+ "python_expert",
30
+ expertise=["python", "fastapi", "django", "testing", "async"],
31
+ role="Python Developer"
32
+ )
33
+ hive.register_agent(
34
+ "data_scientist",
35
+ expertise=["sql", "pandas", "machine-learning", "analytics", "statistics"],
36
+ role="Data Scientist"
37
+ )
38
+ hive.register_agent(
39
+ "frontend_dev",
40
+ expertise=["react", "typescript", "css", "javascript", "ui-ux"],
41
+ role="Frontend Developer"
42
+ )
43
+ hive.register_agent(
44
+ "devops_engineer",
45
+ expertise=["docker", "kubernetes", "aws", "ci-cd", "terraform"],
46
+ role="DevOps Engineer"
47
+ )
48
+ hive.register_agent(
49
+ "tech_writer",
50
+ expertise=["documentation", "api-docs", "tutorials", "examples"],
51
+ role="Technical Writer"
52
+ )
53
+
54
+ # Pre-populate with knowledge
55
+ memories = [
56
+ ("Use async/await with FastAPI for 10x better performance", "python_expert", ["python", "fastapi", "performance"]),
57
+ ("pytest-asyncio is essential for testing async code", "python_expert", ["python", "testing", "async"]),
58
+ ("Connection pooling with asyncpg gives 3x throughput", "data_scientist", ["sql", "performance", "postgres"]),
59
+ ("Use EXPLAIN ANALYZE to debug slow queries", "data_scientist", ["sql", "debugging", "optimization"]),
60
+ ("React 19 Server Components reduce bundle by 40%", "frontend_dev", ["react", "performance", "server-components"]),
61
+ ("CSS container queries > media queries for components", "frontend_dev", ["css", "responsive", "modern"]),
62
+ ("Use multi-stage Docker builds for smaller images", "devops_engineer", ["docker", "optimization", "best-practices"]),
63
+ ("Terraform state should be stored in S3 with locking", "devops_engineer", ["terraform", "aws", "infrastructure"]),
64
+ ("Always include code examples in API documentation", "tech_writer", ["documentation", "api-docs", "best-practices"]),
65
+ ("Use OpenAPI specs to auto-generate client libraries", "tech_writer", ["api-docs", "openapi", "automation"]),
66
+ ]
67
+
68
+ for content, agent, topics in memories:
69
+ hive.remember(content, agent=agent, topics=topics)
70
+
71
+ return hive
72
+
73
+
74
+ # Global hive
75
+ HIVE = create_demo_hive()
76
+
77
+
78
+ # ============================================================================
79
+ # Gradio Interface Functions
80
+ # ============================================================================
81
+
82
+ def get_agents_display() -> str:
83
+ """Get formatted display of all agents and their expertise."""
84
+ lines = ["## Registered Agents\n"]
85
+
86
+ matrix = HIVE.expertise_matrix()
87
+ for agent_name, domains in matrix.items():
88
+ agent = HIVE.get_agent(agent_name)
89
+ role = agent.role if agent else ""
90
+
91
+ top_domains = sorted(domains.items(), key=lambda x: x[1], reverse=True)[:5]
92
+ domain_badges = " ".join([f"`{d}`" for d, _ in top_domains if _ > 0.3])
93
+
94
+ lines.append(f"### {agent_name}")
95
+ lines.append(f"**Role:** {role}")
96
+ lines.append(f"**Expertise:** {domain_badges}")
97
+ lines.append("")
98
+
99
+ return "\n".join(lines)
100
+
101
+
102
+ def who_knows_query(topic: str) -> Tuple[str, str]:
103
+ """Query who knows about a topic."""
104
+ if not topic.strip():
105
+ return "Please enter a topic to search.", ""
106
+
107
+ experts = HIVE.who_knows(topic)
108
+
109
+ if not experts:
110
+ return f"No experts found for: **{topic}**", ""
111
+
112
+ # Format results
113
+ lines = [f"## Experts on '{topic}'\n"]
114
+
115
+ chart_data = []
116
+ for name, score in experts:
117
+ agent = HIVE.get_agent(name)
118
+ role = agent.role if agent else ""
119
+
120
+ # Visual bar
121
+ bar_width = int(score * 20)
122
+ bar = "█" * bar_width + "░" * (20 - bar_width)
123
+
124
+ lines.append(f"**{name}** ({role})")
125
+ lines.append(f"`[{bar}]` {score:.2f}")
126
+ lines.append("")
127
+
128
+ chart_data.append({"agent": name, "score": score})
129
+
130
+ return "\n".join(lines), json.dumps(chart_data, indent=2)
131
+
132
+
133
+ def ask_query(question: str) -> Tuple[str, str, str]:
134
+ """Ask a question and get routed to an expert."""
135
+ if not question.strip():
136
+ return "Please enter a question.", "", ""
137
+
138
+ result = HIVE.ask(question)
139
+
140
+ # Format routing decision
141
+ routing_lines = ["## Routing Decision\n"]
142
+ routing_lines.append(f"**Question:** {question}")
143
+ routing_lines.append("")
144
+ routing_lines.append(f"**Routed to:** {result['expert'] or 'No expert found'}")
145
+ routing_lines.append(f"**Confidence:** {result['confidence']:.2f}")
146
+
147
+ if result['secondary_experts']:
148
+ routing_lines.append(f"**Secondary experts:** {', '.join(result['secondary_experts'])}")
149
+
150
+ routing_lines.append("")
151
+ routing_lines.append("### Reasoning")
152
+ routing_lines.append(result['reasoning'] or "No specific reasoning available.")
153
+
154
+ # Format memories
155
+ memory_lines = ["## Relevant Memories\n"]
156
+ if result['memories']:
157
+ for i, (mem, score) in enumerate(zip(result['memories'], result['scores']), 1):
158
+ memory_lines.append(f"**{i}. From {mem.owner_name}** (relevance: {score:.2f})")
159
+ memory_lines.append(f"> {mem.content}")
160
+ memory_lines.append("")
161
+ else:
162
+ memory_lines.append("No relevant memories found.")
163
+
164
+ return "\n".join(routing_lines), "\n".join(memory_lines), result['expert']
165
+
166
+
167
+ def add_memory(content: str, agent: str, topics: str) -> str:
168
+ """Add a new memory to the hive."""
169
+ if not content.strip():
170
+ return "Please enter memory content."
171
+
172
+ if not agent.strip():
173
+ return "Please select an agent."
174
+
175
+ topic_list = [t.strip() for t in topics.split(",") if t.strip()]
176
+
177
+ try:
178
+ memory = HIVE.remember(content, agent=agent, topics=topic_list)
179
+ return f"Memory stored successfully!\n\n**ID:** `{memory.id[:8]}...`\n**Agent:** {agent}\n**Topics:** {', '.join(topic_list) or 'None'}"
180
+ except Exception as e:
181
+ return f"Error storing memory: {str(e)}"
182
+
183
+
184
+ def recall_memories(query: str) -> str:
185
+ """Search for memories."""
186
+ if not query.strip():
187
+ return "Please enter a search query."
188
+
189
+ results = HIVE.recall(query, top_k=5)
190
+
191
+ if not results:
192
+ return f"No memories found for: **{query}**"
193
+
194
+ lines = [f"## Memories matching '{query}'\n"]
195
+
196
+ for i, (memory, score) in enumerate(results, 1):
197
+ lines.append(f"### {i}. {memory.owner_name} (score: {score:.2f})")
198
+ lines.append(f"> {memory.content}")
199
+ if memory.topics:
200
+ lines.append(f"**Topics:** {', '.join(memory.topics)}")
201
+ lines.append("")
202
+
203
+ return "\n".join(lines)
204
+
205
+
206
+ def get_hive_stats() -> str:
207
+ """Get hive statistics."""
208
+ stats = HIVE.stats()
209
+
210
+ lines = [
211
+ "## Hive Statistics\n",
212
+ f"**Name:** {stats['name']}",
213
+ f"**Agents:** {stats['agent_count']}",
214
+ f"**Memories:** {stats['memory_count']}",
215
+ f"**Queries Processed:** {stats['metrics']['queries_processed']}",
216
+ f"**Routing Decisions:** {stats['metrics']['routing_decisions']}",
217
+ ]
218
+
219
+ return "\n".join(lines)
220
+
221
+
222
+ def reset_hive() -> str:
223
+ """Reset the hive to initial state."""
224
+ global HIVE
225
+ HIVE = create_demo_hive()
226
+ return "Hive reset to initial state with demo data."
227
+
228
+
229
+ # ============================================================================
230
+ # Build Gradio Interface
231
+ # ============================================================================
232
+
233
+ def create_demo():
234
+ """Create the Gradio demo interface."""
235
+
236
+ with gr.Blocks(
237
+ title="CogniHive - Transactive Memory for AI Agents",
238
+ theme=gr.themes.Soft(
239
+ primary_hue="amber",
240
+ secondary_hue="orange",
241
+ ),
242
+ css="""
243
+ .gradio-container { max-width: 1200px !important; }
244
+ .main-header { text-align: center; margin-bottom: 20px; }
245
+ .feature-box { border: 1px solid #e0e0e0; border-radius: 8px; padding: 15px; margin: 10px 0; }
246
+ """
247
+ ) as demo:
248
+
249
+ # Header
250
+ gr.Markdown("""
251
+ # CogniHive
252
+ ### The World's First Transactive Memory System for Multi-Agent AI
253
+
254
+ **"Mem0 gives one agent a brain. CogniHive gives your agent team a collective mind."**
255
+
256
+ ---
257
+ """)
258
+
259
+ with gr.Tabs():
260
+
261
+ # Tab 1: Who Knows What
262
+ with gr.TabItem("Who Knows What"):
263
+ gr.Markdown("""
264
+ ## Find Experts on Any Topic
265
+
266
+ This is the core innovation of CogniHive: **Transactive Memory**.
267
+ Ask "who knows about X" and find the right expert instantly.
268
+ """)
269
+
270
+ with gr.Row():
271
+ with gr.Column(scale=1):
272
+ topic_input = gr.Textbox(
273
+ label="Topic to search",
274
+ placeholder="e.g., python optimization, database security, react components",
275
+ lines=1
276
+ )
277
+ who_knows_btn = gr.Button("Find Experts", variant="primary")
278
+
279
+ gr.Examples(
280
+ examples=[
281
+ ["python async programming"],
282
+ ["database optimization"],
283
+ ["react performance"],
284
+ ["docker best practices"],
285
+ ["API documentation"],
286
+ ],
287
+ inputs=topic_input,
288
+ label="Try these topics:"
289
+ )
290
+
291
+ with gr.Column(scale=2):
292
+ who_knows_output = gr.Markdown(label="Expert Results")
293
+ who_knows_data = gr.Code(label="Raw Data (JSON)", language="json", visible=False)
294
+
295
+ who_knows_btn.click(
296
+ who_knows_query,
297
+ inputs=[topic_input],
298
+ outputs=[who_knows_output, who_knows_data]
299
+ )
300
+
301
+ # Tab 2: Ask a Question
302
+ with gr.TabItem("Ask & Route"):
303
+ gr.Markdown("""
304
+ ## Automatic Query Routing
305
+
306
+ Ask any question and CogniHive will automatically route it to the best expert
307
+ and retrieve relevant memories.
308
+ """)
309
+
310
+ with gr.Row():
311
+ with gr.Column(scale=1):
312
+ question_input = gr.Textbox(
313
+ label="Your Question",
314
+ placeholder="e.g., How do I improve my Python code performance?",
315
+ lines=2
316
+ )
317
+ ask_btn = gr.Button("Ask the Hive", variant="primary")
318
+
319
+ routed_to = gr.Textbox(label="Routed to Expert", interactive=False)
320
+
321
+ gr.Examples(
322
+ examples=[
323
+ ["How do I write better async Python code?"],
324
+ ["What's the best way to optimize SQL queries?"],
325
+ ["How should I structure my React components?"],
326
+ ["What are Docker best practices?"],
327
+ ["How do I document my API effectively?"],
328
+ ],
329
+ inputs=question_input,
330
+ label="Try these questions:"
331
+ )
332
+
333
+ with gr.Column(scale=2):
334
+ routing_output = gr.Markdown(label="Routing Decision")
335
+ memories_output = gr.Markdown(label="Relevant Memories")
336
+
337
+ ask_btn.click(
338
+ ask_query,
339
+ inputs=[question_input],
340
+ outputs=[routing_output, memories_output, routed_to]
341
+ )
342
+
343
+ # Tab 3: Memory Operations
344
+ with gr.TabItem("Memory"):
345
+ gr.Markdown("""
346
+ ## Store & Recall Team Knowledge
347
+
348
+ Add new memories to the hive or search existing knowledge.
349
+ """)
350
+
351
+ with gr.Row():
352
+ # Add memory
353
+ with gr.Column():
354
+ gr.Markdown("### Add New Memory")
355
+ memory_content = gr.Textbox(
356
+ label="Memory Content",
357
+ placeholder="Enter knowledge to store...",
358
+ lines=3
359
+ )
360
+ memory_agent = gr.Dropdown(
361
+ label="Agent",
362
+ choices=["python_expert", "data_scientist", "frontend_dev", "devops_engineer", "tech_writer"],
363
+ value="python_expert"
364
+ )
365
+ memory_topics = gr.Textbox(
366
+ label="Topics (comma-separated)",
367
+ placeholder="e.g., python, performance, tips"
368
+ )
369
+ add_memory_btn = gr.Button("Store Memory", variant="primary")
370
+ add_result = gr.Markdown()
371
+
372
+ # Search memories
373
+ with gr.Column():
374
+ gr.Markdown("### Search Memories")
375
+ search_query = gr.Textbox(
376
+ label="Search Query",
377
+ placeholder="Search for relevant memories...",
378
+ lines=1
379
+ )
380
+ search_btn = gr.Button("Search", variant="secondary")
381
+ search_results = gr.Markdown()
382
+
383
+ add_memory_btn.click(
384
+ add_memory,
385
+ inputs=[memory_content, memory_agent, memory_topics],
386
+ outputs=[add_result]
387
+ )
388
+
389
+ search_btn.click(
390
+ recall_memories,
391
+ inputs=[search_query],
392
+ outputs=[search_results]
393
+ )
394
+
395
+ # Tab 4: Agent Network
396
+ with gr.TabItem("Agents"):
397
+ gr.Markdown("""
398
+ ## Agent Network & Expertise
399
+
400
+ View all registered agents and their areas of expertise.
401
+ """)
402
+
403
+ with gr.Row():
404
+ with gr.Column():
405
+ refresh_btn = gr.Button("Refresh Agent List")
406
+ agents_display = gr.Markdown(value=get_agents_display())
407
+
408
+ with gr.Column():
409
+ stats_display = gr.Markdown(value=get_hive_stats(), label="Hive Stats")
410
+ reset_btn = gr.Button("Reset Hive", variant="secondary")
411
+ reset_result = gr.Markdown()
412
+
413
+ refresh_btn.click(get_agents_display, outputs=[agents_display])
414
+ refresh_btn.click(get_hive_stats, outputs=[stats_display])
415
+ reset_btn.click(reset_hive, outputs=[reset_result])
416
+
417
+ # Footer
418
+ gr.Markdown("""
419
+ ---
420
+
421
+ ### About CogniHive
422
+
423
+ CogniHive implements **Transactive Memory Systems (TMS)** for AI agents -
424
+ a concept from cognitive science that enables teams to know "who knows what."
425
+
426
+ **Key Features:**
427
+ - "Who Knows What" queries
428
+ - Automatic expert routing
429
+ - Memory with access control
430
+ - Framework integrations (CrewAI, AutoGen, LangGraph)
431
+
432
+ [GitHub](https://github.com/vrush/cognihive) | [PyPI](https://pypi.org/project/cognihive/)
433
+
434
+ ---
435
+ *Built with Gradio | Powered by ChromaDB*
436
+ """)
437
+
438
+ return demo
439
+
440
+
441
+ # ============================================================================
442
+ # Main
443
+ # ============================================================================
444
+
445
+ if __name__ == "__main__":
446
+ demo = create_demo()
447
+ demo.launch(
448
+ share=False,
449
+ server_name="0.0.0.0",
450
+ server_port=7860
451
+ )
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ gradio>=4.0.0
2
+ chromadb>=0.4.0
3
+ sentence-transformers>=2.2.0
4
+ pydantic>=2.0.0
5
+ numpy>=1.24.0
6
+ rich>=13.0.0