Metadata-Version: 2.4
Name: kaiwen-agent
Version: 0.7.0a1
Summary: Provider-neutral asynchronous agent runtime
Project-URL: Homepage, https://github.com/ImtheKaiwen/kaiwen-agent-platform
Project-URL: Documentation, https://github.com/ImtheKaiwen/kaiwen-agent-platform/tree/main/docs
Project-URL: Repository, https://github.com/ImtheKaiwen/kaiwen-agent-platform.git
Project-URL: Issues, https://github.com/ImtheKaiwen/kaiwen-agent-platform/issues
Author: Kaiwen
License: MIT
Keywords: agent,ai,asyncio,openai,tools
Classifier: Development Status :: 3 - Alpha
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: pydantic<3,>=2.10
Provides-Extra: dev
Requires-Dist: mypy==1.20.2; extra == 'dev'
Requires-Dist: openai<3,>=2; extra == 'dev'
Requires-Dist: pytest<9,>=8.3; extra == 'dev'
Requires-Dist: python-dotenv<2,>=1.1; extra == 'dev'
Requires-Dist: ruff==0.17.1; extra == 'dev'
Provides-Extra: gemini
Requires-Dist: google-genai<2,>=1; extra == 'gemini'
Provides-Extra: ollama
Requires-Dist: ollama<1,>=0.6; extra == 'ollama'
Provides-Extra: openai
Requires-Dist: openai<3,>=2; extra == 'openai'
Provides-Extra: openai-live
Requires-Dist: websockets<17,>=15; extra == 'openai-live'
Provides-Extra: postgres-memory
Requires-Dist: pgvector<1,>=0.3; extra == 'postgres-memory'
Requires-Dist: psycopg-pool<4,>=3.2; extra == 'postgres-memory'
Requires-Dist: psycopg[binary]<4,>=3.2; extra == 'postgres-memory'
Provides-Extra: redis
Requires-Dist: redis<7,>=5.2; extra == 'redis'
Provides-Extra: release
Requires-Dist: build<2,>=1.2; extra == 'release'
Requires-Dist: twine<7,>=6; extra == 'release'
Description-Content-Type: text/markdown

# kaiwen-agent

Provider-neutral, asynchronous Python runtime for building tool-using agents.
Product applications own their prompts, domain tools, authorization context,
persistence choice, and HTTP surface.

```bash
pip install "kaiwen-agent[openai]"
```

For OpenAI Live primary WebSocket support:

```bash
pip install "kaiwen-agent[openai-live]"
```

Optional text providers are installed independently:

```bash
pip install "kaiwen-agent[gemini]"
pip install "kaiwen-agent[ollama]"
```

## Minimal agent

```python
import asyncio

from pydantic import BaseModel

from kaiwen_agent import Agent, AgentContext, tool
from kaiwen_agent.models.openai import OpenAIResponsesProvider
from kaiwen_agent.types import AgentInput


class ProjectQuery(BaseModel):
    category: str | None = None


@tool(
    name="projects.read",
    description="List projects visible to the current user",
    input_model=ProjectQuery,
    permissions={"projects.read"},
)
async def read_projects(
    context: AgentContext,
    query: ProjectQuery,
) -> list[dict[str, str]]:
    repository = context.services["projects"]
    return await repository.list(category=query.category)


async def main() -> None:
    agent = Agent(
        name="portfolio",
        model=OpenAIResponsesProvider(
            model="your-model-id",
            instructions="Help visitors discover relevant products.",
            store=False,
        ),
        tools=[read_projects],
        permissions={"projects.read"},
    )
    result = await agent.run(
        AgentInput(text="Show me the games"),
        context=AgentContext(
            session_id="session-id",
            permissions=frozenset({"projects.read"}),
            services={"projects": your_repository},
        ),
    )
    print(result.text)


asyncio.run(main())
```

For a single-agent composition that keeps normal chat tool-free and makes action
tools explicit:

```python
from kaiwen_agent import AgentRuntime, RuntimeIdentity

runtime = AgentRuntime(name="assistant", model=provider, tools=[read_projects])
reply = await runtime.chat(
    "Merhaba",
    identity=RuntimeIdentity(session_id="session-id"),
)
```

`AgentRuntime.action()` exposes only the tool names selected by trusted host code.
`AgentRuntime.run()` keeps workflow mode fail-closed. Autonomous hosts explicitly
compose `WorkflowController` with durable run state, the existing Task Runtime, and
completion gates; it never falls back to an unsafe in-memory workflow.

