Skip to content
Closed
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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,7 @@ Coding and memory evaluations, performance benchmarks, and Skill regressions liv
- [Manage context](https://powercontext.oceanbase.io/en/docs/workflows/)
- [Deploy and operate](https://powercontext.oceanbase.io/en/docs/operate/)
- [Develop with APIs](https://powercontext.oceanbase.io/en/docs/develop/)
- [Use a native model SDK](https://powercontext.oceanbase.io/en/docs/develop/native-sdk/)

PowerContext is the successor to [PowerMem](https://www.powermem.ai/).

Expand Down
1 change: 1 addition & 0 deletions README_CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,7 @@ make test
- [管理上下文](https://powercontext.oceanbase.io/zh/docs/workflows/)
- [部署与运维](https://powercontext.oceanbase.io/zh/docs/operate/)
- [开发与 API](https://powercontext.oceanbase.io/zh/docs/develop/)
- [使用原生模型 SDK](https://powercontext.oceanbase.io/zh/docs/develop/native-sdk/)

PowerContext 是 [PowerMem](https://www.powermem.ai/) 的后续项目。

Expand Down
1 change: 1 addition & 0 deletions README_JP.md
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,7 @@ make test
- [コンテキストの管理](https://powercontext.oceanbase.io/en/docs/workflows/)
- [デプロイと運用](https://powercontext.oceanbase.io/en/docs/operate/)
- [開発と API](https://powercontext.oceanbase.io/en/docs/develop/)
- [ネイティブモデル SDK を使う](https://powercontext.oceanbase.io/en/docs/develop/native-sdk/)

PowerContext は [PowerMem](https://www.powermem.ai/) の後継プロジェクトです。

Expand Down
4 changes: 3 additions & 1 deletion docs/en/docs/develop/api-quickstart.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,9 @@ uv run python -m examples.openai_sdk.chat --seed
```

The example reads the same `POWERCONTEXT_URL`, `POWERCONTEXT_TOKEN`, and `POWERCONTEXT_SCOPE` variables. Its README
lists the model settings, the expected output, and offline tests that need no credentials.
lists the model settings, the expected output, and offline tests that need no credentials. The
[native SDK guide](native-sdk.md) covers this pattern for OpenAI and Anthropic, including the PreparedContext
contract, credential and Scope handling, and offline tests.

## Next workflows

Expand Down
3 changes: 3 additions & 0 deletions docs/en/docs/develop/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ description: Connect applications through the HTTP API, Python Client, or Core S
Use the [API Quick Start](api-quickstart.md) to connect an application, capture evidence, save Memory, and prepare
context for one request. It uses a local Server and needs no model for explicit writes.

When your application calls OpenAI or Anthropic itself, follow [Use a native model SDK](native-sdk.md) to add
PreparedContext to that request without an Agent host or framework adapter.

Choose an [interface](interfaces.md) for your application: the async Python Client and HTTP API connect to a running
Server, while the Core SDK supports in-process composition. MCP exposes a curated subset for Agents.

Expand Down
1 change: 1 addition & 0 deletions docs/en/docs/develop/meta.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"pages": [
"index",
"api-quickstart",
"native-sdk",
"interfaces",
"http-api"
]
Expand Down
214 changes: 214 additions & 0 deletions docs/en/docs/develop/native-sdk.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
---
title: Use a native model SDK
description: Add PowerContext PreparedContext to an application that calls OpenAI or Anthropic directly.
---

# Use a native model SDK

PowerContext does not wrap or replace your model SDK. The application keeps its own `openai` or `anthropic` client
and calls PowerContext separately through the async Python Client. No Agent host, prompt hook, plugin, or MCP
connection is required.

Use this pattern when an application, service, or script owns the model loop and you want to keep provider-specific
code in that application. If instead you want a host to capture prompts and recall context automatically, choose an
[Agent integration](../integrations/index.md).

## Request flow

For each turn, the application:

1. selects and authorizes one existing Scope in trusted code;
2. calls `prepare_context` with the current question as the query and a byte budget;
3. sends one model request, adding the returned `content` to the system prompt when the result is `ready`;
4. continues normally when the result is `empty`.

PowerContext is a separate service. The model provider request and the PowerContext request use independent clients
and credentials.

## Runnable examples

Two examples implement the same loop with different provider SDKs:

| SDK | Example | Command |
| --- | --- | --- |
| OpenAI | [`examples/openai_sdk`](https://github.com/oceanbase/powercontext/tree/master/examples/openai_sdk) | `uv run python -m examples.openai_sdk.chat --seed` |
| Anthropic | [`examples/anthropic_sdk`](https://github.com/oceanbase/powercontext/tree/master/examples/anthropic_sdk) | `uv run python -m examples.anthropic_sdk.chat --seed` |

Both create or reuse an example Scope through a stable idempotency key, save one billing decision with `--seed`, call
`prepare_context` with a 4000-byte budget, and send one request. Ready content is appended to the system prompt
unchanged; empty content sends the instructions and question without history.

Each example README lists installation, environment variables, expected output, and its offline tests.

## 1. Start a Server

Install the Server and CLI, then keep the Server running:

```bash
uv tool install --force "powercontext[cli,server] @ git+https://github.com/oceanbase/powercontext.git@master"
powercontext server run
```

From a repository checkout, `uv sync` followed by `uv run powercontext server run` is equivalent. See
[Install and run](../get-started/install-and-run.md) for release selection, storage, and platform requirements.

## 2. Run an example

The example modules live in the repository, not in the published wheel, so they must be run from a clone. The
`uv tool install` in step 1 installs only the Server and CLI. In a second terminal:

```bash
git clone https://github.com/oceanbase/powercontext.git
cd powercontext
uv sync
```

Then, from the repository root, set the provider key and run one example:

```bash
export OPENAI_API_KEY=replace-with-a-secret-store-value
uv run python -m examples.openai_sdk.chat
uv run python -m examples.openai_sdk.chat --seed
Comment on lines +70 to +71

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Require a source checkout before running the example modules

If a reader follows step 1's uv tool install path from outside a repository checkout, these commands fail with ModuleNotFoundError: No module named 'examples'. The wheel only packages src/powercontext and src/powercontext_service_bootstrap (pyproject.toml:209-210), not examples/, and uv help run states that outside a project it uses “the environment of the discovered interpreter,” not the isolated tool environment. Add an explicit checkout, cd, and uv sync prerequisite before this step in both locale guides.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This still reproduces at dec3b4dd: running the Anthropic example from outside a checkout fails with ModuleNotFoundError because the examples are not included in the installed wheel. Could you add the clone, cd, and dependency setup steps to both language guides before the example commands?

```

```bash
export ANTHROPIC_API_KEY=replace-with-a-secret-store-value
uv run python -m examples.anthropic_sdk.chat
uv run python -m examples.anthropic_sdk.chat --seed
```

The first command in each pair uses a Scope with no relevant Memory, so PreparedContext is `empty` and the request
carries no history. The second saves the example decision first, so PreparedContext is `ready`:

```text
Scope: scp_...
PreparedContext: ready (601 bytes)
Answer:
...
```

Pass a different question as the first argument. Both examples also read `POWERCONTEXT_URL`, `POWERCONTEXT_TOKEN`, and
`POWERCONTEXT_SCOPE`.

## 3. Add it to your application

The provider code stays ordinary SDK code. Only the system prompt changes, and only when PowerContext returns content.

OpenAI:

```python
from openai import AsyncOpenAI
from powercontext.client import PowerContextClient
from powercontext.http import PrepareContextRequest, PreparedContext

prepared = await powercontext.prepare_context(
PrepareContextRequest(scope_id=scope_id, query=question, max_bytes=4000)
)
if not isinstance(prepared, PreparedContext):
raise TypeError("ordinary context preparation returned an unexpected envelope")

system = SYSTEM_INSTRUCTIONS
if prepared.status == "ready" and prepared.content:
system = f"{SYSTEM_INSTRUCTIONS}\n\n{prepared.content}"

completion = await openai.chat.completions.create(
model=model,
messages=[
{"role": "system", "content": system},
{"role": "user", "content": question},
],
)
answer = completion.choices[0].message.content or ""
```

Anthropic:

```python
from anthropic import AsyncAnthropic
from powercontext.client import PowerContextClient
from powercontext.http import PrepareContextRequest, PreparedContext

prepared = await powercontext.prepare_context(
PrepareContextRequest(scope_id=scope_id, query=question, max_bytes=4000)
)
if not isinstance(prepared, PreparedContext):
raise TypeError("ordinary context preparation returned an unexpected envelope")

system = SYSTEM_INSTRUCTIONS
if prepared.status == "ready" and prepared.content:
system = f"{SYSTEM_INSTRUCTIONS}\n\n{prepared.content}"

message = await anthropic.messages.create(
model=model,
max_tokens=1024,
system=system,
messages=[{"role": "user", "content": question}],
stream=False,
)
answer = "".join(block.text for block in message.content if block.type == "text")
```

Create the clients once per application and close them with `async with PowerContextClient(...)` and the provider
client's async context manager. `prepare_context` returns ordinary `PreparedContext` unless `include_reuse=True`; then
it returns a versioned reuse envelope. The examples use the ordinary response.

## PreparedContext contract

`PreparedContext` is the bounded, read-only result of one preparation request:

| Field | Meaning |
| --- | --- |
| `status` | `ready` when content was selected, `empty` when nothing relevant was available |
| `content` | Selected text for `ready`, or `None` for `empty` |
| `content_bytes` | UTF-8 size of `content` |

`max_bytes` accepts 512 to 32768 bytes and defaults to 8000. An `empty` result is normal for a new or unrelated Scope;
send the model request without history and do not invent context.

Pass `content` to the model unchanged. It is already bounded and carries its own notice that it is untrusted history,
plus citations. Do not truncate it again. Current instructions, authorization, live system state, and fresh
validation always take precedence over recalled text. Keep it out of the trusted-instruction section's authority:
treat it as data, not as a new policy.

PreparedContext is ephemeral. If a later turn needs context again, call `prepare_context` again with that turn's query.

## Configure access and Scope

| Variable | Default | Purpose |
| --- | --- | --- |
| `POWERCONTEXT_URL` | `http://127.0.0.1:8000` | PowerContext Server URL |
| `POWERCONTEXT_TOKEN` | unset | Bearer token when Server authentication is enabled |
| `POWERCONTEXT_SCOPE` | unset | Existing Scope ID for the examples |

The trusted application owns these values. A Scope ID is a data partition key, not an access-control check or proof of
user identity. Choose and authorize it in trusted code; never let model output select another user's Scope. Credentials
belong in transport configuration only, never in a prompt, log line, or Memory entry.

Loopback HTTP is allowed by default. For non-loopback HTTP, use HTTPS or the explicit consent described in
[Connect to a remote Server](../operate/connect-remote-server.md). HTTPS certificate validation stays enabled.

## Retrieval and empty results

The default Server uses full-text search, so recall depends on the query sharing terms with saved Memory. For semantic
retrieval, configure [vector search](../workflows/configure-vector-search.md). Retrieval mode is a Server policy; the
native SDK caller only supplies the query and byte budget.

## Test without credentials

The example tests replace the PowerContext Server and the model endpoint with `httpx.MockTransport` while using the
real PowerContext Client and provider SDK. They check the prepare request, the system prompt and messages for `ready`
and `empty`, and that credentials appear only in request headers:

```bash
uv run pytest tests/examples/openai_sdk tests/examples/anthropic_sdk
```

These tests use simulated responses. They do not prove that a particular Server or provider returns them; use the
smoke-test commands above for that.

## Next

- [API Quick Start](api-quickstart.md): capture a Source and write Memory with the HTTP API.
- [Interfaces](interfaces.md): compare the Python Client, HTTP API, and Core SDK.
- [HTTP behavior](http-api.md): authentication, request IDs, errors, and concurrency.
- [Python Agent frameworks](../integrations/index.md#python-agent-frameworks): adapters that own the model loop.
7 changes: 7 additions & 0 deletions docs/en/docs/integrations/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,13 @@ All 3 adapters are `community`. Install them in the application environment; do
| [LangChain](langchain.md) | Middleware for context and optional Source capture | `master_only` |
| [LangGraph](langgraph.md) | Recall hook and Memory tools | `master_only` |

## Native model SDKs

When an application already calls OpenAI or Anthropic through its own SDK, it does not need an Agent host or framework
adapter. Keep the provider client and add PowerContext with the async Python Client. [Use a native model SDK](../develop/native-sdk.md)
covers the request flow, the PreparedContext contract, credential and Scope handling, and runnable OpenAI and Anthropic
examples.

## Evaluation integrations

[Bub is for evaluation only](evaluation.md). It is not part of the Agent Host or Python Agent framework support lists.
Expand Down
3 changes: 2 additions & 1 deletion docs/zh/docs/develop/api-quickstart.md
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,8 @@ uv run python -m examples.openai_sdk.chat --seed
```

示例读取相同的 `POWERCONTEXT_URL`、`POWERCONTEXT_TOKEN` 和 `POWERCONTEXT_SCOPE` 变量。其 README 列出了模型配置、
预期输出,以及无需凭据的离线测试。
预期输出,以及无需凭据的离线测试。[原生 SDK 指南](native-sdk.md)说明 OpenAI 与 Anthropic 的这一接入方式,包括
PreparedContext 契约、凭据与 Scope 处理,以及离线测试。

## 后续工作流

Expand Down
3 changes: 3 additions & 0 deletions docs/zh/docs/develop/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ description: 通过 HTTP API、Python Client 或 Core SDK 接入应用。
通过 [API Quick Start](api-quickstart.md)连接应用、采集证据、保存 Memory,并为一次请求准备上下文。
该流程使用本地 Server,显式写入不需要模型。

如果应用直接调用 OpenAI 或 Anthropic,请按[使用原生模型 SDK](native-sdk.md)把 PreparedContext 加入该请求,
无需 Agent Host 或框架适配器。

按应用选择[接口](interfaces.md):异步 Python Client 和 HTTP API 连接运行中的 Server,
Core SDK 支持进程内组合。MCP 向 Agent 暴露经过选择的工具子集。

Expand Down
1 change: 1 addition & 0 deletions docs/zh/docs/develop/meta.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"pages": [
"index",
"api-quickstart",
"native-sdk",
"interfaces",
"http-api"
]
Expand Down
Loading
Loading