Skip to content

CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.

docs(website): use @tool in next docs; fix stripped Unreleased changelog heading

Claudee9a4e3116338
diff --git a/website/docs/getting-started/core-concepts.md b/website/docs/getting-started/core-concepts.md
index 0f17f99..0ef986e 100644
--- a/website/docs/getting-started/core-concepts.md
+++ b/website/docs/getting-started/core-concepts.md
@@ -34,34 +34,26 @@ sync or async.
## Tool
-An `AgentTool` is a name + description + Pydantic parameter model +
-async `execute` function:
+A tool is an async function the model can call. Decorate it with
+`@tool` and CubePi generates the input schema from the parameters:
```python
-from pydantic import BaseModel
-from cubepi import AgentTool, AgentToolResult, TextContent
-
-class SearchParams(BaseModel):
- query: str
- limit: int = 10
-
-async def execute(tool_call_id, params: SearchParams, *, signal=None, on_update=None):
- # do work; respect `signal` if you can be aborted
- return AgentToolResult(content=[TextContent(text=f"…")])
-
-search = AgentTool(
- name="search",
- description="Search the corpus",
- parameters=SearchParams,
- execute=execute,
-)
+from cubepi import tool
+
+@tool
+async def search(query: str, limit: int = 10) -> str:
+ "Search the corpus"
+ # do work; declare `signal` / `on_update` in the signature if you need them
+ return "…"
```
-The Pydantic schema is auto-converted to JSON Schema and passed to the
-model. Arg parsing, error wrapping, and parallel execution are
-handled by the framework. See [Tool Use](../guides/agents/tool-use)
-for `execution_mode`, `on_update` (incremental progress), and
-`terminate` (end the turn from a tool).
+`@tool` builds an `AgentTool` (name + description + Pydantic parameter
+model + async `execute`); the schema is auto-converted to JSON Schema
+and passed to the model. Arg parsing, error wrapping, and parallel
+execution are handled by the framework. See
+[Tool Use](../guides/agents/tool-use) for the longhand `AgentTool(...)`,
+`execution_mode`, `on_update` (incremental progress), and `terminate`
+(end the turn from a tool).
## Provider
diff --git a/website/docs/getting-started/quick-start.md b/website/docs/getting-started/quick-start.md
index 3f44e5d..45f9152 100644
--- a/website/docs/getting-started/quick-start.md
+++ b/website/docs/getting-started/quick-start.md
@@ -22,21 +22,16 @@ Save this as `weather_agent.py`:
```python title="weather_agent.py"
import asyncio
import os
-from pydantic import BaseModel
-from cubepi import Agent, AgentTool, AgentToolResult, TextContent
+from cubepi import Agent, tool
from cubepi.providers.anthropic import AnthropicProvider
-class GetWeatherParams(BaseModel):
- city: str
-
-
-async def get_weather(tool_call_id, params: GetWeatherParams, *, signal=None, on_update=None):
+@tool
+async def get_weather(city: str) -> str:
+ "Get current weather for a city."
# In a real app: call an HTTP weather API. Here we hard-code a reply.
- return AgentToolResult(
- content=[TextContent(text=f"72°F and sunny in {params.city}")]
- )
+ return f"72°F and sunny in {city}"
async def main():
@@ -45,14 +40,7 @@ async def main():
agent = Agent(
model=provider.model("claude-sonnet-4-5-20250929"),
system_prompt="You are a concise weather assistant.",
- tools=[
- AgentTool(
- name="get_weather",
- description="Get current weather for a city",
- parameters=GetWeatherParams,
- execute=get_weather,
- ),
- ],
+ tools=[get_weather],
)
# Subscribe BEFORE prompt() — that's how you see streaming events.
@@ -86,8 +74,9 @@ CubePi ran a loop that looks (conceptually) like this:
1. `agent.prompt("What's the weather in Tokyo?")` enqueued a
`UserMessage` and called the model.
2. The model decided to invoke `get_weather(city="Tokyo")` — CubePi
- parsed the JSON args with your Pydantic model, called your `async
- def`, and fed the result back as a `ToolResultMessage`.
+ parsed the JSON args against the schema `@tool` generated from your
+ function signature, called your `async def`, and fed the result back
+ as a `ToolResultMessage`.
3. The model produced a final assistant response, streamed back as
`text_delta` events.
4. The loop emitted `agent_end` and returned.
@@ -104,9 +93,12 @@ runtime emits: `agent_start`, `turn_start`, `message_start`,
emitted *after* `subscribe` was called. Calling `prompt` first means
the early events are gone.
- **`provider.model(...)` binds the model to its provider.** The provider holds credentials and optional `provider_id` metadata; the model id must match a model that provider supports.
-- **The `execute` signature is fixed.** Keep `(tool_call_id, params,
- *, signal, on_update)` even if you don't use the keyword-only
- arguments. CubePi always passes them.
+- **Tools are decorated async functions.** `@tool` derives the input
+ schema from the typed parameters and uses the docstring as the
+ description; return a `str` (or an `AgentToolResult`). Need the raw
+ `(tool_call_id, params, *, signal, on_update)` form, a shared params
+ model, or `on_update` progress? See
+ [Tool Use](../guides/agents/tool-use).
- **`agent.prompt()` can only run one prompt at a time.** While it's
running, use [`agent.steer()`](../guides/agents/multi-turn) to
inject a follow-up, or `agent.follow_up()` to queue one for after
diff --git a/website/docs/guides/agents/first-agent.md b/website/docs/guides/agents/first-agent.md
index 58bdc25..7fdf75e 100644
--- a/website/docs/guides/agents/first-agent.md
+++ b/website/docs/guides/agents/first-agent.md
@@ -36,44 +36,32 @@ in 0.7.
## Step 2 — declare a tool
-Every tool is a Pydantic param model + an async `execute` function:
+A tool is an async function decorated with `@tool`:
```python
-from pydantic import BaseModel
-from cubepi import AgentTool, AgentToolResult, TextContent
+from cubepi import tool
-class GetWeatherParams(BaseModel):
- city: str
-
-
-async def get_weather(tool_call_id, params: GetWeatherParams, *, signal=None, on_update=None):
+@tool
+async def get_weather(city: str) -> str:
+ "Get current weather for a city. Returns a short text summary."
# do real work here — call an HTTP API, query a DB, etc.
- return AgentToolResult(
- content=[TextContent(text=f"72°F and sunny in {params.city}")]
- )
-
-
-weather_tool = AgentTool(
- name="get_weather",
- description="Get current weather for a city. Returns a short text summary.",
- parameters=GetWeatherParams,
- execute=get_weather,
-)
+ return f"72°F and sunny in {city}"
```
A few details:
-- The Pydantic model is auto-converted to JSON Schema and sent to the
- model as part of the tool definition.
-- The `execute` signature is fixed:
- `(tool_call_id, params, *, signal, on_update)`. The two
- keyword-only args are always passed — keep them in your signature
- even if you ignore them.
-- `signal` is an `asyncio.Event` that's set when the user cancels.
- Check it inside long-running work and bail out early.
-- `on_update(partial)` lets you stream incremental progress (covered
- in [Tool Use](./tool-use#streaming-tool-progress)).
+- The input schema is generated from the typed parameters and sent to
+ the model; the docstring becomes the tool description. Pydantic
+ `Field(...)` defaults and metadata are honoured.
+- Return a `str` (wrapped as text), a `Content`, a `list` of content,
+ or a full `AgentToolResult` when you need `details`/`is_error`.
+- Need cancellation or progress streaming? Declare `signal` (an
+ `asyncio.Event` set when the user cancels) and/or `on_update(partial)`
+ in the signature and CubePi injects them — see
+ [Tool Use](./tool-use#streaming-tool-progress).
+- For a shared params model or dynamic construction, the longhand
+ `AgentTool(...)` is equivalent — see [Tool Use](./tool-use).
## Step 3 — assemble the agent
@@ -83,7 +71,7 @@ from cubepi import Agent
agent = Agent(
model=model,
system_prompt="You are a concise weather assistant.",
- tools=[weather_tool],
+ tools=[get_weather],
)
```
diff --git a/website/docs/recipes/resumable-tasks.md b/website/docs/recipes/resumable-tasks.md
index 7e6de20..49bb324 100644
--- a/website/docs/recipes/resumable-tasks.md
+++ b/website/docs/recipes/resumable-tasks.md
@@ -41,8 +41,7 @@ import os
import json
from pathlib import Path
-from pydantic import BaseModel
-from cubepi import AgentTool, AgentToolResult, TextContent
+from cubepi import AgentToolResult, TextContent, tool
# Simple file-backed job store; replace with Redis / Postgres in prod.
@@ -50,13 +49,12 @@ JOB_DIR = Path(os.environ.get("JOB_DIR", "/tmp/cubepi-jobs"))
JOB_DIR.mkdir(parents=True, exist_ok=True)
-class TranscodeParams(BaseModel):
- source_path: str
- output_path: str
-
-
-async def transcode_video(tool_call_id, params: TranscodeParams, *, signal=None, on_update=None):
- job_key = f"transcode:{params.source_path}->{params.output_path}"
+# execution_mode="sequential" → one transcode at a time. Only `signal` is
+# declared, so that's the only loop-supplied arg injected.
+@tool(execution_mode="sequential")
+async def transcode_video(source_path: str, output_path: str, *, signal=None) -> AgentToolResult:
+ "Transcode a video file. Idempotent — safe to retry."
+ job_key = f"transcode:{source_path}->{output_path}"
job_file = JOB_DIR / f"{job_key.replace('/', '_')}.json"
if job_file.exists():
@@ -69,7 +67,7 @@ async def transcode_video(tool_call_id, params: TranscodeParams, *, signal=None,
# Do the actual work (long-running, expensive).
# Use signal to abort cleanly if cancelled.
- output = await run_ffmpeg(params.source_path, params.output_path, signal=signal)
+ output = await run_ffmpeg(source_path, output_path, signal=signal)
# Commit the job-done marker AFTER the work succeeds.
job_file.write_text(json.dumps({"output_path": output}))
@@ -78,15 +76,6 @@ async def transcode_video(tool_call_id, params: TranscodeParams, *, signal=None,
content=[TextContent(text=f"Transcoded to {output}.")],
details={"output_path": output},
)
-
-
-transcode_tool = AgentTool(
- name="transcode_video",
- description="Transcode a video file. Idempotent — safe to retry.",
- parameters=TranscodeParams,
- execute=transcode_video,
- execution_mode="sequential", # one transcode at a time
-)
```
Now if the process dies during `run_ffmpeg`, the next agent run sees
@@ -106,7 +95,7 @@ from cubepi import Agent
from cubepi.checkpointer import SQLiteCheckpointer
from cubepi.providers.anthropic import AnthropicProvider
-from tools import transcode_tool # the wrapped AgentTool from above
+from tools import transcode_video # the @tool-decorated AgentTool from above
async def main(thread_id: str, initial_prompt: str | None):
@@ -114,7 +103,7 @@ async def main(thread_id: str, initial_prompt: str | None):
agent = Agent(
model=AnthropicProvider(provider_id="anthropic", api_key=os.environ["ANTHROPIC_API_KEY"]).model("claude-sonnet-4-5-20250929"),
system_prompt="You orchestrate video transcoding jobs.",
- tools=[transcode_tool],
+ tools=[transcode_video],
checkpointer=cp,
thread_id=thread_id,
)
diff --git a/website/docs/recipes/weather-agent.md b/website/docs/recipes/weather-agent.md
index a018e98..46e0344 100644
--- a/website/docs/recipes/weather-agent.md
+++ b/website/docs/recipes/weather-agent.md
@@ -19,32 +19,34 @@ import asyncio
import os
import httpx
-from pydantic import BaseModel, Field
+from typing import Annotated
+from pydantic import Field
-from cubepi import Agent, AgentTool, AgentToolResult, TextContent
+from cubepi import Agent, AgentToolResult, TextContent, tool
from cubepi.providers.anthropic import AnthropicProvider
# --- The tool -----------------------------------------------------------
-class GetWeatherParams(BaseModel):
- city: str = Field(..., description="The city to look up weather for")
- units: str = Field("metric", pattern="^(metric|imperial)$")
-
-
-async def get_weather(tool_call_id, params: GetWeatherParams, *, signal=None, on_update=None):
+@tool
+async def get_weather(
+ city: Annotated[str, Field(description="The city to look up weather for")],
+ units: Annotated[str, Field(pattern="^(metric|imperial)$")] = "metric",
+) -> str | AgentToolResult:
+ "Get current weather for a city. Returns a short text summary."
# Free Open-Meteo geocoding + forecast. No API key required.
async with httpx.AsyncClient(timeout=10) as client:
try:
geo = await client.get(
"https://geocoding-api.open-meteo.com/v1/search",
- params={"name": params.city, "count": 1, "language": "en"},
+ params={"name": city, "count": 1, "language": "en"},
)
geo.raise_for_status()
results = geo.json().get("results")
if not results:
+ # Returning is_error=True tells the model the call failed.
return AgentToolResult(
- content=[TextContent(text=f"Couldn't find a city named {params.city!r}.")],
+ content=[TextContent(text=f"Couldn't find a city named {city!r}.")],
is_error=True,
)
lat, lon = results[0]["latitude"], results[0]["longitude"]
@@ -55,15 +57,14 @@ async def get_weather(tool_call_id, params: GetWeatherParams, *, signal=None, on
"latitude": lat,
"longitude": lon,
"current_weather": True,
- "temperature_unit": "celsius" if params.units == "metric" else "fahrenheit",
+ "temperature_unit": "celsius" if units == "metric" else "fahrenheit",
},
)
wx.raise_for_status()
cw = wx.json()["current_weather"]
- unit = "°C" if params.units == "metric" else "°F"
- return AgentToolResult(
- content=[TextContent(text=f"{cw['temperature']}{unit}, wind {cw['windspeed']} km/h in {params.city}.")],
- )
+ unit = "°C" if units == "metric" else "°F"
+ # A plain str is wrapped as a successful text result.
+ return f"{cw['temperature']}{unit}, wind {cw['windspeed']} km/h in {city}."
except httpx.HTTPError as e:
return AgentToolResult(
content=[TextContent(text=f"Weather API error: {e}")],
@@ -71,14 +72,6 @@ async def get_weather(tool_call_id, params: GetWeatherParams, *, signal=None, on
)
-weather_tool = AgentTool(
- name="get_weather",
- description="Get current weather for a city. Returns a short text summary.",
- parameters=GetWeatherParams,
- execute=get_weather,
-)
-
-
# --- The agent ----------------------------------------------------------
async def main():
@@ -86,7 +79,7 @@ async def main():
agent = Agent(
model=provider.model("claude-sonnet-4-5-20250929"),
system_prompt="You are a concise weather assistant. Always use the tool; don't guess.",
- tools=[weather_tool],
+ tools=[get_weather],
)
def on_event(event, signal=None):
diff --git a/website/docusaurus.config.ts b/website/docusaurus.config.ts
index c179b36..8408a93 100644
--- a/website/docusaurus.config.ts
+++ b/website/docusaurus.config.ts
@@ -107,11 +107,13 @@ const config: Config = {
clientModules: [require.resolve('./src/clientModules/posthog.ts')],
markdown: {
- // Strip empty ## [Unreleased] sections before MDX compilation so the
- // /changelog page doesn't open with a heading that has no content and
- // makes the first release look unreleased.
+ // Strip the ## [Unreleased] heading only when the section is empty — i.e.
+ // immediately followed by the next release heading (`## [x.y.z]`). The
+ // lookahead requires "## " with a trailing space so a populated section
+ // whose first child is a "### Added" subsection is NOT stripped (### also
+ // starts with ##), which would otherwise drop the heading but keep its body.
preprocessor: ({fileContent}) =>
- fileContent.replace(/^## \[Unreleased\]\n+(?=##)/m, ''),
+ fileContent.replace(/^## \[Unreleased\]\n+(?=## )/m, ''),
},
presets: [['classic', classicOptions]],
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/core-concepts.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/core-concepts.md
index f278146..3906943 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/core-concepts.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/core-concepts.md
@@ -32,31 +32,24 @@ Subscriber 会收到循环发出的每一个 `AgentEvent`。可以是同步或
## Tool
-`AgentTool` = name + description + Pydantic 参数模型 + 异步 `execute`:
+工具就是一个模型可以调用的 async 函数。用 `@tool` 装饰它,CubePi 会从
+参数生成输入 schema:
```python
-from pydantic import BaseModel
-from cubepi import AgentTool, AgentToolResult, TextContent
-
-class SearchParams(BaseModel):
- query: str
- limit: int = 10
-
-async def execute(tool_call_id, params: SearchParams, *, signal=None, on_update=None):
- # 干活;如果可以被打断,记得检查 signal
- return AgentToolResult(content=[TextContent(text=f"…")])
-
-search = AgentTool(
- name="search",
- description="搜索语料库",
- parameters=SearchParams,
- execute=execute,
-)
+from cubepi import tool
+
+@tool
+async def search(query: str, limit: int = 10) -> str:
+ "搜索语料库"
+ # 干活;需要的话在签名里声明 signal / on_update
+ return "…"
```
-Pydantic schema 会自动转成 JSON Schema 喂给模型。参数解析、错误包装、
-并行执行都由框架处理。`execution_mode`、`on_update`(增量进度)、
-`terminate`(在工具里结束本轮)见 [工具使用](../guides/agents/tool-use)。
+`@tool` 会构建一个 `AgentTool`(name + description + Pydantic 参数模型 +
+异步 `execute`);schema 自动转成 JSON Schema 喂给模型。参数解析、错误
+包装、并行执行都由框架处理。长写法 `AgentTool(...)`、`execution_mode`、
+`on_update`(增量进度)、`terminate`(在工具里结束本轮)见
+[工具使用](../guides/agents/tool-use)。
## Provider
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/quick-start.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/quick-start.md
index 2e80441..5be9d05 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/quick-start.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/quick-start.md
@@ -22,21 +22,16 @@ description: "在几分钟内构建你的第一个 CubePi agent。"
```python title="weather_agent.py"
import asyncio
import os
-from pydantic import BaseModel
-from cubepi import Agent, AgentTool, AgentToolResult, TextContent
+from cubepi import Agent, tool
from cubepi.providers.anthropic import AnthropicProvider
-class GetWeatherParams(BaseModel):
- city: str
-
-
-async def get_weather(tool_call_id, params: GetWeatherParams, *, signal=None, on_update=None):
+@tool
+async def get_weather(city: str) -> str:
+ "获取一个城市的当前天气"
# 真实应用里:调一个 HTTP 天气 API。这里直接返回一段假数据。
- return AgentToolResult(
- content=[TextContent(text=f"{params.city} 现在 72°F,晴")]
- )
+ return f"{city} 现在 72°F,晴"
async def main():
@@ -45,14 +40,7 @@ async def main():
agent = Agent(
model=provider.model("claude-sonnet-4-5-20250929"),
system_prompt="你是一个简洁的天气助手。",
- tools=[
- AgentTool(
- name="get_weather",
- description="获取一个城市的当前天气",
- parameters=GetWeatherParams,
- execute=get_weather,
- ),
- ],
+ tools=[get_weather],
)
# 在 prompt() 之前订阅 —— 这是看到流式事件的关键。
@@ -84,8 +72,8 @@ CubePi 跑了一个概念上长这样的循环:
1. `agent.prompt("东京现在天气怎么样?")` 把一条 `UserMessage` 入队,
然后调用模型。
-2. 模型决定调用 `get_weather(city="Tokyo")`——CubePi 用你的 Pydantic
- 模型解析 JSON 参数,调用你的 `async def`,把结果作为
+2. 模型决定调用 `get_weather(city="Tokyo")`——CubePi 按 `@tool` 从函数
+ 签名生成的 schema 解析 JSON 参数,调用你的 `async def`,把结果作为
`ToolResultMessage` 反馈回去。
3. 模型产生最终的 assistant 回复,以 `text_delta` 事件流的形式回来。
4. 循环发出 `agent_end` 然后返回。
@@ -101,9 +89,11 @@ CubePi 跑了一个概念上长这样的循环:
- **必须在 prompt 之前订阅。** Listener 只会收到 `subscribe` 之后发出
的事件。先 prompt 再 subscribe,早期事件就丢了。
- **`provider.model(...)` 会把模型绑定到 provider。** provider 保存凭证和可选的 `provider_id` 元数据;模型 id 必须是这个 provider 支持的模型名。
-- **`execute` 签名是固定的。** 哪怕你不用 keyword-only 参数,签名也得
- 保留 `(tool_call_id, params, *, signal, on_update)`。CubePi 总是
- 会传它们。
+- **工具就是被装饰的 async 函数。** `@tool` 从带类型的参数推断输入
+ schema,用 docstring 作为描述;返回 `str`(或 `AgentToolResult`)。
+ 需要原始的 `(tool_call_id, params, *, signal, on_update)` 写法、共享
+ 参数模型,或 `on_update` 进度?见
+ [工具使用](../guides/agents/tool-use)。
- **`agent.prompt()` 一次只能跑一个 prompt。** 跑的过程中,用
[`agent.steer()`](../guides/agents/multi-turn) 插入修正,或
`agent.follow_up()` 把后续消息排队。
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/first-agent.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/first-agent.md
index c264644..bb0dace 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/first-agent.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/first-agent.md
@@ -33,41 +33,30 @@ model = provider.model(
## 第 2 步 —— 声明一个工具
-每个工具 = Pydantic 参数模型 + 一个异步 `execute` 函数:
+工具就是一个用 `@tool` 装饰的 async 函数:
```python
-from pydantic import BaseModel
-from cubepi import AgentTool, AgentToolResult, TextContent
+from cubepi import tool
-class GetWeatherParams(BaseModel):
- city: str
-
-
-async def get_weather(tool_call_id, params: GetWeatherParams, *, signal=None, on_update=None):
+@tool
+async def get_weather(city: str) -> str:
+ "获取一个城市的当前天气,返回简短文字。"
# 真实工作放在这里 —— 调 HTTP API、查 DB 等。
- return AgentToolResult(
- content=[TextContent(text=f"{params.city} 现在 72°F,晴")]
- )
-
-
-weather_tool = AgentTool(
- name="get_weather",
- description="获取一个城市的当前天气,返回简短文字。",
- parameters=GetWeatherParams,
- execute=get_weather,
-)
+ return f"{city} 现在 72°F,晴"
```
注意几点:
-- Pydantic 模型自动转成 JSON Schema,作为工具定义发给模型。
-- `execute` 签名是固定的:`(tool_call_id, params, *, signal, on_update)`。
- 最后两个 keyword-only 参数一定会被传入 —— 哪怕你不用,也得在签名里。
-- `signal` 是用户取消时会被 set 的 `asyncio.Event`。在长时间运行的
- 代码里检查它,及时退出。
-- `on_update(partial)` 让你流式回报进度(见
- [工具使用](./tool-use))。
+- 输入 schema 从带类型的参数生成并发给模型;docstring 作为工具描述。
+ Pydantic `Field(...)` 的默认值与元数据都会被保留。
+- 返回 `str`(自动包成文本)、`Content`、内容列表,或在需要
+ `details`/`is_error` 时返回完整的 `AgentToolResult`。
+- 需要取消或进度流?在签名里声明 `signal`(用户取消时被 set 的
+ `asyncio.Event`)和/或 `on_update(partial)`,CubePi 会注入它们 —— 见
+ [工具使用](./tool-use)。
+- 需要共享参数模型或动态构建?长写法 `AgentTool(...)` 与之等价 —— 见
+ [工具使用](./tool-use)。
## 第 3 步 —— 组装 Agent
@@ -77,7 +66,7 @@ from cubepi import Agent
agent = Agent(
model=model,
system_prompt="你是一个简洁的天气助手。",
- tools=[weather_tool],
+ tools=[get_weather],
)
```
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/resumable-tasks.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/resumable-tasks.md
index 1fe8cfc..f6b398b 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/resumable-tasks.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/resumable-tasks.md
@@ -37,8 +37,7 @@ import os
import json
from pathlib import Path
-from pydantic import BaseModel
-from cubepi import AgentTool, AgentToolResult, TextContent
+from cubepi import AgentToolResult, TextContent, tool
# 简单的文件支撑 job store;生产中替换为 Redis / Postgres。
@@ -46,13 +45,12 @@ JOB_DIR = Path(os.environ.get("JOB_DIR", "/tmp/cubepi-jobs"))
JOB_DIR.mkdir(parents=True, exist_ok=True)
-class TranscodeParams(BaseModel):
- source_path: str
- output_path: str
-
-
-async def transcode_video(tool_call_id, params: TranscodeParams, *, signal=None, on_update=None):
- job_key = f"transcode:{params.source_path}->{params.output_path}"
+# execution_mode="sequential" → 一次只转码一个。只声明了 `signal`,
+# 所以只有它这一个由循环提供的参数会被注入。
+@tool(execution_mode="sequential")
+async def transcode_video(source_path: str, output_path: str, *, signal=None) -> AgentToolResult:
+ "Transcode a video file. Idempotent — safe to retry."
+ job_key = f"transcode:{source_path}->{output_path}"
job_file = JOB_DIR / f"{job_key.replace('/', '_')}.json"
if job_file.exists():
@@ -65,7 +63,7 @@ async def transcode_video(tool_call_id, params: TranscodeParams, *, signal=None,
# 执行实际工作(长时间运行,代价高昂)。
# 使用 signal 在取消时干净地中止。
- output = await run_ffmpeg(params.source_path, params.output_path, signal=signal)
+ output = await run_ffmpeg(source_path, output_path, signal=signal)
# 在工作成功后再写入 job 完成标记。
job_file.write_text(json.dumps({"output_path": output}))
@@ -74,15 +72,6 @@ async def transcode_video(tool_call_id, params: TranscodeParams, *, signal=None,
content=[TextContent(text=f"Transcoded to {output}.")],
details={"output_path": output},
)
-
-
-transcode_tool = AgentTool(
- name="transcode_video",
- description="Transcode a video file. Idempotent — safe to retry.",
- parameters=TranscodeParams,
- execute=transcode_video,
- execution_mode="sequential", # 一次只转码一个
-)
```
现在,如果进程在 `run_ffmpeg` 执行期间崩溃,下次 agent 运行时会发现
@@ -101,7 +90,7 @@ from cubepi import Agent
from cubepi.checkpointer import SQLiteCheckpointer
from cubepi.providers.anthropic import AnthropicProvider
-from tools import transcode_tool # 上面封装好的 AgentTool
+from tools import transcode_video # 上面用 @tool 装饰的 AgentTool
async def main(thread_id: str, initial_prompt: str | None):
@@ -109,7 +98,7 @@ async def main(thread_id: str, initial_prompt: str | None):
agent = Agent(
model=AnthropicProvider(provider_id="anthropic", api_key=os.environ["ANTHROPIC_API_KEY"]).model("claude-sonnet-4-5-20250929"),
system_prompt="You orchestrate video transcoding jobs.",
- tools=[transcode_tool],
+ tools=[transcode_video],
checkpointer=cp,
thread_id=thread_id,
)
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/weather-agent.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/weather-agent.md
index a33d79c..e529511 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/weather-agent.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/weather-agent.md
@@ -18,32 +18,34 @@ import asyncio
import os
import httpx
-from pydantic import BaseModel, Field
+from typing import Annotated
+from pydantic import Field
-from cubepi import Agent, AgentTool, AgentToolResult, TextContent
+from cubepi import Agent, AgentToolResult, TextContent, tool
from cubepi.providers.anthropic import AnthropicProvider
# --- 工具 -----------------------------------------------------------------
-class GetWeatherParams(BaseModel):
- city: str = Field(..., description="The city to look up weather for")
- units: str = Field("metric", pattern="^(metric|imperial)$")
-
-
-async def get_weather(tool_call_id, params: GetWeatherParams, *, signal=None, on_update=None):
+@tool
+async def get_weather(
+ city: Annotated[str, Field(description="The city to look up weather for")],
+ units: Annotated[str, Field(pattern="^(metric|imperial)$")] = "metric",
+) -> str | AgentToolResult:
+ "Get current weather for a city. Returns a short text summary."
# 免费的 Open-Meteo 地理编码 + 预报。无需 API key。
async with httpx.AsyncClient(timeout=10) as client:
try:
geo = await client.get(
"https://geocoding-api.open-meteo.com/v1/search",
- params={"name": params.city, "count": 1, "language": "en"},
+ params={"name": city, "count": 1, "language": "en"},
)
geo.raise_for_status()
results = geo.json().get("results")
if not results:
+ # 返回 is_error=True 告诉模型这次调用失败了。
return AgentToolResult(
- content=[TextContent(text=f"Couldn't find a city named {params.city!r}.")],
+ content=[TextContent(text=f"Couldn't find a city named {city!r}.")],
is_error=True,
)
lat, lon = results[0]["latitude"], results[0]["longitude"]
@@ -54,15 +56,14 @@ async def get_weather(tool_call_id, params: GetWeatherParams, *, signal=None, on
"latitude": lat,
"longitude": lon,
"current_weather": True,
- "temperature_unit": "celsius" if params.units == "metric" else "fahrenheit",
+ "temperature_unit": "celsius" if units == "metric" else "fahrenheit",
},
)
wx.raise_for_status()
cw = wx.json()["current_weather"]
- unit = "°C" if params.units == "metric" else "°F"
- return AgentToolResult(
- content=[TextContent(text=f"{cw['temperature']}{unit}, wind {cw['windspeed']} km/h in {params.city}.")],
- )
+ unit = "°C" if units == "metric" else "°F"
+ # 普通 str 会被包装成一次成功的文本结果。
+ return f"{cw['temperature']}{unit}, wind {cw['windspeed']} km/h in {city}."
except httpx.HTTPError as e:
return AgentToolResult(
content=[TextContent(text=f"Weather API error: {e}")],
@@ -70,14 +71,6 @@ async def get_weather(tool_call_id, params: GetWeatherParams, *, signal=None, on
)
-weather_tool = AgentTool(
- name="get_weather",
- description="Get current weather for a city. Returns a short text summary.",
- parameters=GetWeatherParams,
- execute=get_weather,
-)
-
-
# --- Agent ----------------------------------------------------------------
async def main():
@@ -85,7 +78,7 @@ async def main():
agent = Agent(
model=provider.model("claude-sonnet-4-5-20250929"),
system_prompt="You are a concise weather assistant. Always use the tool; don't guess.",
- tools=[weather_tool],
+ tools=[get_weather],
)
def on_event(event, signal=None):
diff --git a/website/src/components/Home/HelloAgent.tsx b/website/src/components/Home/HelloAgent.tsx
index 6a25a2d..5e53fa9 100644
--- a/website/src/components/Home/HelloAgent.tsx
+++ b/website/src/components/Home/HelloAgent.tsx
@@ -5,31 +5,20 @@ import { useIsZhHans } from '@site/src/hooks/useIsZhHans';
import styles from './HelloAgent.module.css';
const SAMPLE = `import asyncio
-from pydantic import BaseModel
-from cubepi import Agent, AgentTool, Model
-from cubepi.agent.types import AgentToolResult
+from cubepi import Agent, Model, tool
from cubepi.providers.anthropic import AnthropicProvider
-from cubepi.providers.base import TextContent
provider = AnthropicProvider(api_key="sk-...")
-class GetWeatherParams(BaseModel):
- city: str
-
-async def get_weather(tool_call_id, params: GetWeatherParams, *, signal=None, on_update=None):
- return AgentToolResult(
- content=[TextContent(text=f"72°F and sunny in {params.city}")]
- )
+@tool
+async def get_weather(city: str) -> str:
+ "Get current weather for a city."
+ return f"72°F and sunny in {city}"
agent = Agent(
provider=provider,
model=Model(id="claude-sonnet-4-5-20250929", provider="anthropic"),
- tools=[AgentTool(
- name="get_weather",
- description="Get current weather for a city",
- parameters=GetWeatherParams,
- execute=get_weather,
- )],
+ tools=[get_weather],
system_prompt="You are a helpful weather assistant.",
)