hipcortex 0.3.2__tar.gz → 0.5.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.
Files changed (54) hide show
  1. hipcortex-0.5.0/PKG-INFO +162 -0
  2. hipcortex-0.5.0/README.md +118 -0
  3. {hipcortex-0.3.2 → hipcortex-0.5.0}/hipcortex/__init__.py +15 -15
  4. hipcortex-0.5.0/hipcortex/adapters/__init__.py +13 -0
  5. {hipcortex-0.3.2 → hipcortex-0.5.0}/hipcortex/adapters/autogen.py +175 -156
  6. hipcortex-0.5.0/hipcortex/adapters/common.py +151 -0
  7. {hipcortex-0.3.2 → hipcortex-0.5.0}/hipcortex/adapters/crewai.py +173 -153
  8. {hipcortex-0.3.2 → hipcortex-0.5.0}/hipcortex/async_client.py +378 -255
  9. hipcortex-0.5.0/hipcortex/cli.py +1652 -0
  10. {hipcortex-0.3.2 → hipcortex-0.5.0}/hipcortex/client.py +160 -2
  11. hipcortex-0.5.0/hipcortex/config.py +270 -0
  12. hipcortex-0.5.0/hipcortex/daemon.py +543 -0
  13. hipcortex-0.5.0/hipcortex/doctor.py +594 -0
  14. hipcortex-0.5.0/hipcortex/framework_scaffold.py +405 -0
  15. {hipcortex-0.3.2 → hipcortex-0.5.0}/hipcortex/indexer.py +219 -219
  16. {hipcortex-0.3.2 → hipcortex-0.5.0}/hipcortex/install/SKILL.md +162 -144
  17. {hipcortex-0.3.2 → hipcortex-0.5.0}/hipcortex/install/__init__.py +1 -1
  18. hipcortex-0.5.0/hipcortex/install/templates/autogen.py.tmpl +24 -0
  19. hipcortex-0.5.0/hipcortex/install/templates/crewai.py.tmpl +24 -0
  20. hipcortex-0.5.0/hipcortex/install/templates/dspy.py.tmpl +21 -0
  21. hipcortex-0.5.0/hipcortex/install/templates/langchain.py.tmpl +17 -0
  22. hipcortex-0.5.0/hipcortex/install/templates/llamaindex.py.tmpl +23 -0
  23. hipcortex-0.5.0/hipcortex/install/templates/n8n_curl.sh.tmpl +17 -0
  24. hipcortex-0.5.0/hipcortex/install/templates/pydantic_ai.py.tmpl +22 -0
  25. hipcortex-0.5.0/hipcortex/install_hosts.py +997 -0
  26. {hipcortex-0.3.2 → hipcortex-0.5.0}/hipcortex/langchain_memory.py +282 -238
  27. {hipcortex-0.3.2 → hipcortex-0.5.0}/hipcortex/llamaindex_storage.py +107 -107
  28. hipcortex-0.5.0/hipcortex.egg-info/PKG-INFO +162 -0
  29. hipcortex-0.5.0/hipcortex.egg-info/SOURCES.txt +45 -0
  30. {hipcortex-0.3.2 → hipcortex-0.5.0}/hipcortex.egg-info/requires.txt +4 -0
  31. {hipcortex-0.3.2 → hipcortex-0.5.0}/pyproject.toml +53 -49
  32. {hipcortex-0.3.2 → hipcortex-0.5.0}/setup.py +35 -35
  33. hipcortex-0.5.0/tests/test_adapters_common.py +178 -0
  34. {hipcortex-0.3.2 → hipcortex-0.5.0}/tests/test_async_client.py +101 -60
  35. {hipcortex-0.3.2 → hipcortex-0.5.0}/tests/test_async_langchain.py +61 -61
  36. hipcortex-0.5.0/tests/test_cli_install.py +2241 -0
  37. hipcortex-0.5.0/tests/test_client_config.py +57 -0
  38. hipcortex-0.5.0/tests/test_config.py +343 -0
  39. hipcortex-0.5.0/tests/test_daemon.py +415 -0
  40. hipcortex-0.5.0/tests/test_doctor.py +844 -0
  41. hipcortex-0.5.0/tests/test_harness_with_loop.py +80 -0
  42. hipcortex-0.5.0/tests/test_host_install_e2e.py +145 -0
  43. hipcortex-0.5.0/tests/test_reflect_predict.py +64 -0
  44. hipcortex-0.3.2/PKG-INFO +0 -108
  45. hipcortex-0.3.2/README.md +0 -67
  46. hipcortex-0.3.2/hipcortex/adapters/__init__.py +0 -1
  47. hipcortex-0.3.2/hipcortex/cli.py +0 -1221
  48. hipcortex-0.3.2/hipcortex.egg-info/PKG-INFO +0 -108
  49. hipcortex-0.3.2/hipcortex.egg-info/SOURCES.txt +0 -24
  50. hipcortex-0.3.2/tests/test_cli_install.py +0 -137
  51. {hipcortex-0.3.2 → hipcortex-0.5.0}/hipcortex.egg-info/dependency_links.txt +0 -0
  52. {hipcortex-0.3.2 → hipcortex-0.5.0}/hipcortex.egg-info/entry_points.txt +0 -0
  53. {hipcortex-0.3.2 → hipcortex-0.5.0}/hipcortex.egg-info/top_level.txt +0 -0
  54. {hipcortex-0.3.2 → hipcortex-0.5.0}/setup.cfg +0 -0
