memhouse 2.0.0rc2__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.
- memhouse-2.0.0rc2/.gitignore +34 -0
- memhouse-2.0.0rc2/PKG-INFO +75 -0
- memhouse-2.0.0rc2/README.md +58 -0
- memhouse-2.0.0rc2/conformance/_serve.py +66 -0
- memhouse-2.0.0rc2/conformance/driver.py +44 -0
- memhouse-2.0.0rc2/conformance/driver_langgraph.py +86 -0
- memhouse-2.0.0rc2/conformance/driver_openai_agents.py +79 -0
- memhouse-2.0.0rc2/examples/langgraph_example.py +116 -0
- memhouse-2.0.0rc2/examples/openai_agents_example.py +91 -0
- memhouse-2.0.0rc2/pyproject.toml +38 -0
- memhouse-2.0.0rc2/src/memhouse/__init__.py +20 -0
- memhouse-2.0.0rc2/src/memhouse/_generated.py +2629 -0
- memhouse-2.0.0rc2/src/memhouse/adapters/__init__.py +14 -0
- memhouse-2.0.0rc2/src/memhouse/adapters/_tools.py +90 -0
- memhouse-2.0.0rc2/src/memhouse/adapters/langgraph.py +372 -0
- memhouse-2.0.0rc2/src/memhouse/adapters/openai_agents.py +177 -0
- memhouse-2.0.0rc2/src/memhouse/client.py +267 -0
- memhouse-2.0.0rc2/src/memhouse/hooks.py +143 -0
- memhouse-2.0.0rc2/src/memhouse/py.typed +0 -0
- memhouse-2.0.0rc2/tests/conftest.py +6 -0
- memhouse-2.0.0rc2/tests/fakes.py +22 -0
- memhouse-2.0.0rc2/tests/test_adapter_langgraph.py +400 -0
- memhouse-2.0.0rc2/tests/test_adapter_openai_agents.py +219 -0
- memhouse-2.0.0rc2/tests/test_adapters_shared.py +59 -0
- memhouse-2.0.0rc2/tests/test_client.py +279 -0
- memhouse-2.0.0rc2/tests/test_hooks.py +178 -0
- memhouse-2.0.0rc2/uv.lock +3121 -0
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/target
|
|
2
|
+
.DS_Store
|
|
3
|
+
/bench-data/
|
|
4
|
+
/bench-results/*/items.jsonl
|
|
5
|
+
.fastembed_cache/
|
|
6
|
+
/.dev-home/
|
|
7
|
+
bench-results/logs/
|
|
8
|
+
|
|
9
|
+
.env
|
|
10
|
+
/bench-results/guard/
|
|
11
|
+
|
|
12
|
+
# Publication settings (G09): founder decisions, kept local
|
|
13
|
+
scripts/publish/publish.env
|
|
14
|
+
|
|
15
|
+
# Embedded bindings (G18): build outputs
|
|
16
|
+
/bindings/python/.venv/
|
|
17
|
+
/bindings/python/python/memhouse_lite/*.so
|
|
18
|
+
/bindings/python/python/memhouse_lite/*.pyd
|
|
19
|
+
/bindings/python/.pytest_cache/
|
|
20
|
+
/bindings/**/__pycache__/
|
|
21
|
+
/bindings/node/node_modules/
|
|
22
|
+
/bindings/node/*.node
|
|
23
|
+
|
|
24
|
+
# SDKs (G18): environments and build outputs
|
|
25
|
+
/sdk/python/.venv/
|
|
26
|
+
/sdk/python/.pytest_cache/
|
|
27
|
+
/sdk/python/.mypy_cache/
|
|
28
|
+
/sdk/python/dist/
|
|
29
|
+
/sdk/**/__pycache__/
|
|
30
|
+
/sdk/typescript/node_modules/
|
|
31
|
+
/sdk/typescript/dist/
|
|
32
|
+
|
|
33
|
+
# Release artefacts (G21): scripts/release-dry-run.sh and the release tools it downloads
|
|
34
|
+
/dist/
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: memhouse
|
|
3
|
+
Version: 2.0.0rc2
|
|
4
|
+
Summary: Python SDK for MemHouse, a governed memory service for AI agents: a client generated from the OpenAPI specification, and lifecycle hooks that only call the API
|
|
5
|
+
Project-URL: Repository, https://github.com/memhousehq/memhouse
|
|
6
|
+
Project-URL: Documentation, https://github.com/memhousehq/memhouse/blob/main/docs/sdk.md
|
|
7
|
+
License-Expression: Apache-2.0
|
|
8
|
+
Keywords: agents,governance,llm,memory
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Typing :: Typed
|
|
11
|
+
Requires-Python: >=3.9
|
|
12
|
+
Provides-Extra: langgraph
|
|
13
|
+
Requires-Dist: langgraph>=1.2.24; (python_version >= '3.10') and extra == 'langgraph'
|
|
14
|
+
Provides-Extra: openai-agents
|
|
15
|
+
Requires-Dist: openai-agents>=0.26.0; (python_version >= '3.10') and extra == 'openai-agents'
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
|
|
18
|
+
<!-- SPDX-License-Identifier: Apache-2.0 -->
|
|
19
|
+
# MemHouse SDK for Python
|
|
20
|
+
|
|
21
|
+
The Python client for [MemHouse](https://github.com/memhousehq/memhouse), a governed memory
|
|
22
|
+
service for AI agents. Python 3.9 or newer, no runtime dependencies (HTTP goes through the
|
|
23
|
+
standard library).
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
from memhouse import MemHouse, MemoryHooks
|
|
27
|
+
|
|
28
|
+
mh = MemHouse() # MEMHOUSE_URL (default http://127.0.0.1:7077) and MEMHOUSE_API_KEY
|
|
29
|
+
|
|
30
|
+
mh.remember({"subject": "customer:acme", "content": "Acme renews on 2027-03-01", "wait": True})
|
|
31
|
+
answer = mh.recall({"subject": "customer:acme", "query": "when does Acme renew?", "render": True})
|
|
32
|
+
print(answer["rendered"])
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
- **Client.** `MemHouse` has one method per operation of the API (`remember`, `recall`, `revise`,
|
|
36
|
+
`forget`, `ingest`, `get_memory`, `list_memories`, ...), with typed requests and responses.
|
|
37
|
+
They are generated from the OpenAPI specification (`src/memhouse/_generated.py`, written by
|
|
38
|
+
`cargo xtask sdk`; do not edit it). An error answer raises `MemHouseError` with the API's
|
|
39
|
+
stable `code`, its message `error` and the HTTP `status`.
|
|
40
|
+
- **Hooks.** `MemoryHooks(client, subject, session_id=None)` gives an agent loop four calls:
|
|
41
|
+
`before_model_call(query)` (recall, returns a prompt-ready block), `after_turn(user_message,
|
|
42
|
+
assistant_message)` (ingest), `on_tool_result(tool_name, result)` (remember) and
|
|
43
|
+
`at_session_end()` (sends buffered turns). They only call the API: nothing is enforced in them.
|
|
44
|
+
- **Embedded.** `MemHouse.embedded(path)` runs the Lite engine in this process instead of calling
|
|
45
|
+
a server; it needs the package `memhouse-lite` (`bindings/python` of the repository).
|
|
46
|
+
- **Framework adapters.** Optional extras, for Python 3.10 or newer: `memhouse[openai-agents]`
|
|
47
|
+
(`memhouse.adapters.openai_agents`, tested with `openai-agents` 0.26.0) and
|
|
48
|
+
`memhouse[langgraph]` (`memhouse.adapters.langgraph`, tested with `langgraph` 1.2.24). Each
|
|
49
|
+
gives the memory tools (`remember`, `recall`, `revise`, `forget`) and the lifecycle hooks in
|
|
50
|
+
its framework's own form: run hooks and a model-input filter for the OpenAI Agents SDK; graph
|
|
51
|
+
nodes and a `BaseStore` for LangGraph. They only call the client and the hooks: nothing is
|
|
52
|
+
enforced in them. Examples are in [`examples/`](examples).
|
|
53
|
+
|
|
54
|
+
The full guide is [docs/sdk.md](../../docs/sdk.md).
|
|
55
|
+
|
|
56
|
+
## Development
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
uv sync # a virtual environment with pytest
|
|
60
|
+
uv run pytest # offline tests; with MEMHOUSE_URL and MEMHOUSE_API_KEY set, the live ones too
|
|
61
|
+
|
|
62
|
+
# with the framework adapters (their tests are skipped when the framework is missing)
|
|
63
|
+
uv run --python 3.12 --extra openai-agents --extra langgraph pytest
|
|
64
|
+
uv run --python 3.12 --extra openai-agents --extra langgraph --with mypy mypy src tests conformance examples
|
|
65
|
+
|
|
66
|
+
# the examples, against a MemHouse server, with a stand-in model (no model provider, no key)
|
|
67
|
+
uv run --python 3.12 --extra openai-agents python examples/openai_agents_example.py
|
|
68
|
+
uv run --python 3.12 --extra langgraph python examples/langgraph_example.py
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
`conformance/driver.py` serves the profile conformance suite
|
|
72
|
+
([docs/conformance.md](../../docs/conformance.md#the-sdks)), and `driver_openai_agents.py` and
|
|
73
|
+
`driver_langgraph.py` serve it through the two adapters: `scripts/sdk-conformance.sh` from the
|
|
74
|
+
repository root runs the suite through this SDK and both adapters against a throwaway
|
|
75
|
+
deployment.
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
<!-- SPDX-License-Identifier: Apache-2.0 -->
|
|
2
|
+
# MemHouse SDK for Python
|
|
3
|
+
|
|
4
|
+
The Python client for [MemHouse](https://github.com/memhousehq/memhouse), a governed memory
|
|
5
|
+
service for AI agents. Python 3.9 or newer, no runtime dependencies (HTTP goes through the
|
|
6
|
+
standard library).
|
|
7
|
+
|
|
8
|
+
```python
|
|
9
|
+
from memhouse import MemHouse, MemoryHooks
|
|
10
|
+
|
|
11
|
+
mh = MemHouse() # MEMHOUSE_URL (default http://127.0.0.1:7077) and MEMHOUSE_API_KEY
|
|
12
|
+
|
|
13
|
+
mh.remember({"subject": "customer:acme", "content": "Acme renews on 2027-03-01", "wait": True})
|
|
14
|
+
answer = mh.recall({"subject": "customer:acme", "query": "when does Acme renew?", "render": True})
|
|
15
|
+
print(answer["rendered"])
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
- **Client.** `MemHouse` has one method per operation of the API (`remember`, `recall`, `revise`,
|
|
19
|
+
`forget`, `ingest`, `get_memory`, `list_memories`, ...), with typed requests and responses.
|
|
20
|
+
They are generated from the OpenAPI specification (`src/memhouse/_generated.py`, written by
|
|
21
|
+
`cargo xtask sdk`; do not edit it). An error answer raises `MemHouseError` with the API's
|
|
22
|
+
stable `code`, its message `error` and the HTTP `status`.
|
|
23
|
+
- **Hooks.** `MemoryHooks(client, subject, session_id=None)` gives an agent loop four calls:
|
|
24
|
+
`before_model_call(query)` (recall, returns a prompt-ready block), `after_turn(user_message,
|
|
25
|
+
assistant_message)` (ingest), `on_tool_result(tool_name, result)` (remember) and
|
|
26
|
+
`at_session_end()` (sends buffered turns). They only call the API: nothing is enforced in them.
|
|
27
|
+
- **Embedded.** `MemHouse.embedded(path)` runs the Lite engine in this process instead of calling
|
|
28
|
+
a server; it needs the package `memhouse-lite` (`bindings/python` of the repository).
|
|
29
|
+
- **Framework adapters.** Optional extras, for Python 3.10 or newer: `memhouse[openai-agents]`
|
|
30
|
+
(`memhouse.adapters.openai_agents`, tested with `openai-agents` 0.26.0) and
|
|
31
|
+
`memhouse[langgraph]` (`memhouse.adapters.langgraph`, tested with `langgraph` 1.2.24). Each
|
|
32
|
+
gives the memory tools (`remember`, `recall`, `revise`, `forget`) and the lifecycle hooks in
|
|
33
|
+
its framework's own form: run hooks and a model-input filter for the OpenAI Agents SDK; graph
|
|
34
|
+
nodes and a `BaseStore` for LangGraph. They only call the client and the hooks: nothing is
|
|
35
|
+
enforced in them. Examples are in [`examples/`](examples).
|
|
36
|
+
|
|
37
|
+
The full guide is [docs/sdk.md](../../docs/sdk.md).
|
|
38
|
+
|
|
39
|
+
## Development
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
uv sync # a virtual environment with pytest
|
|
43
|
+
uv run pytest # offline tests; with MEMHOUSE_URL and MEMHOUSE_API_KEY set, the live ones too
|
|
44
|
+
|
|
45
|
+
# with the framework adapters (their tests are skipped when the framework is missing)
|
|
46
|
+
uv run --python 3.12 --extra openai-agents --extra langgraph pytest
|
|
47
|
+
uv run --python 3.12 --extra openai-agents --extra langgraph --with mypy mypy src tests conformance examples
|
|
48
|
+
|
|
49
|
+
# the examples, against a MemHouse server, with a stand-in model (no model provider, no key)
|
|
50
|
+
uv run --python 3.12 --extra openai-agents python examples/openai_agents_example.py
|
|
51
|
+
uv run --python 3.12 --extra langgraph python examples/langgraph_example.py
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
`conformance/driver.py` serves the profile conformance suite
|
|
55
|
+
([docs/conformance.md](../../docs/conformance.md#the-sdks)), and `driver_openai_agents.py` and
|
|
56
|
+
`driver_langgraph.py` serve it through the two adapters: `scripts/sdk-conformance.sh` from the
|
|
57
|
+
repository root runs the suite through this SDK and both adapters against a throwaway
|
|
58
|
+
deployment.
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""What the adapter drivers share: the JSON-lines protocol of the profile suite's `Process` way
|
|
3
|
+
(docs/conformance.md), and reading a scenario request into what an adapter is given.
|
|
4
|
+
|
|
5
|
+
A driver passes `serve` one function that carries out an operation through its adapter. A field
|
|
6
|
+
of a request that the adapter has no place for is an error, never dropped silently.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import sys
|
|
11
|
+
from typing import Any, Callable, Dict, List, Tuple
|
|
12
|
+
|
|
13
|
+
OPERATIONS = ("remember", "recall", "revise", "forget", "ingest")
|
|
14
|
+
|
|
15
|
+
# What a memory object is built with (the subject and the session it is bound to, and whether it
|
|
16
|
+
# asks for the write gate's decision), as against what a tool call or a turn carries.
|
|
17
|
+
BOUND = ("subject", "wait", "session_id")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def serve(call: Callable[[str, Dict[str, Any]], Any]) -> int:
|
|
21
|
+
"""Answer one line per request line until standard input ends."""
|
|
22
|
+
for line in sys.stdin:
|
|
23
|
+
if not line.strip():
|
|
24
|
+
continue
|
|
25
|
+
try:
|
|
26
|
+
request = json.loads(line)
|
|
27
|
+
op = request.get("op")
|
|
28
|
+
if op not in OPERATIONS:
|
|
29
|
+
raise ValueError(f"the driver has no operation {op!r}")
|
|
30
|
+
result = call(op, request.get("body") or {})
|
|
31
|
+
if not isinstance(result, dict):
|
|
32
|
+
raise ValueError(f"the adapter did not return the API's answer: {result!r}")
|
|
33
|
+
answer = {"ok": True, "result": result}
|
|
34
|
+
except Exception as e: # one failed call is one failed step, not the end of the run
|
|
35
|
+
answer = {"ok": False, "error": f"{type(e).__name__}: {e}"}
|
|
36
|
+
sys.stdout.write(json.dumps(answer) + "\n")
|
|
37
|
+
sys.stdout.flush()
|
|
38
|
+
return 0
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def is_cleanup(op: str, body: Dict[str, Any]) -> bool:
|
|
42
|
+
"""The suite's cleanup after a run: `forget` of a whole subject. It is not a step of the
|
|
43
|
+
scenario, and the adapters give an agent no tool that erases a subject, so the drivers
|
|
44
|
+
carry it out with the bare client."""
|
|
45
|
+
return op == "forget" and "id" not in body
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def tool_arguments(body: Dict[str, Any], accepted: List[str]) -> Dict[str, Any]:
|
|
49
|
+
"""The arguments of a tool call: the request without what the tools are bound to."""
|
|
50
|
+
arguments = {k: v for k, v in body.items() if k not in BOUND}
|
|
51
|
+
unknown = sorted(set(arguments) - set(accepted))
|
|
52
|
+
if unknown:
|
|
53
|
+
raise ValueError(f"the adapter's tool has no argument {', '.join(unknown)}")
|
|
54
|
+
return arguments
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def one_round(body: Dict[str, Any]) -> Tuple[str, str]:
|
|
58
|
+
"""The user message and the reply of an `ingest` request, which the adapters' after-turn
|
|
59
|
+
path can carry only when it is exactly one round."""
|
|
60
|
+
unknown = sorted(set(body) - set(BOUND) - {"messages"})
|
|
61
|
+
if unknown:
|
|
62
|
+
raise ValueError(f"the adapter's after-turn path has no place for {', '.join(unknown)}")
|
|
63
|
+
messages = body.get("messages") or []
|
|
64
|
+
if [m.get("role") for m in messages] != ["user", "assistant"]:
|
|
65
|
+
raise ValueError("the adapter's after-turn path carries one round: a user message and the assistant's reply")
|
|
66
|
+
return messages[0]["content"], messages[1]["content"]
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""The Python SDK as a way into a deployment, for the profile conformance suite.
|
|
4
|
+
|
|
5
|
+
Reads one JSON object per line on standard input, `{"op": "remember", "body": {...}}` (the
|
|
6
|
+
operation is `remember`, `recall`, `revise`, `forget` or `ingest`), carries it out with the
|
|
7
|
+
SDK's client and writes one line: `{"ok": true, "result": {...}}` or `{"ok": false, "error":
|
|
8
|
+
"..."}`. The deployment is the one at MEMHOUSE_URL with MEMHOUSE_API_KEY, or with
|
|
9
|
+
MEMHOUSE_EMBEDDED=<database file> the embedded Lite engine. See docs/conformance.md.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import sys
|
|
15
|
+
|
|
16
|
+
from memhouse import MemHouse
|
|
17
|
+
|
|
18
|
+
OPERATIONS = ("remember", "recall", "revise", "forget", "ingest")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def main() -> int:
|
|
22
|
+
embedded = os.environ.get("MEMHOUSE_EMBEDDED")
|
|
23
|
+
client = MemHouse.embedded(embedded) if embedded else MemHouse()
|
|
24
|
+
try:
|
|
25
|
+
for line in sys.stdin:
|
|
26
|
+
if not line.strip():
|
|
27
|
+
continue
|
|
28
|
+
try:
|
|
29
|
+
request = json.loads(line)
|
|
30
|
+
op = request.get("op")
|
|
31
|
+
if op not in OPERATIONS:
|
|
32
|
+
raise ValueError(f"the driver has no operation {op!r}")
|
|
33
|
+
answer = {"ok": True, "result": getattr(client, op)(request.get("body") or {})}
|
|
34
|
+
except Exception as e: # one failed call is one failed step, not the end of the run
|
|
35
|
+
answer = {"ok": False, "error": f"{type(e).__name__}: {e}"}
|
|
36
|
+
sys.stdout.write(json.dumps(answer) + "\n")
|
|
37
|
+
sys.stdout.flush()
|
|
38
|
+
finally:
|
|
39
|
+
client.close()
|
|
40
|
+
return 0
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
if __name__ == "__main__":
|
|
44
|
+
sys.exit(main())
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""The LangGraph adapter as a way into a deployment, for the profile conformance suite.
|
|
4
|
+
|
|
5
|
+
Speaks the protocol of `driver.py`. Each operation is carried out through the adapter
|
|
6
|
+
(`memhouse.adapters.langgraph`) by a compiled graph, with no model in the loop:
|
|
7
|
+
|
|
8
|
+
- `remember`, `recall`, `revise`, `forget`: a graph of one `ToolNode` with the adapter's tools,
|
|
9
|
+
given an assistant message that carries the tool call, as a model would have produced it.
|
|
10
|
+
The content of the resulting `ToolMessage`, JSON text, is the API's answer.
|
|
11
|
+
- `ingest`: a graph of the adapter's propose node, given the user message and the reply, with
|
|
12
|
+
the session as the run's thread: the adapter's after-turn path. The API's answer is what the
|
|
13
|
+
node writes to the state.
|
|
14
|
+
|
|
15
|
+
The deployment is the one at MEMHOUSE_URL with MEMHOUSE_API_KEY. Needs `memhouse[langgraph]`.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
import json
|
|
19
|
+
import sys
|
|
20
|
+
from typing import Any, Dict, Optional
|
|
21
|
+
|
|
22
|
+
from langchain_core.messages import AIMessage, HumanMessage
|
|
23
|
+
from langchain_core.runnables import RunnableConfig
|
|
24
|
+
from langgraph.graph import END, START, MessagesState, StateGraph
|
|
25
|
+
from langgraph.prebuilt import ToolNode
|
|
26
|
+
|
|
27
|
+
from _serve import is_cleanup, one_round, serve, tool_arguments
|
|
28
|
+
from memhouse import MemHouse
|
|
29
|
+
from memhouse.adapters.langgraph import MemHouseMemory
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class State(MessagesState, total=False):
|
|
33
|
+
proposed: Dict[str, Any]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Driver:
|
|
37
|
+
def __init__(self, client: MemHouse) -> None:
|
|
38
|
+
self.client = client
|
|
39
|
+
# `revise` and `forget` name a record, not a subject: they go to the tools of the
|
|
40
|
+
# subject the scenario is running on.
|
|
41
|
+
self.subject: Optional[str] = None
|
|
42
|
+
self.calls = 0
|
|
43
|
+
|
|
44
|
+
def call(self, op: str, body: Dict[str, Any]) -> Any:
|
|
45
|
+
if is_cleanup(op, body):
|
|
46
|
+
return self.client.forget(body) # type: ignore[arg-type]
|
|
47
|
+
self.subject = body.get("subject") or self.subject
|
|
48
|
+
if not self.subject:
|
|
49
|
+
raise ValueError(f"{op} before any request named a subject")
|
|
50
|
+
memory = MemHouseMemory(self.client, self.subject, wait=bool(body.get("wait")), result_key="proposed")
|
|
51
|
+
return self.ingest(memory, body) if op == "ingest" else self.tool_call(memory, op, body)
|
|
52
|
+
|
|
53
|
+
def tool_call(self, memory: MemHouseMemory, op: str, body: Dict[str, Any]) -> Any:
|
|
54
|
+
tool = next(t for t in memory.tools if t.name == op)
|
|
55
|
+
arguments = tool_arguments(body, list(tool.args))
|
|
56
|
+
graph = StateGraph(State)
|
|
57
|
+
# An error of the API fails the step instead of becoming a message for the model.
|
|
58
|
+
graph.add_node("tools", ToolNode(memory.tools, handle_tool_errors=False))
|
|
59
|
+
graph.add_edge(START, "tools")
|
|
60
|
+
graph.add_edge("tools", END)
|
|
61
|
+
self.calls += 1
|
|
62
|
+
call = {"name": op, "args": arguments, "id": f"call-{self.calls}", "type": "tool_call"}
|
|
63
|
+
state = graph.compile().invoke({"messages": [AIMessage(content="", tool_calls=[call])]})
|
|
64
|
+
return json.loads(state["messages"][-1].content)
|
|
65
|
+
|
|
66
|
+
def ingest(self, memory: MemHouseMemory, body: Dict[str, Any]) -> Any:
|
|
67
|
+
user, reply = one_round(body)
|
|
68
|
+
graph = StateGraph(State)
|
|
69
|
+
graph.add_node("propose", memory.propose)
|
|
70
|
+
graph.add_edge(START, "propose")
|
|
71
|
+
graph.add_edge("propose", END)
|
|
72
|
+
config: RunnableConfig = {"configurable": {"thread_id": body["session_id"]}} if body.get("session_id") else {}
|
|
73
|
+
state = graph.compile().invoke({"messages": [HumanMessage(user), AIMessage(reply)]}, config=config)
|
|
74
|
+
return state.get("proposed")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def main() -> int:
|
|
78
|
+
client = MemHouse()
|
|
79
|
+
try:
|
|
80
|
+
return serve(Driver(client).call)
|
|
81
|
+
finally:
|
|
82
|
+
client.close()
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
if __name__ == "__main__":
|
|
86
|
+
sys.exit(main())
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""The OpenAI Agents SDK adapter as a way into a deployment, for the profile conformance suite.
|
|
4
|
+
|
|
5
|
+
Speaks the protocol of `driver.py`. Each operation is carried out through the adapter
|
|
6
|
+
(`memhouse.adapters.openai_agents`) the way the framework invokes it, with no model in the
|
|
7
|
+
loop:
|
|
8
|
+
|
|
9
|
+
- `remember`, `recall`, `revise`, `forget`: the function tool's `on_invoke_tool` with a tool
|
|
10
|
+
context and the arguments as JSON text, as the runner calls it for a model's tool call. The
|
|
11
|
+
tool's output, JSON text, is the API's answer.
|
|
12
|
+
- `ingest`: the run hook `on_agent_end` with the user message as the run's input and the reply
|
|
13
|
+
as the agent's final output: the adapter's after-turn path. The API's answer is the
|
|
14
|
+
adapter's `last_turn`.
|
|
15
|
+
|
|
16
|
+
The deployment is the one at MEMHOUSE_URL with MEMHOUSE_API_KEY. Needs `memhouse[openai-agents]`.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
import asyncio
|
|
20
|
+
import json
|
|
21
|
+
import sys
|
|
22
|
+
from typing import Any, Dict, Optional
|
|
23
|
+
|
|
24
|
+
from agents import Agent, AgentHookContext
|
|
25
|
+
from agents.tool_context import ToolContext
|
|
26
|
+
|
|
27
|
+
from _serve import is_cleanup, one_round, serve, tool_arguments
|
|
28
|
+
from memhouse import MemHouse
|
|
29
|
+
from memhouse.adapters.openai_agents import MemHouseMemory
|
|
30
|
+
|
|
31
|
+
AGENT: Agent[Any] = Agent(name="profile-suite")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class Driver:
|
|
35
|
+
def __init__(self, client: MemHouse) -> None:
|
|
36
|
+
self.client = client
|
|
37
|
+
# `revise` and `forget` name a record, not a subject: they go to the tools of the
|
|
38
|
+
# subject the scenario is running on.
|
|
39
|
+
self.subject: Optional[str] = None
|
|
40
|
+
self.calls = 0
|
|
41
|
+
|
|
42
|
+
def call(self, op: str, body: Dict[str, Any]) -> Any:
|
|
43
|
+
if is_cleanup(op, body):
|
|
44
|
+
return self.client.forget(body) # type: ignore[arg-type]
|
|
45
|
+
self.subject = body.get("subject") or self.subject
|
|
46
|
+
if not self.subject:
|
|
47
|
+
raise ValueError(f"{op} before any request named a subject")
|
|
48
|
+
memory = MemHouseMemory(self.client, self.subject, body.get("session_id"), wait=bool(body.get("wait")))
|
|
49
|
+
return asyncio.run(self.ingest(memory, body) if op == "ingest" else self.tool_call(memory, op, body))
|
|
50
|
+
|
|
51
|
+
async def tool_call(self, memory: MemHouseMemory, op: str, body: Dict[str, Any]) -> Any:
|
|
52
|
+
tool = next(t for t in memory.tools if t.name == op)
|
|
53
|
+
arguments = json.dumps(tool_arguments(body, list(tool.params_json_schema["properties"])))
|
|
54
|
+
self.calls += 1
|
|
55
|
+
context: ToolContext[Any] = ToolContext(context=None, tool_name=tool.name, tool_call_id=f"call-{self.calls}", tool_arguments=arguments)
|
|
56
|
+
output = await tool.on_invoke_tool(context, arguments)
|
|
57
|
+
try:
|
|
58
|
+
return json.loads(output)
|
|
59
|
+
except ValueError:
|
|
60
|
+
# The framework's tool-error message, which is what the model would get.
|
|
61
|
+
raise RuntimeError(str(output)) from None
|
|
62
|
+
|
|
63
|
+
async def ingest(self, memory: MemHouseMemory, body: Dict[str, Any]) -> Any:
|
|
64
|
+
user, reply = one_round(body)
|
|
65
|
+
context: AgentHookContext[Any] = AgentHookContext(context=None, turn_input=[{"role": "user", "content": user}])
|
|
66
|
+
await memory.run_hooks.on_agent_end(context, AGENT, reply)
|
|
67
|
+
return memory.last_turn
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def main() -> int:
|
|
71
|
+
client = MemHouse()
|
|
72
|
+
try:
|
|
73
|
+
return serve(Driver(client).call)
|
|
74
|
+
finally:
|
|
75
|
+
client.close()
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
if __name__ == "__main__":
|
|
79
|
+
sys.exit(main())
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""An agent with MemHouse memory as a LangGraph graph: two conversations about one customer.
|
|
4
|
+
|
|
5
|
+
recall -> model -> (tools -> model)* -> propose
|
|
6
|
+
|
|
7
|
+
The recall node puts what MemHouse knows for the user's message into the state before the model
|
|
8
|
+
node runs; the propose node hands the finished turn to MemHouse after it. In the first
|
|
9
|
+
conversation the agent stores what it is told with the `remember` tool; the second is a new
|
|
10
|
+
thread, answered from memory.
|
|
11
|
+
|
|
12
|
+
cd sdk/python
|
|
13
|
+
uv run --python 3.12 --extra langgraph python examples/langgraph_example.py
|
|
14
|
+
|
|
15
|
+
It needs a MemHouse server: MEMHOUSE_URL (default http://127.0.0.1:7077) and MEMHOUSE_API_KEY.
|
|
16
|
+
The model is a stand-in function, so no model provider is called. To use a real model, name it
|
|
17
|
+
in EXAMPLE_MODEL and add the package `langchain-openai`, which reads its key from
|
|
18
|
+
OPENAI_API_KEY:
|
|
19
|
+
|
|
20
|
+
EXAMPLE_MODEL=<model name> uv run --python 3.12 --extra langgraph --with langchain-openai python examples/langgraph_example.py
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
import os
|
|
24
|
+
import uuid
|
|
25
|
+
from typing import Any, List, Optional, Sequence
|
|
26
|
+
|
|
27
|
+
from langchain_core.messages import AIMessage, AnyMessage, HumanMessage, SystemMessage, ToolMessage
|
|
28
|
+
from langchain_core.tools import BaseTool
|
|
29
|
+
from langgraph.graph import END, START, MessagesState, StateGraph
|
|
30
|
+
from langgraph.prebuilt import ToolNode, tools_condition
|
|
31
|
+
|
|
32
|
+
from memhouse import MemHouse
|
|
33
|
+
from memhouse.adapters.langgraph import SUBJECT_KEY, MemHouseMemory
|
|
34
|
+
|
|
35
|
+
INSTRUCTIONS = "You are a support agent. Store what the customer tells you that is worth keeping with the remember tool. Answer questions from what you know about the customer."
|
|
36
|
+
CONVERSATIONS = ["Our contract renews on 2027-03-01.", "When does our contract renew?"]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class State(MessagesState):
|
|
40
|
+
memory: str # what the recall node found, for the model's prompt
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
# ---- The model: the only part that differs between the stand-in and a real one. ----
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def call_model(system: str, messages: Sequence[AnyMessage], tools: List[BaseTool]) -> AIMessage:
|
|
47
|
+
"""One model call: the model EXAMPLE_MODEL names, or the stand-in."""
|
|
48
|
+
name = os.environ.get("EXAMPLE_MODEL")
|
|
49
|
+
if not name:
|
|
50
|
+
return stand_in_model(system, messages)
|
|
51
|
+
from langchain_openai import ChatOpenAI # type: ignore[import-not-found]
|
|
52
|
+
|
|
53
|
+
reply: AIMessage = ChatOpenAI(model=name).bind_tools(tools).invoke([SystemMessage(system), *messages])
|
|
54
|
+
return reply
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def stand_in_model(system: str, messages: Sequence[AnyMessage]) -> AIMessage:
|
|
58
|
+
"""Not a model: no provider, no key. It does what a model would be expected to."""
|
|
59
|
+
last = messages[-1]
|
|
60
|
+
if isinstance(last, ToolMessage):
|
|
61
|
+
return AIMessage("Thanks, I have noted that.")
|
|
62
|
+
said = str(last.content)
|
|
63
|
+
if not said.endswith("?"):
|
|
64
|
+
return AIMessage("", tool_calls=[{"name": "remember", "args": {"content": said}, "id": "call-1", "type": "tool_call"}])
|
|
65
|
+
known = system.replace(INSTRUCTIONS, "").strip()
|
|
66
|
+
return AIMessage(f"From memory: {known}" if known else "I don't know that yet.")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
# ---- The graph: the same for either model. ----
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def build(client: MemHouse) -> Any:
|
|
73
|
+
# No fixed subject: each run names its own in its config, so one graph serves every customer.
|
|
74
|
+
# `wait` so that the next conversation sees what this one stored.
|
|
75
|
+
memory = MemHouseMemory(client, wait=True)
|
|
76
|
+
|
|
77
|
+
def model(state: State) -> Any:
|
|
78
|
+
system = f"{INSTRUCTIONS}\n\n{state['memory']}" if state.get("memory") else INSTRUCTIONS
|
|
79
|
+
return {"messages": [call_model(system, state["messages"], memory.tools)]}
|
|
80
|
+
|
|
81
|
+
graph = StateGraph(State)
|
|
82
|
+
graph.add_node("recall", memory.recall)
|
|
83
|
+
graph.add_node("model", model)
|
|
84
|
+
graph.add_node("tools", ToolNode(memory.tools))
|
|
85
|
+
graph.add_node("propose", memory.propose)
|
|
86
|
+
graph.add_edge(START, "recall")
|
|
87
|
+
graph.add_edge("recall", "model")
|
|
88
|
+
graph.add_conditional_edges("model", tools_condition, {"tools": "tools", END: "propose"})
|
|
89
|
+
graph.add_edge("tools", "model")
|
|
90
|
+
graph.add_edge("propose", END)
|
|
91
|
+
return graph.compile()
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def run(client: MemHouse, subject: str) -> List[str]:
|
|
95
|
+
app = build(client)
|
|
96
|
+
answers = []
|
|
97
|
+
for conversation, message in enumerate(CONVERSATIONS):
|
|
98
|
+
config = {"configurable": {SUBJECT_KEY: subject, "thread_id": f"conversation-{conversation}"}}
|
|
99
|
+
state = app.invoke({"messages": [HumanMessage(message)]}, config=config)
|
|
100
|
+
answer = str(state["messages"][-1].content)
|
|
101
|
+
print(f"user: {message}\nagent: {answer}\n")
|
|
102
|
+
answers.append(answer)
|
|
103
|
+
return answers
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def main(client: Optional[MemHouse] = None) -> List[str]:
|
|
107
|
+
client = client or MemHouse()
|
|
108
|
+
subject = f"example:langgraph:{uuid.uuid4().hex[:12]}"
|
|
109
|
+
try:
|
|
110
|
+
return run(client, subject)
|
|
111
|
+
finally:
|
|
112
|
+
client.forget({"subject": subject}) # the example leaves nothing behind
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
if __name__ == "__main__":
|
|
116
|
+
main()
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""An agent with MemHouse memory on the OpenAI Agents SDK: two conversations about one customer.
|
|
4
|
+
|
|
5
|
+
In the first the agent is told something and stores it with the `remember` tool. The second is
|
|
6
|
+
a new conversation: what MemHouse recalls for the question is added to the agent's instructions
|
|
7
|
+
before the model is called, so the agent can answer from memory.
|
|
8
|
+
|
|
9
|
+
cd sdk/python
|
|
10
|
+
uv run --python 3.12 --extra openai-agents python examples/openai_agents_example.py
|
|
11
|
+
|
|
12
|
+
It needs a MemHouse server: MEMHOUSE_URL (default http://127.0.0.1:7077) and MEMHOUSE_API_KEY.
|
|
13
|
+
The model is a stand-in that follows a script, so no model provider is called. To use a real
|
|
14
|
+
model, name it in EXAMPLE_MODEL; the Agents SDK reads its key from OPENAI_API_KEY:
|
|
15
|
+
|
|
16
|
+
EXAMPLE_MODEL=<model name> uv run --python 3.12 --extra openai-agents python examples/openai_agents_example.py
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
import asyncio
|
|
20
|
+
import os
|
|
21
|
+
import uuid
|
|
22
|
+
from typing import Any, List, Optional
|
|
23
|
+
|
|
24
|
+
from agents import Agent, Runner
|
|
25
|
+
from agents.testing import ModelCall, ModelStep, ScriptedModel, assistant_message, function_call
|
|
26
|
+
|
|
27
|
+
from memhouse import MemHouse
|
|
28
|
+
from memhouse.adapters.openai_agents import MemHouseMemory
|
|
29
|
+
|
|
30
|
+
INSTRUCTIONS = "You are a support agent. Store what the customer tells you that is worth keeping with the remember tool. Answer questions from what you know about the customer."
|
|
31
|
+
CONVERSATIONS = ["Our contract renews on 2027-03-01.", "When does our contract renew?"]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
# ---- The model: the only part that differs between the stand-in and a real one. ----
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def model(conversation: int) -> Any:
|
|
38
|
+
"""The model of the agent: the one EXAMPLE_MODEL names, or the stand-in."""
|
|
39
|
+
return os.environ.get("EXAMPLE_MODEL") or stand_in_model(conversation)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def stand_in_model(conversation: int) -> ScriptedModel:
|
|
43
|
+
"""A scripted model: no provider, no key. It does what a model would be expected to."""
|
|
44
|
+
|
|
45
|
+
def store_what_was_said(call: ModelCall) -> Any:
|
|
46
|
+
return [function_call("remember", {"content": call.input[-1]["content"], "kind": None}, call_id="call-1")]
|
|
47
|
+
|
|
48
|
+
def answer_from_instructions(call: ModelCall) -> Any:
|
|
49
|
+
# The memories are the part of the instructions that the adapter added.
|
|
50
|
+
known = (call.system_instructions or "").replace(INSTRUCTIONS, "").strip()
|
|
51
|
+
return [assistant_message(f"From memory: {known}" if known else "I don't know that yet.")]
|
|
52
|
+
|
|
53
|
+
if conversation == 0:
|
|
54
|
+
return ScriptedModel([ModelStep.respond(store_what_was_said), [assistant_message("Thanks, I have noted that.")]])
|
|
55
|
+
return ScriptedModel([ModelStep.respond(answer_from_instructions)])
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
# ---- The agent: the same code for either model. ----
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
async def converse(client: MemHouse, subject: str, conversation: int, message: str) -> str:
|
|
62
|
+
# One MemHouseMemory per conversation: `wait` so that the next one sees what this one stored.
|
|
63
|
+
memory = MemHouseMemory(client, subject, session_id=f"conversation-{conversation}", wait=True)
|
|
64
|
+
agent = Agent(name="Support", instructions=INSTRUCTIONS, tools=list(memory.tools), model=model(conversation))
|
|
65
|
+
# Tracing would upload the run to the model provider: off when there is none.
|
|
66
|
+
config = memory.run_config(tracing_disabled="EXAMPLE_MODEL" not in os.environ)
|
|
67
|
+
result = await Runner.run(agent, message, hooks=memory.run_hooks, run_config=config)
|
|
68
|
+
await memory.end_session()
|
|
69
|
+
return str(result.final_output)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
async def run(client: MemHouse, subject: str) -> List[str]:
|
|
73
|
+
answers = []
|
|
74
|
+
for conversation, message in enumerate(CONVERSATIONS):
|
|
75
|
+
answer = await converse(client, subject, conversation, message)
|
|
76
|
+
print(f"user: {message}\nagent: {answer}\n")
|
|
77
|
+
answers.append(answer)
|
|
78
|
+
return answers
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def main(client: Optional[MemHouse] = None) -> List[str]:
|
|
82
|
+
client = client or MemHouse()
|
|
83
|
+
subject = f"example:openai-agents:{uuid.uuid4().hex[:12]}"
|
|
84
|
+
try:
|
|
85
|
+
return asyncio.run(run(client, subject))
|
|
86
|
+
finally:
|
|
87
|
+
client.forget({"subject": subject}) # the example leaves nothing behind
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
if __name__ == "__main__":
|
|
91
|
+
main()
|