代码

cookbook/agent_concepts/user_control_flows/user_input_required_stream.py
from typing import List

from agno.agent import Agent
from agno.models.openai import OpenAIChat
from agno.tools import tool
from agno.tools.function import UserInputField
from agno.utils import pprint

@tool(requires_user_input=True, user_input_fields=["to_address"])
def send_email(subject: str, body: str, to_address: str) -> str:
    """
    发送电子邮件。

    参数:
        subject (str): 电子邮件的主题。
        body (str): 电子邮件的正文。
        to_address (str): 要发送电子邮件的地址。
    """
    return f"Sent email to {to_address} with subject {subject} and body {body}"

agent = Agent(
    model=OpenAIChat(id="gpt-4o-mini"),
    tools=[send_email],
    markdown=True,
)

for run_response in agent.run(
    "Send an email with the subject 'Hello' and the body 'Hello, world!'", stream=True
):
    if run_response.is_paused:
        for tool in run_response.tools_requiring_user_input:
            input_schema: List[UserInputField] = tool.user_input_schema

            for field in input_schema:
                # 向用户显示字段信息
                print(f"\n字段: {field.name}")
                print(f"描述: {field.description}")
                print(f"类型: {field.field_type}")

                # 获取用户输入
                if field.value is None:
                    user_value = input(f"请输入 {field.name} 的值: ")
                    # 更新字段值
                    field.value = user_value
                else:
                    print(f"值: {field.value}")

        run_response = agent.continue_run(stream=True)
    pprint.pprint_run_response(run_response)

用法

1

创建虚拟环境

打开 Terminal 并创建一个 python 虚拟环境。

python3 -m venv .venv
source .venv/bin/activate
2

设置您的 API 密钥

export OPENAI_API_KEY=xxx
3

安装库

pip install -U agno openai
4

运行示例

python cookbook/agent_concepts/user_control_flows/user_input_required_stream.py

主要特点

  • 使用 agent.run(stream=True) 进行流式响应
  • 使用 agent.continue_run(stream=True) 实现流式续传
  • 通过用户输入收集保持实时交互
  • 演示了如何处理带有用户输入的流式响应

用途

  • 实时用户交互
  • 需要用户输入的流式应用程序
  • 交互式表单类界面
  • 带用户输入的渐进式响应生成