Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
62 changes: 62 additions & 0 deletions python/src/kimi_agent_sdk/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,65 @@
"""
Kimi Agent SDK is a Python SDK for building AI agents powered by Kimi.
It provides both high-level and low-level APIs for seamless agent integration, stateful sessions,
and tool orchestration in modern AI applications.

Key features:

- `kimi_agent_sdk.prompt` provides a high-level async generator API that sends prompts to Kimi
and yields aggregated Message objects, handling approval requests automatically or via custom
handlers.
- `kimi_agent_sdk.Session` offers low-level control with Wire message access, manual approval
handling, session persistence, and context management for long-running agent interactions.
- Message structures, approval types, and exceptions are re-exported from kosong and kimi_cli
for convenient access.

Example (high-level API):

```python
import asyncio

from kimi_agent_sdk import prompt


async def main() -> None:
async for message in prompt(
"What is the capital of France?",
model="kimi",
yolo=True,
):
print(message.extract_text())


asyncio.run(main())
```

Example (low-level API with Session):

```python
import asyncio

from kaos.path import KaosPath

from kimi_agent_sdk import ApprovalRequest, Session


async def main() -> None:
async with await Session.create(
work_dir=KaosPath.cwd(),
model="kimi",
yolo=False,
) as session:
async for wire_msg in session.prompt("What is the capital of France?"):
if isinstance(wire_msg, ApprovalRequest):
wire_msg.resolve("approve")
else:
print(wire_msg)


asyncio.run(main())
```
"""

from __future__ import annotations

from fastmcp.mcp_config import MCPConfig
Expand Down
27 changes: 27 additions & 0 deletions python/src/kimi_agent_sdk/_aggregator.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,30 @@
"""
Wire message aggregation for Kimi Agent SDK.

This module provides the MessageAggregator class that transforms streaming Wire messages
(low-level protocol messages) into aggregated Message objects (high-level content structures).
It supports two output modes: full step-by-step messages with tool calls/results, or final
message text only.

Key classes:

- `MessageAggregator` buffers and merges WireMessage events (ContentPart, ToolCall, ToolResult)
and flushes them as complete Message objects at step boundaries.

Example:

```python
from kimi_agent_sdk._aggregator import MessageAggregator

aggregator = MessageAggregator(final_message_only=False)
for wire_msg in wire_stream:
for message in aggregator.feed(wire_msg):
print(message)
for message in aggregator.flush():
print(message)
```
"""

from __future__ import annotations

from dataclasses import dataclass
Expand Down
26 changes: 26 additions & 0 deletions python/src/kimi_agent_sdk/_approval.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,29 @@
"""
Approval handling types for Kimi Agent SDK.

This module defines the ApprovalHandlerFn type for custom approval handling in agent sessions.
Approval handlers allow you to programmatically approve or reject tool execution requests from
the agent, providing fine-grained control over what actions the agent can perform.

Key types:

- `ApprovalHandlerFn` is a callback function type that receives ApprovalRequest objects and
resolves them with "approve", "approve_for_session", or "reject".

Example:

```python
from kimi_agent_sdk import ApprovalRequest


def my_handler(request: ApprovalRequest) -> None:
if request.sender == "bash":
request.resolve("approve")
else:
request.resolve("reject")
```
"""

from __future__ import annotations

from collections.abc import Awaitable, Callable
Expand Down
14 changes: 14 additions & 0 deletions python/src/kimi_agent_sdk/_exception.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,17 @@
"""
Custom exceptions for Kimi Agent SDK.

This module defines SDK-specific exceptions for validation and state management errors.
All exceptions inherit from KimiCLIException for consistent error handling across the SDK.

Key exceptions:

- `PromptValidationError` is raised when prompt configuration is invalid (e.g., neither yolo
nor approval_handler_fn is provided).
- `SessionStateError` is raised when session operations are performed in invalid states (e.g.,
prompting while already running or after closing).
"""

from __future__ import annotations

from kimi_cli.exception import KimiCLIException
Expand Down
59 changes: 59 additions & 0 deletions python/src/kimi_agent_sdk/_prompt.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,62 @@
"""
High-level prompt API for Kimi Agent SDK.

This module provides the prompt function, the highest-level API for sending prompts to Kimi
and receiving aggregated Message responses. It handles session lifecycle, approval requests,
and message aggregation automatically.

Key functions:

- `prompt` is an async generator that creates a session, sends a prompt, handles approvals via
yolo mode or custom handler, and yields aggregated Message objects similar to
`kimi --print --output stream-json`.

Example:

```python
import asyncio

from kimi_agent_sdk import prompt


async def main() -> None:
async for message in prompt(
"What is 2 + 3?",
model="kimi",
yolo=True,
):
print(message.extract_text())


asyncio.run(main())
```

Example (with custom approval handler):

```python
import asyncio

from kimi_agent_sdk import ApprovalRequest, prompt


def my_approval_handler(request: ApprovalRequest) -> None:
print(f"Approval requested: {request.description}")
request.resolve("approve")


async def main() -> None:
async for message in prompt(
"Create a file named test.txt",
model="kimi",
approval_handler_fn=my_approval_handler,
):
print(message.extract_text())


asyncio.run(main())
```
"""

from __future__ import annotations

import inspect
Expand Down
38 changes: 38 additions & 0 deletions python/src/kimi_agent_sdk/_session.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,41 @@
"""
Session management for Kimi Agent SDK.

This module provides the Session class for low-level agent control with Wire message access,
manual approval handling, and session persistence. Use Session when you need full control over
agent execution flow, custom approval logic, or resumable sessions across multiple prompts.

Key classes:

- `Session` wraps KimiCLI to provide stateful agent sessions with async context manager support,
cancellation, and resource cleanup.

Example:

```python
import asyncio

from kaos.path import KaosPath

from kimi_agent_sdk import ApprovalRequest, Session


async def main() -> None:
async with await Session.create(
work_dir=KaosPath.cwd(),
model="kimi",
) as session:
async for wire_msg in session.prompt("Hello!"):
if isinstance(wire_msg, ApprovalRequest):
wire_msg.resolve("approve")
else:
print(wire_msg)


asyncio.run(main())
```
"""

from __future__ import annotations

import asyncio
Expand Down
Loading