Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions .github/workflows/python-agent-framework.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
name: Microsoft Agent Framework Integration

on:
pull_request:
paths:
- 'examples/agent-framework/**'
- '.github/workflows/python-agent-framework.yml'
push:
branches: [main]
paths:
- 'examples/agent-framework/**'
- '.github/workflows/python-agent-framework.yml'

permissions:
contents: read

jobs:
contracts:
runs-on: ubuntu-24.04
strategy:
matrix:
include:
- maf: 'agent-framework-core==1.20.0'
sdk: 'openviking-sdk==0.1.13'
- maf: 'agent-framework-core>=1.20,<2'
sdk: 'openviking-sdk>=0.1.13,<0.2'
defaults:
run:
working-directory: examples/agent-framework
steps:
- uses: actions/checkout@v6
- uses: actions/setup-python@v6
with:
python-version: '3.12'
- name: Install supported dependencies
run: python -m pip install '.[test,dev]' '${{ matrix.maf }}' '${{ matrix.sdk }}'
- name: Check package and offline contracts
run: |
ruff check .
ruff format --check .
mypy src
pytest -q --confcutdir=tests tests
python -m build
python -m twine check dist/*
118 changes: 118 additions & 0 deletions examples/agent-framework/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
# OpenViking for Microsoft Agent Framework

An optional Python package for MAF agents. It recalls OpenViking context before a
run and captures completed agent runs, including tool calls and results.
The application controls when memory extraction is requested.

## Install and try

Requires Python 3.10+, MAF core 1.20–1.x, OpenViking SDK 0.1.13–0.1.x, and a
running OpenViking 0.4.23+ server. Install from an OpenViking checkout:

```bash
pip install './examples/agent-framework[example]'
```

Set `OPENVIKING_URL`, `OPENVIKING_API_KEY` (a normal user key), `OPENAI_API_KEY`,
`OPENAI_BASE_URL`, and `OPENAI_MODEL`, then run:

```bash
python examples/agent-framework/example.py
```

The example records a preference, waits for extraction, and asks about it in a new
conversation. Its OpenAI-compatible model client is optional; the provider works
with other MAF chat clients that support chat middleware (including the built-in
clients). The package installs neither the OpenViking server
nor a model client unless the `example` extra is selected.

## Attach to an existing agent

With an initialized, application-owned `AsyncHTTPClient`:

```python
from agent_framework import Agent
from openviking_agent_framework import OpenVikingContextProvider

memory = OpenVikingContextProvider(client)
agent = Agent(chat_client, context_providers=[memory])
session = agent.create_session()
response = await agent.run("Remember my preferred reply format: JSON.", session=session)
job = await memory.commit(session)
```

`commit()` returns task acceptance. Poll `client.get_task(job["task_id"])` until
completion before checking extracted memory. Close the client in the application.

## Capture and commit policies

```python
memory = OpenVikingContextProvider(
client,
capture=True,
commit_policy="pending_tokens",
commit_token_threshold=20_000,
)
```

| `commit_policy` | Behavior |
| --- | --- |
| `"never"` (default) | Capture automatically; the application calls `commit(session)` |
| `"always"` | Request a commit after each completed, captured agent invocation |
| `"pending_tokens"` | Request a commit when OV's post-capture pending tokens reach the threshold |

The threshold defaults to 20,000 and must be a positive integer. It counts the
session's captured, uncommitted tokens; `token_budget` controls recalled context.
Policies run only after all message batches are acknowledged. A successful
`flush()` of pending capture also applies the policy. Commit or metadata errors
propagate, but acknowledged messages remain recorded and are not sent again;
the next completed invocation or an explicit `commit()` can retry the commit.
Automatic commits start background extraction and do not wait for completion.

Set `capture=False` for automatic recall without conversation uploads or
automatic commits. Explicit `flush()` and `commit()` remain available. Turning
capture off does not discard existing pending messages. The application still
calls `commit()` at its conversation/workflow boundary to extract a tail below
the threshold. These policies do not change OV's server-side auto-commit settings.

## State and failure handling

- Use one client/provider per user and actor; serialize work for the same session.
- Persist `session.to_dict()` and restore with `AgentSession.from_dict()` under the
same authenticated user. Preserve message IDs when replaying previous messages.
- Recalled context is attributed reference data and is excluded from capture.
System instructions, hidden reasoning, and nontext media are also excluded.
- Fully consume streaming responses. Capture happens after each completed agent
run, including each `AgentLoopMiddleware` iteration, for both streaming and
non-streaming runs. If a later iteration is interrupted, earlier completed
iterations remain captured; the interrupted iteration is excluded.
- Middleware must preserve provider state. `fresh_context=True` rolls that state
back between loop iterations and is unsupported; detected state resets raise
before further capture or commit.
- Errors propagate. Unconfirmed capture blocks another run and `commit()`.
`flush(session)` retries pending messages after a known failure before sending.
A lost response can mean the server already appended the messages: inspect
active records and archives by `source_message_ids` before retrying or updating
the saved provider state. Blind retries can duplicate capture.

The application owns MAF session persistence; there is no exactly-once guarantee.
Options are `source_id="openviking"`, `limit=5`, `token_budget=4000` (64–32000),
and `peer_scope="all"`. Use `peer_scope="actor"` with the SDK client's actor ID.
The server owns access control, retrieval, storage, and extraction; MAF owns agent
execution and chat history. No framework modifications or MCP tools are required.

## Validate

```bash
pip install -e './examples/agent-framework[test,dev]'
cd examples/agent-framework
pytest -q --confcutdir=tests tests
ruff check .
ruff format --check .
mypy src
python -m build
```

Offline tests use the real MAF agent lifecycle with deterministic model and SDK
boundaries. They require no server, credentials, or model calls. Support belongs
in [OpenViking issues](https://github.com/volcengine/OpenViking/issues/new/choose).
57 changes: 57 additions & 0 deletions examples/agent-framework/example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
"""Record a preference and recall it in a new MAF conversation."""

import asyncio
import os
import time

from agent_framework import Agent
from agent_framework.openai import OpenAIChatCompletionClient
from openai import AsyncOpenAI
from openviking_sdk import AsyncHTTPClient

from openviking_agent_framework import OpenVikingContextProvider


async def main():
client = AsyncHTTPClient(
url=os.environ["OPENVIKING_URL"], api_key=os.environ["OPENVIKING_API_KEY"], timeout=60
)
await client.initialize()
try:
memory = OpenVikingContextProvider(client)
async with AsyncOpenAI(
api_key=os.environ["OPENAI_API_KEY"], base_url=os.environ["OPENAI_BASE_URL"]
) as model:
agent = Agent(
OpenAIChatCompletionClient(model=os.environ["OPENAI_MODEL"], async_client=model),
instructions="Use retrieved reference data when relevant.",
context_providers=[memory],
)
session = agent.create_session()
print(
(await agent.run("Remember my preferred reply format: JSON.", session=session)).text
)
job = await memory.commit(session)
deadline = time.monotonic() + 180
while time.monotonic() < deadline:
task = await client.get_task(job["task_id"])
if task is None or task["status"] in {"failed", "cancelled"}:
raise RuntimeError(f"Extraction failed: {task}")
if task["status"] == "completed":
break
await asyncio.sleep(1)
else:
raise TimeoutError("Extraction did not complete within 180 seconds")
print(
(
await agent.run(
"What reply format do I prefer?", session=agent.create_session()
)
).text
)
finally:
await client.close()


if __name__ == "__main__":
asyncio.run(main())
43 changes: 43 additions & 0 deletions examples/agent-framework/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
[build-system]
requires = ["setuptools>=77.0", "wheel"]
build-backend = "setuptools.build_meta"

[project]
name = "openviking-agent-framework"
version = "0.1.0"
description = "OpenViking context provider for Microsoft Agent Framework"
readme = "README.md"
requires-python = ">=3.10"
license = "AGPL-3.0"
dependencies = ["agent-framework-core>=1.20,<2", "openviking-sdk>=0.1.13,<0.2"]

[project.optional-dependencies]
example = ["agent-framework-openai>=1.15,<2"]
test = ["pytest>=8", "pytest-asyncio>=0.24"]
dev = ["ruff", "mypy", "build", "twine"]

[project.urls]
Repository = "https://github.com/volcengine/OpenViking"
Documentation = "https://github.com/volcengine/OpenViking/tree/main/examples/agent-framework"
Issues = "https://github.com/volcengine/OpenViking/issues/new/choose"

[tool.setuptools.packages.find]
where = ["src"]

[tool.setuptools.package-data]
openviking_agent_framework = ["py.typed"]

[tool.pytest.ini_options]
asyncio_mode = "auto"

[tool.ruff]
line-length = 100
target-version = "py310"

[tool.ruff.lint]
select = ["E", "F", "I", "B"]

[tool.mypy]
python_version = "3.10"
check_untyped_defs = true
ignore_missing_imports = true
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
# SPDX-License-Identifier: AGPL-3.0
"""OpenViking memory for Microsoft Agent Framework."""

from .provider import OpenVikingContextProvider

__all__ = ["OpenVikingContextProvider"]
Loading
Loading