# Agent 调用与方法

```
from openprogram import Agent

class ReviewAgent(Agent):
    tools = []
    instructions = "Preserve facts. Return concise text."

    def classify(self, review: str) -> str:
        """Classify review sentiment."""
        return self(f"Classify as positive, negative, or neutral:\n{review}")

    def summarize(self, review: str) -> str:
        """Summarize a review with its sentiment."""
        sentiment = self.classify(review)
        return self(f"Summarize this {sentiment} review in one sentence:\n{review}")

reviewer = ReviewAgent(model="configured-model")
summary = reviewer.summarize("The service was fast.")
```

`self(...)` 通过现有 Runtime 发起模型请求。docstring 描述函数；提示词承载指令和数据。

| 对象 | 行为 |
| --- | --- |
| Agent 实例 | 保存配置；独立的顶层调用之间不保留对话 |
| 同一 Agent 的嵌套调用 | 使用当前执行，没有自己的 DAG 节点 |
| 另一个 Agent | 自己的 DAG；父级保存结果和 `child_session_id` 引用 |
| DAG 内容 | 用户消息、模型请求和直接派发的工具 |
| 权限、取消、文件检查点 | 仍属于发起的执行 |
| Context | 为每次请求选择允许的历史并解析配置内容 |

## 直接调用和异步调用

```
from openprogram import agent, agent_async

answer = agent("Summarize this text", tools=[])
# In an async function:
# answer = await agent_async("Summarize this text", tools=[])
# answer = await reviewer.arun("Summarize this text")
```

`tools=[]`：没有模型工具。`tools=None`：运行时按当前授权解析可用工具。

## 方法元数据和工具

```
class TextAgent(Agent):
    tools = []
    method_options = {
        "summarize": {
            "tool": True,
            "name": "summarize_notes",
            "input": {"text": {"description": "Text to summarize"}},
            "expose": "io",
        },
    }

    def summarize(self, text: str) -> str:
        """Summarize text."""
        return self(f"Summarize:\n{text}")
```

`method_options` 声明输入表单元数据、可见性、持久步骤、授权和工具注册；字段见[函数元数据](https://fzkuji.github.io/OpenProgram/docs/capabilities/agentic-programming/writing-functions/function-metadata.zh.html)。只有 `tool=True` 才会注册为工具，被记录不算。名称和签名提供 schema。可见性控制历史渲染，不授予权限。

## 普通 Program 函数

托管加载器捕获已授权 Program 包内源码定义的函数，不包括任意宿主文件或依赖。把公开入口列入 `PROGRAM_ENTRIES`；私有帮助函数保留运行时访问，但不产生 DAG 节点，也不成为工具。确定性组合用 Python；[由模型选择的调用](https://fzkuji.github.io/OpenProgram/docs/capabilities/agentic-programming/choosing-the-next-step/tool-calling.zh.html)要提供已注册的工具。

## 持久对话

```
from openprogram import Agent, Context, TurnRequest
from openprogram.runtime.context.session_db import default_db

context = Context.for_session(default_db(), "example-conversation",
                              blocks={"reference": "User-supplied reference material"})
worker = Agent(context=context)
result = worker.run_turn(
    TurnRequest(session_id="example-conversation", user_text="Summarize the reference",
                agent_id="main", source="python"),
    on_event=lambda event: print(event["type"]),
)
print(result.final_text)
```

`ChatAgent` 是 App、Web、TUI 和频道适配器使用的对话子类型。它和 `Agent.run_turn()` 共用同一回合运行时：历史、权限、工具、流式、压缩和最终持久化。

| 项目 | 规则 |
| --- | --- |
| 下一回合 | 沿用会话 ID |
| `Context.for_session` | 选择 store，不创建 Provider。可选 `head_id` 选择前驱分支。 |
| `Context(history=None)` | 排除历史图内容，保留当前提示词 |
| 命名内容和 Provider | 作为用户内容渲染，不能改变系统指令或工具权限 |
| `arun_turn()`、`aresume_turn()` | 异步版本。回调在执行线程运行，更新 asyncio 消费者要线程安全地转交。取消等待任务会通知回合并等待其协作清理。 |
| `cancel_event` | `threading.Event`，供同步调用者使用 |
| `resume_turn(continuation)` | 消费已有的 continuation 及其冻结请求；不追加用户消息，也不重新应用已改的实例设置 |
| 暂停、插话、continuation 准入 | 由生产驱动的执行控制服务负责；Agent API 不新增任务注册表 |
| 工具超时 | 不取消父对话 |

[API 参考](https://fzkuji.github.io/OpenProgram/docs/reference/api/agent.zh.html) · [函数元数据](https://fzkuji.github.io/OpenProgram/docs/capabilities/agentic-programming/writing-functions/function-metadata.zh.html)
