Skip to content

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

feat(agent): add @tool decorator for ergonomic tool definition

Claude5458fa353d6c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 13bdcb5..4a0cc9d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+
+- **`@tool` decorator** — `cubepi.tool` builds an `AgentTool` from a plain
+ async function: the input schema is generated from the typed parameters
+ (honouring `Field(...)` metadata), the docstring becomes the description,
+ and the loop-supplied `tool_call_id` / `signal` / `on_update` are injected
+ only when declared. Tools may return a `str`, a `Content`, a `list` of
+ content, or a full `AgentToolResult`. The longhand `AgentTool(...)` remains
+ fully supported.
+
## [0.7.0] - 2026-06-05
### Added
diff --git a/README.md b/README.md
index 1f4b57d..9ceaa19 100644
--- a/README.md
+++ b/README.md
@@ -52,32 +52,19 @@ uv add cubepi[sqlite,postgres,mysql,mcp,tracing]
```python
import asyncio
-from pydantic import BaseModel
-from cubepi import Agent, AgentTool, Model
-from cubepi.agent.types import AgentToolResult
+from cubepi import Agent, tool
from cubepi.providers.anthropic import AnthropicProvider
-from cubepi.providers.base import TextContent
provider = AnthropicProvider(provider_id="anthropic", 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(
model=provider.model("claude-sonnet-4-5-20250929"),
- 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.",
)
@@ -115,7 +102,21 @@ faux.set_responses(["Hello!", "How can I help?"])
### Tools
-Declare tools with a name, a Pydantic model for parameters, and an async `execute` returning `AgentToolResult`. The framework handles JSON Schema derivation, argument parsing, parallel execution, and error wrapping.
+Decorate an async function with `@tool`: the input schema is derived from the
+typed parameters, the docstring becomes the description, and the framework
+handles argument parsing, parallel execution, and error wrapping.
+
+```python
+from cubepi import tool
+
+@tool
+async def search(query: str) -> str:
+ "Search the web."
+ return f"Results for: {query}"
+```
+
+Need a shared params model, dynamic construction, or `execution_mode`? The
+longhand `AgentTool(...)` is equivalent and fully supported:
```python
from pydantic import BaseModel
@@ -129,7 +130,7 @@ class SearchParams(BaseModel):
async def execute(tool_call_id, params: SearchParams, *, signal=None, on_update=None):
return AgentToolResult(content=[TextContent(text=f"Results for: {params.query}")])
-tool = AgentTool(
+search = AgentTool(
name="search",
description="Search the web",
parameters=SearchParams,
diff --git a/cubepi/__init__.py b/cubepi/__init__.py
index f22708f..c97539b 100644
--- a/cubepi/__init__.py
+++ b/cubepi/__init__.py
@@ -15,6 +15,7 @@ from cubepi.agent import (
AgentToolResult,
run_agent_loop,
run_agent_loop_continue,
+ tool,
)
from cubepi.middleware import Middleware, compose_middleware
from cubepi.providers import (
@@ -113,4 +114,5 @@ __all__ = [
"compose_middleware",
"run_agent_loop",
"run_agent_loop_continue",
+ "tool",
]
diff --git a/cubepi/agent/__init__.py b/cubepi/agent/__init__.py
index 3c4f0e7..34a0bb5 100644
--- a/cubepi/agent/__init__.py
+++ b/cubepi/agent/__init__.py
@@ -1,5 +1,6 @@
from cubepi.agent.agent import Agent, AgentState
from cubepi.agent.loop import run_agent_loop, run_agent_loop_continue
+from cubepi.agent.tool_decorator import tool
from cubepi.agent.tools import execute_tool_calls
from cubepi.agent.types import (
AfterToolCallContext,
@@ -52,4 +53,5 @@ __all__ = [
"TurnEndEvent",
"TurnStartEvent",
"emit_event",
+ "tool",
]
diff --git a/cubepi/agent/tool_decorator.py b/cubepi/agent/tool_decorator.py
new file mode 100644
index 0000000..3acbbac
--- /dev/null
+++ b/cubepi/agent/tool_decorator.py
@@ -0,0 +1,185 @@
+"""The ``@tool`` decorator — build an :class:`AgentTool` from a plain function.
+
+Declaring a tool by hand means writing a Pydantic params model, an ``execute``
+callable with the engine's exact ``(tool_call_id, params, *, signal, on_update)``
+signature, and an ``AgentTool(...)`` wrapper. ``@tool`` collapses all three: the
+input schema is generated from the function signature, the engine-supplied
+arguments are injected only if the function asks for them, and the return value
+is normalised so a tool can simply ``return "some text"``.
+
+```python
+from cubepi import tool
+
+
+@tool
+async def get_weather(city: str) -> str:
+ "Get the current weather for a city."
+ return f"72F and sunny in {city}"
+```
+
+is equivalent to the longhand ``AgentTool(name=..., parameters=..., execute=...)``.
+"""
+
+from __future__ import annotations
+
+import inspect
+from typing import (
+ Any,
+ Awaitable,
+ Callable,
+ Literal,
+ get_type_hints,
+ overload,
+)
+
+from pydantic import BaseModel, create_model
+
+from cubepi.agent.types import AgentTool, AgentToolResult
+from cubepi.providers.base import Content, TextContent
+
+# Arguments the agent loop supplies when it calls a tool (see
+# cubepi/agent/tools.py). They are injected into the decorated function only if
+# it declares a parameter by that name, and never appear in the input schema.
+_RESERVED = ("tool_call_id", "signal", "on_update")
+
+ToolFunc = Callable[..., Awaitable[Any]]
+
+
+def _build_params_model(
+ fn: Callable[..., Any],
+ schema_params: list[inspect.Parameter],
+ hints: dict[str, Any],
+) -> type[BaseModel]:
+ """Generate a Pydantic model from the tool function's schema parameters."""
+ fields: dict[str, Any] = {}
+ for p in schema_params:
+ if p.kind in (
+ inspect.Parameter.VAR_POSITIONAL,
+ inspect.Parameter.VAR_KEYWORD,
+ ):
+ raise TypeError(
+ f"@tool function {fn.__name__!r} cannot use *args/**kwargs; "
+ "declare explicit parameters so an input schema can be generated."
+ )
+ if p.name not in hints and p.annotation is inspect.Parameter.empty:
+ raise TypeError(
+ f"@tool parameter {p.name!r} of {fn.__name__!r} needs a type "
+ "annotation to generate its schema."
+ )
+ annotation = hints.get(p.name, p.annotation)
+ default = ... if p.default is inspect.Parameter.empty else p.default
+ fields[p.name] = (annotation, default)
+
+ model_name = "".join(part.capitalize() for part in fn.__name__.split("_")) + "Args"
+ return create_model(model_name, **fields)
+
+
+def _normalize_result(result: Any, fn: Callable[..., Any]) -> AgentToolResult:
+ """Accept the ergonomic return shapes and coerce to an AgentToolResult."""
+ if isinstance(result, AgentToolResult):
+ return result
+ if isinstance(result, str):
+ return AgentToolResult(content=[TextContent(text=result)])
+ if isinstance(result, Content):
+ return AgentToolResult(content=[result])
+ if isinstance(result, list):
+ return AgentToolResult(content=result)
+ raise TypeError(
+ f"@tool function {fn.__name__!r} returned {type(result).__name__}; "
+ "return an AgentToolResult, a str, a Content, or a list of Content."
+ )
+
+
+def _make_agent_tool(
+ fn: ToolFunc,
+ *,
+ name: str | None,
+ description: str | None,
+ execution_mode: Literal["sequential", "parallel"] | None,
+) -> AgentTool[Any]:
+ if not inspect.iscoroutinefunction(fn):
+ raise TypeError(
+ f"@tool requires an async function; {fn.__name__!r} is not declared "
+ "with 'async def'. Wrap blocking work with asyncio.to_thread()."
+ )
+
+ sig = inspect.signature(fn)
+ try:
+ hints = get_type_hints(fn, include_extras=True)
+ except Exception as exc: # pragma: no cover — unresolved annotations
+ raise TypeError(
+ f"@tool could not resolve type hints for {fn.__name__!r}: {exc}"
+ ) from exc
+
+ schema_params = [p for n, p in sig.parameters.items() if n not in _RESERVED]
+ injected = [n for n in _RESERVED if n in sig.parameters]
+ params_model = _build_params_model(fn, schema_params, hints)
+ field_names = list(params_model.model_fields.keys())
+
+ tool_name = name or fn.__name__
+ tool_desc = description if description is not None else (inspect.getdoc(fn) or "")
+
+ async def execute(
+ tool_call_id: str,
+ params: BaseModel,
+ *,
+ signal: Any = None,
+ on_update: Any = None,
+ ) -> AgentToolResult:
+ kwargs: dict[str, Any] = {n: getattr(params, n) for n in field_names}
+ if "tool_call_id" in injected:
+ kwargs["tool_call_id"] = tool_call_id
+ if "signal" in injected:
+ kwargs["signal"] = signal
+ if "on_update" in injected:
+ kwargs["on_update"] = on_update
+ return _normalize_result(await fn(**kwargs), fn)
+
+ return AgentTool(
+ name=tool_name,
+ description=tool_desc,
+ parameters=params_model,
+ execute=execute,
+ execution_mode=execution_mode,
+ )
+
+
+@overload
+def tool(fn: ToolFunc) -> AgentTool[Any]: ...
+
+
+@overload
+def tool(
+ *,
+ name: str | None = ...,
+ description: str | None = ...,
+ execution_mode: Literal["sequential", "parallel"] | None = ...,
+) -> Callable[[ToolFunc], AgentTool[Any]]: ...
+
+
+def tool(
+ fn: ToolFunc | None = None,
+ *,
+ name: str | None = None,
+ description: str | None = None,
+ execution_mode: Literal["sequential", "parallel"] | None = None,
+) -> AgentTool[Any] | Callable[[ToolFunc], AgentTool[Any]]:
+ """Turn an async function into an :class:`AgentTool`.
+
+ Usable bare (``@tool``) or with arguments (``@tool(name=..., ...)``).
+
+ - The tool's input schema is generated from the function's parameters; each
+ needs a type annotation. ``Field(...)`` defaults/metadata are honoured.
+ - If the function declares ``tool_call_id``, ``signal``, or ``on_update``,
+ the loop's values are passed through; otherwise they are omitted from the
+ schema and not passed.
+ - The return value may be an ``AgentToolResult``, a ``str``, a ``Content``,
+ or a ``list[Content]``.
+ """
+
+ def decorator(f: ToolFunc) -> AgentTool[Any]:
+ return _make_agent_tool(
+ f, name=name, description=description, execution_mode=execution_mode
+ )
+
+ return decorator(fn) if fn is not None else decorator
diff --git a/tests/agent/test_tool_decorator.py b/tests/agent/test_tool_decorator.py
new file mode 100644
index 0000000..c694600
--- /dev/null
+++ b/tests/agent/test_tool_decorator.py
@@ -0,0 +1,185 @@
+import asyncio
+
+import pytest
+from pydantic import Field
+
+from cubepi import AgentTool, AgentToolResult, TextContent, tool
+from cubepi.agent.tools import execute_tool_calls
+from cubepi.agent.types import AgentContext
+from cubepi.providers.base import AssistantMessage, ToolCall
+
+
+def _ctx(tools: list[AgentTool]) -> AgentContext:
+ return AgentContext(system_prompt="", messages=[], tools=tools)
+
+
+def _assistant(tool_calls: list[ToolCall]) -> AssistantMessage:
+ return AssistantMessage(content=tool_calls, stop_reason="tool_use")
+
+
+class TestBuild:
+ def test_bare_decorator_builds_agent_tool(self):
+ @tool
+ async def get_weather(city: str) -> str:
+ "Get the current weather for a city."
+ return f"sunny in {city}"
+
+ assert isinstance(get_weather, AgentTool)
+ assert get_weather.name == "get_weather"
+ assert get_weather.description == "Get the current weather for a city."
+
+ def test_schema_generated_from_signature(self):
+ @tool
+ async def search(query: str, limit: int = 10) -> str:
+ "Search."
+ return query
+
+ schema = search.to_definition().parameters
+ assert schema["properties"]["query"]["type"] == "string"
+ assert schema["properties"]["limit"]["type"] == "integer"
+ assert schema["properties"]["limit"]["default"] == 10
+ # query is required, limit (with a default) is not
+ assert schema["required"] == ["query"]
+
+ def test_field_metadata_is_honoured(self):
+ @tool
+ async def search(query: str = Field(..., description="the query")) -> str:
+ "Search."
+ return query
+
+ schema = search.to_definition().parameters
+ assert schema["properties"]["query"]["description"] == "the query"
+
+ def test_options_form(self):
+ @tool(name="weather", description="override", execution_mode="sequential")
+ async def get_weather(city: str) -> str:
+ "docstring ignored when description given"
+ return city
+
+ assert get_weather.name == "weather"
+ assert get_weather.description == "override"
+ assert get_weather.execution_mode == "sequential"
+
+ def test_no_params_tool(self):
+ @tool
+ async def ping() -> str:
+ "Ping."
+ return "pong"
+
+ schema = ping.to_definition().parameters
+ assert schema.get("properties", {}) == {}
+
+
+class TestExecute:
+ async def _run(self, t: AgentTool, **kwargs) -> AgentToolResult:
+ params = t.parameters(**kwargs)
+ return await t.execute("call-1", params, signal=None, on_update=None)
+
+ async def test_str_return_is_wrapped(self):
+ @tool
+ async def echo(value: str) -> str:
+ "Echo."
+ return f"got {value}"
+
+ result = await self._run(echo, value="hi")
+ assert isinstance(result, AgentToolResult)
+ assert result.content[0].text == "got hi"
+
+ async def test_agent_tool_result_passthrough(self):
+ @tool
+ async def echo(value: str) -> AgentToolResult:
+ "Echo."
+ return AgentToolResult(content=[TextContent(text=value)], details={"k": 1})
+
+ result = await self._run(echo, value="hi")
+ assert result.details == {"k": 1}
+
+ async def test_content_and_list_returns(self):
+ @tool
+ async def one(value: str) -> TextContent:
+ "One."
+ return TextContent(text=value)
+
+ @tool
+ async def many(value: str) -> list:
+ "Many."
+ return [TextContent(text=value), TextContent(text=value)]
+
+ assert (await self._run(one, value="x")).content[0].text == "x"
+ assert len((await self._run(many, value="x")).content) == 2
+
+ async def test_injected_params_excluded_from_schema_but_passed(self):
+ seen = {}
+
+ @tool
+ async def t(value: str, *, tool_call_id, signal=None, on_update=None) -> str:
+ "Tool that uses injected args."
+ seen["tool_call_id"] = tool_call_id
+ seen["signal"] = signal
+ seen["on_update"] = on_update
+ return value
+
+ # reserved names are not in the input schema
+ props = t.to_definition().parameters["properties"]
+ assert set(props) == {"value"}
+
+ sig = asyncio.Event()
+ cb = lambda _p: None # noqa: E731
+ params = t.parameters(value="hi")
+ await t.execute("call-9", params, signal=sig, on_update=cb)
+ assert seen == {"tool_call_id": "call-9", "signal": sig, "on_update": cb}
+
+
+class TestErrors:
+ def test_sync_function_rejected(self):
+ with pytest.raises(TypeError, match="async function"):
+
+ @tool
+ def not_async(x: str) -> str: # type: ignore[misc]
+ return x
+
+ def test_missing_annotation_rejected(self):
+ with pytest.raises(TypeError, match="needs a type"):
+
+ @tool
+ async def bad(x) -> str: # type: ignore[no-untyped-def]
+ return x
+
+ def test_var_args_rejected(self):
+ with pytest.raises(TypeError, match="cannot use"):
+
+ @tool
+ async def bad(*args: str) -> str:
+ return ""
+
+ async def test_bad_return_type_rejected(self):
+ @tool
+ async def bad(value: str) -> int: # type: ignore[return-value]
+ "Bad."
+ return 123 # type: ignore[return-value]
+
+ params = bad.parameters(value="x")
+ with pytest.raises(TypeError, match="returned int"):
+ await bad.execute("c", params, signal=None, on_update=None)
+
+
+class TestEngineIntegration:
+ async def test_decorated_tool_runs_through_engine(self):
+ """The generated execute signature must match what the loop calls."""
+
+ @tool
+ async def add(a: int, b: int) -> str:
+ "Add two numbers."
+ return str(a + b)
+
+ ctx = _ctx([add])
+ msg = _assistant([ToolCall(id="t1", name="add", arguments={"a": 2, "b": 3})])
+ events: list = []
+ batch = await execute_tool_calls(
+ ctx, msg, tool_execution="sequential", emit=lambda e: events.append(e)
+ )
+
+ assert len(batch.messages) == 1
+ assert batch.messages[0].tool_call_id == "t1"
+ assert not batch.messages[0].is_error
+ assert batch.messages[0].content[0].text == "5"
diff --git a/website/docs/guides/agents/tool-use.md b/website/docs/guides/agents/tool-use.md
index 01f80c8..daeff1e 100644
--- a/website/docs/guides/agents/tool-use.md
+++ b/website/docs/guides/agents/tool-use.md
@@ -11,7 +11,70 @@ runs the work, and feeds the result back as a `ToolResultMessage`. By
default tools run in parallel when the model calls more than one in a
single turn.
-## Anatomy of a tool
+## The `@tool` decorator
+
+The quickest way to define a tool is to decorate an async function. CubePi
+generates the input schema from the parameters, so there's no separate model
+or boilerplate `execute` signature to write:
+
+```python
+from typing import Annotated
+from pydantic import Field
+from cubepi import tool
+
+
+@tool
+async def search(
+ query: Annotated[str, Field(description="The natural-language query")],
+ limit: Annotated[int, Field(ge=1, le=100)] = 10,
+) -> str:
+ "Search the internal knowledge base."
+ results = await my_search_backend(query, limit)
+ return "\n".join(results)
+```
+
+That's a complete, registrable `AgentTool`. The decorator infers:
+
+- **name** from the function name (override with `@tool(name=...)`);
+- **description** from the docstring (override with `@tool(description=...)`);
+- **the input schema** from the typed parameters — `Field(...)` defaults and
+ metadata are honoured exactly as in a hand-written model.
+
+The return value can be a plain `str` (wrapped as text, as above), a
+`TextContent`, a `list` of content, or a full `AgentToolResult` when you need
+`details`, `is_error`, or `terminate`:
+
+```python
+from cubepi import tool, AgentToolResult, TextContent
+
+
+@tool
+async def search(query: str, limit: int = 10) -> AgentToolResult:
+ "Search the internal knowledge base."
+ results = await my_search_backend(query, limit)
+ return AgentToolResult(
+ content=[TextContent(text="\n".join(results))],
+ details={"raw_results": results}, # passes through to ToolResultMessage.details
+ )
+```
+
+To run a tool sequentially, pass `@tool(execution_mode="sequential")`. If the
+function needs the loop-supplied arguments, just declare them — any of
+`tool_call_id`, `signal`, or `on_update` are injected when present and never
+appear in the schema:
+
+```python
+@tool
+async def long_job(prompt: str, *, signal=None, on_update=None) -> str:
+ "Run a long job, streaming progress."
+ ...
+```
+
+## Anatomy of a tool (longhand)
+
+The decorator is sugar over the explicit `AgentTool`. The form below is
+equivalent and remains fully supported — reach for it when you want to build
+tools dynamically or share one params model across several tools:
```python
from pydantic import BaseModel, Field
diff --git a/website/docs/migration/from-langgraph.md b/website/docs/migration/from-langgraph.md
index d97da49..4227e2b 100644
--- a/website/docs/migration/from-langgraph.md
+++ b/website/docs/migration/from-langgraph.md
@@ -72,32 +72,30 @@ for chunk in app.stream({"messages": [("user", "Weather in Tokyo?")]}):
```python
import asyncio
-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):
- 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(
model=AnthropicProvider(provider_id="anthropic", api_key="…").model("claude-sonnet-4-5-20250929"),
- tools=[AgentTool(
- name="get_weather",
- description="Get current weather for a city.",
- parameters=GetWeatherParams,
- execute=get_weather,
- )],
+ tools=[get_weather],
)
agent.subscribe(lambda e, s=None: print(e.type))
asyncio.run(agent.prompt("Weather in Tokyo?"))
```
+The `@tool` decorator mirrors langgraph's `@tool`: the input schema comes
+from the function signature, the docstring becomes the description, and a
+plain `str` return is wrapped for you. (For tools that need a shared params
+model or dynamic construction, the longhand `AgentTool(...)` is still there —
+see [Tool Use](../guides/agents/tool-use).)
+
CubePi version removes:
- The `StateGraph`, edges, nodes, `END` sentinel, conditional edges.
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/tool-use.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/tool-use.md
index ffe86eb..8741f5d 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/tool-use.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/tool-use.md
@@ -10,7 +10,66 @@ description: "注册工具、并行或顺序执行、并通过 Pydantic 校验
`ToolResultMessage` 喂回。默认情况下,只要模型在一轮里发出多个工具
调用,它们就会并行执行。
-## 工具的结构
+## `@tool` 装饰器
+
+定义工具最快的方式是给一个 async 函数加装饰器。CubePi 会从参数生成输入
+schema,不需要单独写参数模型,也不用写样板的 `execute` 签名:
+
+```python
+from typing import Annotated
+from pydantic import Field
+from cubepi import tool
+
+
+@tool
+async def search(
+ query: Annotated[str, Field(description="自然语言查询")],
+ limit: Annotated[int, Field(ge=1, le=100)] = 10,
+) -> str:
+ "在内部知识库里搜索。"
+ results = await my_search_backend(query, limit)
+ return "\n".join(results)
+```
+
+这就是一个完整、可注册的 `AgentTool`。装饰器会推断:
+
+- **name** 来自函数名(用 `@tool(name=...)` 覆盖);
+- **description** 来自 docstring(用 `@tool(description=...)` 覆盖);
+- **输入 schema** 来自带类型的参数 —— `Field(...)` 的默认值与元数据和手写
+ 模型完全一致。
+
+返回值可以是普通 `str`(如上,自动包成文本)、`TextContent`、内容列表,或
+在你需要 `details`、`is_error`、`terminate` 时返回完整的 `AgentToolResult`:
+
+```python
+from cubepi import tool, AgentToolResult, TextContent
+
+
+@tool
+async def search(query: str, limit: int = 10) -> AgentToolResult:
+ "在内部知识库里搜索。"
+ results = await my_search_backend(query, limit)
+ return AgentToolResult(
+ content=[TextContent(text="\n".join(results))],
+ details={"raw_results": results}, # 透传到 ToolResultMessage.details
+ )
+```
+
+要让工具顺序执行,传 `@tool(execution_mode="sequential")`。如果函数需要由
+循环提供的参数,直接声明即可 —— `tool_call_id`、`signal`、`on_update` 中
+任意一个声明了就会被注入,且不会出现在 schema 里:
+
+```python
+@tool
+async def long_job(prompt: str, *, signal=None, on_update=None) -> str:
+ "运行一个长任务并流式上报进度。"
+ ...
+```
+
+## 工具的结构(完整写法)
+
+装饰器只是 `AgentTool` 的语法糖。下面这种写法与之等价,且会一直支持 ——
+当你需要动态构建工具,或在多个工具间共享同一个参数模型时,用它:
```python
from pydantic import BaseModel, Field
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/migration/from-langgraph.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/migration/from-langgraph.md
index 91270e2..52bc727 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/migration/from-langgraph.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/migration/from-langgraph.md
@@ -71,32 +71,29 @@ for chunk in app.stream({"messages": [("user", "Weather in Tokyo?")]}):
```python
import asyncio
-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):
- 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(
model=AnthropicProvider(provider_id="anthropic", api_key="…").model("claude-sonnet-4-5-20250929"),
- tools=[AgentTool(
- name="get_weather",
- description="Get current weather for a city.",
- parameters=GetWeatherParams,
- execute=get_weather,
- )],
+ tools=[get_weather],
)
agent.subscribe(lambda e, s=None: print(e.type))
asyncio.run(agent.prompt("Weather in Tokyo?"))
```
+`@tool` 装饰器对标 langgraph 的 `@tool`:输入 schema 来自函数签名,
+docstring 作为描述,返回的普通 `str` 会自动包装。(若工具需要共享参数模型
+或动态构建,完整的 `AgentTool(...)` 写法依然可用 —— 见
+[工具使用](../guides/agents/tool-use)。)
+
CubePi 版本去除了:
- `StateGraph`、边、节点、`END` 哨兵、条件边。