@@ -0,0 +1,162 @@
1
+ Metadata-Version: 2.4
2
+ Name: hipcortex
3
+ Version: 0.5.0
4
+ Summary: Persistent causal memory for AI agents -- LangChain, LlamaIndex, AutoGen, CrewAI
5
+ Author: HipCortex Contributors
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/farmountain/HipCortex
8
+ Project-URL: Repository, https://github.com/farmountain/HipCortex
9
+ Project-URL: Issues, https://github.com/farmountain/HipCortex/issues
10
+ Project-URL: Benchmark, https://github.com/farmountain/HipCortex/blob/main/BENCHMARK.md
11
+ Keywords: ai,memory,langchain,autogen,crewai,llm,agents,rag
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
15
+ Classifier: Intended Audience :: Developers
16
+ Requires-Python: >=3.9
17
+ Description-Content-Type: text/markdown
18
+ Requires-Dist: requests>=2.28
19
+ Requires-Dist: httpx>=0.27
20
+ Provides-Extra: langchain
21
+ Requires-Dist: langchain-core>=0.1; extra == "langchain"
22
+ Provides-Extra: llamaindex
23
+ Requires-Dist: llama-index-core>=0.10; extra == "llamaindex"
24
+ Provides-Extra: crewai
25
+ Requires-Dist: crewai>=0.28; extra == "crewai"
26
+ Requires-Dist: crewai-tools>=0.1; extra == "crewai"
27
+ Provides-Extra: autogen
28
+ Requires-Dist: pyautogen>=0.2; extra == "autogen"
29
+ Provides-Extra: benchmark
30
+ Requires-Dist: mem0ai>=0.1; extra == "benchmark"
31
+ Requires-Dist: tabulate>=0.9; extra == "benchmark"
32
+ Provides-Extra: test
33
+ Requires-Dist: pytest>=7.0; extra == "test"
34
+ Requires-Dist: pytest-asyncio>=0.23; extra == "test"
35
+ Provides-Extra: all
36
+ Requires-Dist: langchain-core>=0.1; extra == "all"
37
+ Requires-Dist: llama-index-core>=0.10; extra == "all"
38
+ Requires-Dist: crewai>=0.28; extra == "all"
39
+ Requires-Dist: crewai-tools>=0.1; extra == "all"
40
+ Requires-Dist: pyautogen>=0.2; extra == "all"
41
+ Requires-Dist: mem0ai>=0.1; extra == "all"
42
+ Requires-Dist: tabulate>=0.9; extra == "all"
43
+ Dynamic: requires-python
44
+
45
+ # HipCortex Python SDK (`v0.5.0`)
46
+
47
+ **Persistent causal topological memory, recursive Bayesian world-model prediction (`/worldmodel/rollout`), and automatic FSM skill compilation for autonomous AI agents.**
48
+
49
+ Runs against the standalone local Rust binary (`http://127.0.0.1:3030`) with `0.48–0.61 ms p50` write latency, SHA-256 Merkle audit chains, and Headroom context budgeting (`59–88% token savings`).
50
+
51
+ ---
52
+
53
+ ## 🚀 Installation
54
+
55
+ ```bash
56
+ pip install hipcortex
57
+ hipcortex doctor # verify server health + version after install
58
+ ```
59
+
60
+ ---
61
+
62
+ ## ⚡ Quick Start: Multi-Tier Memory & World Model Prediction
63
+
64
+ ```python
65
+ from hipcortex import HipCortexClient
66
+
67
+ client = HipCortexClient(base_url="http://127.0.0.1:3030")
68
+
69
+ # 1. Multi-Tier Memory Ingestion (5 verified memory tiers)
70
+ client.add_memory(
71
+ actor="agent",
72
+ action="configured",
73
+ target="jwt_token_ttl=3600",
74
+ record_type="Working", # Mapped natively to Temporal tier
75
+ priority="high"
76
+ )
77
+
78
+ client.add_memory(
79
+ actor="agent",
80
+ action="established",
81
+ target="All database migrations must run inside transactions",
82
+ record_type="Semantic", # Mapped natively to Symbolic/LongTerm tier
83
+ priority="pinned"
84
+ )
85
+
86
+ # 2. Check SelfModel Execution Capacity Gates before running risky actions
87
+ if client.can_execute("rollout"):
88
+ print("Health check passed — engine ready for simulation")
89
+
90
+ # 3. World Model Trajectory Rollout Prediction (POST /worldmodel/rollout)
91
+ rollout_result = client.rollout(
92
+ initial_state={"db_status": "locked", "active_tx": 1},
93
+ actions=["rollback_tx", "release_lock", "retry_migration"]
94
+ )
95
+ print("Predicted outcome:", rollout_result)
96
+ ```
97
+
98
+ ---
99
+
100
+ ## 🧠 Proactive CodeAct Harness & Live Beliefs
101
+
102
+ For autonomous agent harnesses (`LangChain`, `LlamaIndex`, `CrewAI`, `AutoGen`), query the topological substrate before reasoning:
103
+
104
+ ```python
105
+ # Query live causal beliefs and Top-K topological context (Personalized PageRank)
106
+ context = client.context(query="database migrations", actor="agent", limit=5)
107
+ print("Active Topological Context:\n", context)
108
+
109
+ # Store multi-hop reasoning or CoT reflection
110
+ client.add_memory(
111
+ actor="agent",
112
+ action="reflected",
113
+ target="Migration failed due to missing index on users.email",
114
+ record_type="Causal"
115
+ )
116
+ ```
117
+
118
+ ---
119
+
120
+ ## 🧩 Framework Integrations
121
+
122
+ ### LangChain (`ConversationBufferMemory` drop-in)
123
+ ```python
124
+ from hipcortex.langchain_memory import HipCortexMemory
125
+
126
+ memory = HipCortexMemory(session_id="session-42", url="http://127.0.0.1:3030")
127
+ ```
128
+
129
+ ### LlamaIndex (`ChatStore`)
130
+ ```python
131
+ from hipcortex.llamaindex_storage import HipCortexStorageContext
132
+
133
+ storage_context = HipCortexStorageContext.from_defaults(client=client)
134
+ ```
135
+
136
+ ### CrewAI (`Remember` & `Recall` Tools)
137
+ ```python
138
+ from hipcortex.adapters.crewai import HipCortexRememberTool, HipCortexRecallTool
139
+
140
+ tools = [HipCortexRememberTool(client=client), HipCortexRecallTool(client=client)]
141
+ ```
142
+
143
+ ### AutoGen (`Memory` Hook)
144
+ ```python
145
+ from hipcortex.adapters.autogen import HipCortexAutoGenMemory
146
+
147
+ mem = HipCortexAutoGenMemory(client=client, agent_id="researcher")
148
+ agent.register_hook("process_message_before_send", mem.on_message_sent)
149
+ ```
150
+
151
+ ---
152
+
153
+ ## 📊 Server Statistics & GDPR Right-to-Forget
154
+
155
+ ```python
156
+ # Get Merkle hash chain status and tier counts
157
+ stats = client.stats()
158
+ print("Memory statistics:", stats)
159
+
160
+ # Erase all records for a specific actor (GDPR compliant)
161
+ client.forget("agent")
162
+ ```
@@ -0,0 +1,118 @@
1
+ # HipCortex Python SDK (`v0.5.0`)
2
+
3
+ **Persistent causal topological memory, recursive Bayesian world-model prediction (`/worldmodel/rollout`), and automatic FSM skill compilation for autonomous AI agents.**
4
+
5
+ Runs against the standalone local Rust binary (`http://127.0.0.1:3030`) with `0.48–0.61 ms p50` write latency, SHA-256 Merkle audit chains, and Headroom context budgeting (`59–88% token savings`).
6
+
7
+ ---
8
+
9
+ ## 🚀 Installation
10
+
11
+ ```bash
12
+ pip install hipcortex
13
+ hipcortex doctor # verify server health + version after install
14
+ ```
15
+
16
+ ---
17
+
18
+ ## ⚡ Quick Start: Multi-Tier Memory & World Model Prediction
19
+
20
+ ```python
21
+ from hipcortex import HipCortexClient
22
+
23
+ client = HipCortexClient(base_url="http://127.0.0.1:3030")
24
+
25
+ # 1. Multi-Tier Memory Ingestion (5 verified memory tiers)
26
+ client.add_memory(
27
+ actor="agent",
28
+ action="configured",
29
+ target="jwt_token_ttl=3600",
30
+ record_type="Working", # Mapped natively to Temporal tier
31
+ priority="high"
32
+ )
33
+
34
+ client.add_memory(
35
+ actor="agent",
36
+ action="established",
37
+ target="All database migrations must run inside transactions",
38
+ record_type="Semantic", # Mapped natively to Symbolic/LongTerm tier
39
+ priority="pinned"
40
+ )
41
+
42
+ # 2. Check SelfModel Execution Capacity Gates before running risky actions
43
+ if client.can_execute("rollout"):
44
+ print("Health check passed — engine ready for simulation")
45
+
46
+ # 3. World Model Trajectory Rollout Prediction (POST /worldmodel/rollout)
47
+ rollout_result = client.rollout(
48
+ initial_state={"db_status": "locked", "active_tx": 1},
49
+ actions=["rollback_tx", "release_lock", "retry_migration"]
50
+ )
51
+ print("Predicted outcome:", rollout_result)
52
+ ```
53
+
54
+ ---
55
+
56
+ ## 🧠 Proactive CodeAct Harness & Live Beliefs
57
+
58
+ For autonomous agent harnesses (`LangChain`, `LlamaIndex`, `CrewAI`, `AutoGen`), query the topological substrate before reasoning:
59
+
60
+ ```python
61
+ # Query live causal beliefs and Top-K topological context (Personalized PageRank)
62
+ context = client.context(query="database migrations", actor="agent", limit=5)
63
+ print("Active Topological Context:\n", context)
64
+
65
+ # Store multi-hop reasoning or CoT reflection
66
+ client.add_memory(
67
+ actor="agent",
68
+ action="reflected",
69
+ target="Migration failed due to missing index on users.email",
70
+ record_type="Causal"
71
+ )
72
+ ```
73
+
74
+ ---
75
+
76
+ ## 🧩 Framework Integrations
77
+
78
+ ### LangChain (`ConversationBufferMemory` drop-in)
79
+ ```python
80
+ from hipcortex.langchain_memory import HipCortexMemory
81
+
82
+ memory = HipCortexMemory(session_id="session-42", url="http://127.0.0.1:3030")
83
+ ```
84
+
85
+ ### LlamaIndex (`ChatStore`)
86
+ ```python
87
+ from hipcortex.llamaindex_storage import HipCortexStorageContext
88
+
89
+ storage_context = HipCortexStorageContext.from_defaults(client=client)
90
+ ```
91
+
92
+ ### CrewAI (`Remember` & `Recall` Tools)
93
+ ```python
94
+ from hipcortex.adapters.crewai import HipCortexRememberTool, HipCortexRecallTool
95
+
96
+ tools = [HipCortexRememberTool(client=client), HipCortexRecallTool(client=client)]
97
+ ```
98
+
99
+ ### AutoGen (`Memory` Hook)
100
+ ```python
101
+ from hipcortex.adapters.autogen import HipCortexAutoGenMemory
102
+
103
+ mem = HipCortexAutoGenMemory(client=client, agent_id="researcher")
104
+ agent.register_hook("process_message_before_send", mem.on_message_sent)
105
+ ```
106
+
107
+ ---
108
+
109
+ ## 📊 Server Statistics & GDPR Right-to-Forget
110
+
111
+ ```python
112
+ # Get Merkle hash chain status and tier counts
113
+ stats = client.stats()
114
+ print("Memory statistics:", stats)
115
+
116
+ # Erase all records for a specific actor (GDPR compliant)
117
+ client.forget("agent")
118
+ ```
@@ -1,15 +1,15 @@
1
- """HipCortex Python SDK — AI memory engine client."""
2
-
3
- from .client import HipCortexClient
4
- from .async_client import AsyncHipCortexClient
5
- from .langchain_memory import HipCortexMemory, AsyncHipCortexMemory
6
- from .llamaindex_storage import HipCortexStorageContext
7
-
8
- __version__ = "0.2.0"
9
- __all__ = [
10
- "HipCortexClient",
11
- "AsyncHipCortexClient",
12
- "HipCortexMemory",
13
- "AsyncHipCortexMemory",
14
- "HipCortexStorageContext",
15
- ]
1
+ """HipCortex Python SDK — AI memory engine client."""
2
+
3
+ from .client import HipCortexClient
4
+ from .async_client import AsyncHipCortexClient
5
+ from .langchain_memory import HipCortexMemory, AsyncHipCortexMemory
6
+ from .llamaindex_storage import HipCortexStorageContext
7
+
8
+ __version__ = "0.5.0"
9
+ __all__ = [
10
+ "HipCortexClient",
11
+ "AsyncHipCortexClient",
12
+ "HipCortexMemory",
13
+ "AsyncHipCortexMemory",
14
+ "HipCortexStorageContext",
15
+ ]
@@ -0,0 +1,13 @@
1
+ """Framework adapters for HipCortex — shared factories, CrewAI, AutoGen."""
2
+
3
+ from .common import (
4
+ bootstrap_live_beliefs,
5
+ client_from_settings,
6
+ default_session_id,
7
+ )
8
+
9
+ __all__ = [
10
+ "bootstrap_live_beliefs",
11
+ "client_from_settings",
12
+ "default_session_id",
13
+ ]
@@ -1,156 +1,175 @@
1
- """HipCortex AutoGen adapter — targets AutoGen 0.4+ (autogen-agentchat >= 0.4).
2
-
3
- AutoGen 0.4 changed from register_hook() to the Memory protocol.
4
-
5
- Usage (AutoGen 0.4+):
6
- from autogen_agentchat.agents import AssistantAgent
7
- from hipcortex import HipCortexClient
8
- from hipcortex.adapters.autogen import HipCortexAutoGenMemory
9
-
10
- client = HipCortexClient(base_url="http://localhost:3030")
11
- memory = HipCortexAutoGenMemory(client=client, agent_id="researcher")
12
- agent = AssistantAgent(name="researcher", model_client=..., memory=[memory])
13
-
14
- Usage (AutoGen 0.3 — legacy):
15
- agent.register_hook("process_message_before_send", memory.on_message_sent_v03)
16
- agent.register_hook("process_all_messages_before_reply", memory.on_messages_received_v03)
17
- """
18
-
19
- from __future__ import annotations
20
-
21
- from typing import Any, Dict, List, Optional
22
-
23
- from ..client import HipCortexClient
24
-
25
- try:
26
- from autogen_core.memory import Memory, MemoryContent, MemoryMimeType, MemoryQueryResult
27
- from autogen_core import CancellationToken
28
- _AUTOGEN4_AVAILABLE = True
29
- except ImportError:
30
- _AUTOGEN4_AVAILABLE = False
31
- class Memory: # type: ignore[no-redef]
32
- pass
33
- class CancellationToken: # type: ignore[no-redef]
34
- pass
35
-
36
-
37
- class HipCortexAutoGenMemory(Memory): # type: ignore[misc]
38
- """AutoGen 0.4 Memory protocol backed by HipCortex."""
39
-
40
- def __init__(
41
- self,
42
- client: HipCortexClient,
43
- agent_id: str = "autogen-agent",
44
- top_k: int = 10,
45
- ) -> None:
46
- self._client = client
47
- self._agent_id = agent_id
48
- self._top_k = top_k
49
-
50
- # AutoGen 0.4 Memory protocol -------------------------------------------
51
-
52
- async def add(
53
- self,
54
- content: Any,
55
- cancellation_token: Optional[CancellationToken] = None,
56
- ) -> None:
57
- if _AUTOGEN4_AVAILABLE and hasattr(content, "content"):
58
- text = str(content.content)
59
- role = getattr(content, "role", None)
60
- mime = getattr(content, "mime_type", None)
61
- action = "ai_message" if (
62
- (role and role in ("assistant", "ai")) or
63
- (mime and "assistant" in str(mime).lower())
64
- ) else "observation"
65
- else:
66
- text = str(content)
67
- action = "observation"
68
- self._client.add_memory(
69
- actor=self._agent_id, action=action,
70
- target=text, record_type="Temporal",
71
- )
72
-
73
- async def query(
74
- self,
75
- query: Any,
76
- cancellation_token: Optional[CancellationToken] = None,
77
- ) -> Any:
78
- query_text = str(getattr(query, "content", query))
79
- try:
80
- search_results = self._client.search(query=query_text, limit=self._top_k)
81
- except Exception:
82
- search_results = [
83
- {"record": r, "score": 1.0}
84
- for r in self._client.get_conversation_history(self._agent_id, limit=self._top_k)
85
- ]
86
- if not _AUTOGEN4_AVAILABLE:
87
- return search_results
88
- memories = []
89
- for item in search_results:
90
- rec = item.get("record", item)
91
- memories.append(MemoryContent(
92
- content=rec.get("target", ""),
93
- mime_type=MemoryMimeType.TEXT,
94
- metadata={"score": item.get("score", 1.0), "actor": rec.get("actor", ""),
95
- "action": rec.get("action", ""), "timestamp": rec.get("timestamp", "")},
96
- ))
97
- return MemoryQueryResult(results=memories)
98
-
99
- async def update_context(
100
- self,
101
- model_context: Any,
102
- cancellation_token: Optional[CancellationToken] = None,
103
- ) -> Any:
104
- records = self._client.get_conversation_history(self._agent_id, limit=self._top_k)
105
- records.sort(key=lambda r: r.get("timestamp", ""))
106
- if not records:
107
- return {"memories_added": 0}
108
- lines = [f"[{r.get('action','memory')}] {r.get('target','')}" for r in records]
109
- system_msg = {"role": "system", "content": "[HipCortex memory]\n" + "\n".join(lines)}
110
- if hasattr(model_context, "add_message"):
111
- await model_context.add_message(system_msg)
112
- elif hasattr(model_context, "messages"):
113
- model_context.messages.insert(0, system_msg)
114
- return {"memories_added": len(records)}
115
-
116
- async def clear(self) -> None:
117
- self._client.forget(self._agent_id)
118
-
119
- # AutoGen 0.3 legacy hooks -----------------------------------------------
120
-
121
- def on_message_sent_v03(self, message: Dict[str, Any], **kwargs: Any) -> Dict[str, Any]:
122
- """AutoGen 0.3 hook: process_message_before_send."""
123
- content = message.get("content", "")
124
- role = message.get("role", "assistant")
125
- action = "ai_message" if role == "assistant" else "human_message"
126
- self._client.add_memory(actor=self._agent_id, action=action, target=str(content),
127
- record_type="Reflexion" if role == "assistant" else "Temporal")
128
- return message
129
-
130
- def on_messages_received_v03(
131
- self, messages: List[Dict[str, Any]], **kwargs: Any
132
- ) -> List[Dict[str, Any]]:
133
- """AutoGen 0.3 hook: process_all_messages_before_reply."""
134
- history = self._client.get_conversation_history(self._agent_id, limit=20)
135
- if not history:
136
- return messages
137
- history.sort(key=lambda r: r.get("timestamp", ""))
138
- lines = [
139
- f"{'AI' if r.get('action') == 'ai_message' else 'Human'}: {r.get('target','')}"
140
- for r in history
141
- ]
142
- return [{"role": "system", "content": "[HipCortex memory]\n" + "\n".join(lines)}] + list(messages)
143
-
144
- # Sync helpers (no AutoGen needed) ---------------------------------------
145
-
146
- def store(self, content: str, action: str = "observation") -> Dict[str, Any]:
147
- return self._client.add_memory(actor=self._agent_id, action=action,
148
- target=content, record_type="Temporal")
149
-
150
- def recall(self, limit: int = 20) -> str:
151
- records = self._client.get_conversation_history(self._agent_id, limit=limit)
152
- records.sort(key=lambda r: r.get("timestamp", ""))
153
- return "\n".join(f"[{r.get('action','?')}] {r.get('target','')}" for r in records)
154
-
155
- def forget_all(self) -> Dict[str, Any]:
156
- return self._client.forget(self._agent_id)
1
+ """HipCortex AutoGen adapter — targets AutoGen 0.4+ (autogen-agentchat >= 0.4).
2
+
3
+ AutoGen 0.4 changed from register_hook() to the Memory protocol.
4
+
5
+ Usage (AutoGen 0.4+):
6
+ from autogen_agentchat.agents import AssistantAgent
7
+ from hipcortex.adapters.autogen import HipCortexAutoGenMemory
8
+
9
+ memory = HipCortexAutoGenMemory.from_settings() # config URL + default actor
10
+ agent = AssistantAgent(name="researcher", model_client=..., memory=[memory])
11
+
12
+ Usage (AutoGen 0.3 — legacy):
13
+ agent.register_hook("process_message_before_send", memory.on_message_sent_v03)
14
+ agent.register_hook("process_all_messages_before_reply", memory.on_messages_received_v03)
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from typing import Any, Dict, List, Optional
20
+
21
+ from ..client import HipCortexClient
22
+
23
+ try:
24
+ from autogen_core.memory import Memory, MemoryContent, MemoryMimeType, MemoryQueryResult
25
+ from autogen_core import CancellationToken
26
+ _AUTOGEN4_AVAILABLE = True
27
+ except ImportError:
28
+ _AUTOGEN4_AVAILABLE = False
29
+ class Memory: # type: ignore[no-redef]
30
+ pass
31
+ class CancellationToken: # type: ignore[no-redef]
32
+ pass
33
+
34
+
35
+ class HipCortexAutoGenMemory(Memory): # type: ignore[misc]
36
+ """AutoGen 0.4 Memory protocol backed by HipCortex."""
37
+
38
+ def __init__(
39
+ self,
40
+ client: HipCortexClient,
41
+ agent_id: str = "autogen-agent",
42
+ top_k: int = 10,
43
+ ) -> None:
44
+ self._client = client
45
+ self._agent_id = agent_id
46
+ self._top_k = top_k
47
+
48
+ @classmethod
49
+ def from_settings(
50
+ cls,
51
+ agent_id: Optional[str] = None,
52
+ top_k: int = 10,
53
+ **kw: Any,
54
+ ) -> "HipCortexAutoGenMemory":
55
+ """Build memory from project/user config (URL + default actor).
56
+
57
+ Args:
58
+ agent_id: Actor scope; defaults to :func:`default_session_id`.
59
+ top_k: Max results for query/update_context.
60
+ **kw: Optional ``client`` override and unused extras ignored.
61
+ """
62
+ from .common import client_from_settings, default_session_id
63
+
64
+ client = kw.pop("client", None) or client_from_settings()
65
+ if agent_id is None:
66
+ agent_id = default_session_id()
67
+ return cls(client=client, agent_id=agent_id, top_k=top_k)
68
+
69
+ # AutoGen 0.4 Memory protocol -------------------------------------------
70
+
71
+ async def add(
72
+ self,
73
+ content: Any,
74
+ cancellation_token: Optional[CancellationToken] = None,
75
+ ) -> None:
76
+ if _AUTOGEN4_AVAILABLE and hasattr(content, "content"):
77
+ text = str(content.content)
78
+ role = getattr(content, "role", None)
79
+ mime = getattr(content, "mime_type", None)
80
+ action = "ai_message" if (
81
+ (role and role in ("assistant", "ai")) or
82
+ (mime and "assistant" in str(mime).lower())
83
+ ) else "observation"
84
+ else:
85
+ text = str(content)
86
+ action = "observation"
87
+ self._client.add_memory(
88
+ actor=self._agent_id, action=action,
89
+ target=text, record_type="Temporal",
90
+ )
91
+
92
+ async def query(
93
+ self,
94
+ query: Any,
95
+ cancellation_token: Optional[CancellationToken] = None,
96
+ ) -> Any:
97
+ query_text = str(getattr(query, "content", query))
98
+ try:
99
+ search_results = self._client.search(query=query_text, limit=self._top_k)
100
+ except Exception:
101
+ search_results = [
102
+ {"record": r, "score": 1.0}
103
+ for r in self._client.get_conversation_history(self._agent_id, limit=self._top_k)
104
+ ]
105
+ if not _AUTOGEN4_AVAILABLE:
106
+ return search_results
107
+ memories = []
108
+ for item in search_results:
109
+ rec = item.get("record", item)
110
+ memories.append(MemoryContent(
111
+ content=rec.get("target", ""),
112
+ mime_type=MemoryMimeType.TEXT,
113
+ metadata={"score": item.get("score", 1.0), "actor": rec.get("actor", ""),
114
+ "action": rec.get("action", ""), "timestamp": rec.get("timestamp", "")},
115
+ ))
116
+ return MemoryQueryResult(results=memories)
117
+
118
+ async def update_context(
119
+ self,
120
+ model_context: Any,
121
+ cancellation_token: Optional[CancellationToken] = None,
122
+ ) -> Any:
123
+ records = self._client.get_conversation_history(self._agent_id, limit=self._top_k)
124
+ records.sort(key=lambda r: r.get("timestamp", ""))
125
+ if not records:
126
+ return {"memories_added": 0}
127
+ lines = [f"[{r.get('action','memory')}] {r.get('target','')}" for r in records]
128
+ system_msg = {"role": "system", "content": "[HipCortex memory]\n" + "\n".join(lines)}
129
+ if hasattr(model_context, "add_message"):
130
+ await model_context.add_message(system_msg)
131
+ elif hasattr(model_context, "messages"):
132
+ model_context.messages.insert(0, system_msg)
133
+ return {"memories_added": len(records)}
134
+
135
+ async def clear(self) -> None:
136
+ self._client.forget(self._agent_id)
137
+
138
+ # AutoGen 0.3 legacy hooks -----------------------------------------------
139
+
140
+ def on_message_sent_v03(self, message: Dict[str, Any], **kwargs: Any) -> Dict[str, Any]:
141
+ """AutoGen 0.3 hook: process_message_before_send."""
142
+ content = message.get("content", "")
143
+ role = message.get("role", "assistant")
144
+ action = "ai_message" if role == "assistant" else "human_message"
145
+ self._client.add_memory(actor=self._agent_id, action=action, target=str(content),
146
+ record_type="Reflexion" if role == "assistant" else "Temporal")
147
+ return message
148
+
149
+ def on_messages_received_v03(
150
+ self, messages: List[Dict[str, Any]], **kwargs: Any
151
+ ) -> List[Dict[str, Any]]:
152
+ """AutoGen 0.3 hook: process_all_messages_before_reply."""
153
+ history = self._client.get_conversation_history(self._agent_id, limit=20)
154
+ if not history:
155
+ return messages
156
+ history.sort(key=lambda r: r.get("timestamp", ""))
157
+ lines = [
158
+ f"{'AI' if r.get('action') == 'ai_message' else 'Human'}: {r.get('target','')}"
159
+ for r in history
160
+ ]
161
+ return [{"role": "system", "content": "[HipCortex memory]\n" + "\n".join(lines)}] + list(messages)
162
+
163
+ # Sync helpers (no AutoGen needed) ---------------------------------------
164
+
165
+ def store(self, content: str, action: str = "observation") -> Dict[str, Any]:
166
+ return self._client.add_memory(actor=self._agent_id, action=action,
167
+ target=content, record_type="Temporal")
168
+
169
+ def recall(self, limit: int = 20) -> str:
170
+ records = self._client.get_conversation_history(self._agent_id, limit=limit)
171
+ records.sort(key=lambda r: r.get("timestamp", ""))
172
+ return "\n".join(f"[{r.get('action','?')}] {r.get('target','')}" for r in records)
173
+
174
+ def forget_all(self) -> Dict[str, Any]:
175
+ return self._client.forget(self._agent_id)