Larger applications can register immutable `AgentDefinition` records and compose
them through `AgentFactory` plus a strict `WorkspaceProfile`. The factory resolves
exact prompt and capability versions, constructs a fresh provider instance, validates
tool visibility against both capability and workspace allowlists, and records the
selected versions in runtime context. Policy and execution-time permission checks
remain authoritative; configuration never grants additional access.

The smallest credential-free runtime example is
[`examples/simple-runtime`](../examples/simple-runtime). The provider-neutral fake
speech composition is in [`examples/speech-pipeline`](../examples/speech-pipeline).
Durable single-agent workflow and least-privilege team composition are demonstrated
in [`examples/autonomous-single-agent`](../examples/autonomous-single-agent) and
[`examples/software-agent-team`](../examples/software-agent-team). All four are
executed by CI so their public imports stay valid.

Applications may inject `ContextBuilder`, `ContextWindow`, and
`ContextCompactionManager` into the runtime. Context collection stays optional for
simple chat, uses a provider-specific `TokenCounter` when available, and never treats
lossy session summaries as policy or configuration. Use
`ArtifactToolResultProcessor` when large tool output should be stored out-of-band and
represented to the model by an owner-scoped artifact reference.

Runtime delivery requirements use immutable `StandardsPack` definitions and
host-registered verifiers. `CompletionGate` accepts a mandatory requirement only when
its artifact evidence is owned by the trusted user, belongs to the current run, and
matches both the protected input fingerprint and declared evidence type. The package
does not include product-specific test, legal, citation, or CI verifiers.

`OPENAI_API_KEY` is read by the OpenAI SDK from the server environment. The
runtime never stores it and it must never be exposed to browser code.

## Runtime capabilities

- Provider-neutral async agent loop and deterministic fake provider.
- Typed Pydantic tool inputs and deny-by-default permission intersection.
- Approval, idempotency, timeout, and retry handling for side effects.
- Session, run, event, and audit ports with a SQLite reference adapter.
- SSE event fan-out and trace propagation.
- Durable task graphs, workers, checkpoints, mailbox control, resource locks,
  cancellation, and bounded concurrency.
- Optional OpenAI Responses API adapter.
- Optional Gemini Generate Content and Ollama Chat adapters. Provider SDKs only
  return tool proposals; central runtime execution remains authoritative.
- Technical model capability records and data-locality-aware routing that prevents
  cloud fallback for `local_only` requests.
- Provider-neutral Realtime sessions, OpenAI Live/WebRTC adapters, durable
  text-and-voice conversations, and allowlisted background task delegation.
- Trusted OpenAI Live sideband execution through the same permission, approval,
  idempotency, and audit pipeline used by text agents.
- Deterministic lifecycle and central policy runtimes, bounded context assembly,
  short-term session summaries, and policy-gated long-term memory.
- Non-blocking background jobs projected onto the existing Task Runtime, including
  progress events, cooperative cancellation, parent-child progress, and recovery.
- A deterministic Trigger Router that filters, deduplicates, debounces, and
  coalesces untrusted events before scheduling lifecycle wakeups.
- Policy-gated model routing, hierarchical runtime budgets, immutable versioned
  prompt and declarative skill registries, owner-scoped artifacts, and inspectable
  capability manifests.
- Structured evaluation, observation-only replay, fail-closed simulation,
  tenant-scoped redacted dead letters, backpressure, optional Redis coordination
  leases with fencing tokens, fixed-catalog tenant-scoped metrics, heartbeat health,
  and an allowlisted server-side secret-provider boundary.
- Optional PostgreSQL full-text + pgvector hybrid memory retrieval via
  `kaiwen-agent[postgres-memory]`.
- Optional Redis distributed lease coordination via `kaiwen-agent[redis]`.
- Optional root-bounded workspace filesystem tools and trusted MCP bindings. Remote
  discovery does not grant authority; both use the central tool safety pipeline.

Realtime usage and integration boundaries are documented in the repository's
`docs/realtime.md`, `docs/openai-live.md`, and `docs/conversation-bridge.md` files.

## Side effects

Tools marked `reversible` or `destructive` receive a runtime idempotency key.
Set `requires_approval=True` and supply an application-owned `ApprovalGate` for
publishing, deleting, deploying, calling, or sending messages. Applications
must still perform authorization inside their own service boundary. Memory setup and
its trust boundaries are documented in `docs/long-term-memory.md`.

## Coding-agent handoff

When asking another coding agent to integrate this package, provide the root
repository files `AGENTS.md` and `docs/consumer-agent-brief.md`. The complete,
provider-free example is in `examples/basic-agent`.
