运行代理

基本代理抽象公开用于运行代理的各种选项。 呼叫者可以选择提供零条、一条或多条输入消息。 调用方还可以在流式处理和非流式处理之间进行选择。 让我们深入了解不同的使用方案。

流式处理和非流式处理

Microsoft Agent Framework 支持用于运行代理的流式处理和非流式处理方法。

对于非流式处理,请使用 RunAsync 该方法。

Console.WriteLine(await agent.RunAsync("What is the weather like in Amsterdam?"));

对于流式处理,请使用 RunStreamingAsync 该方法。

await foreach (var update in agent.RunStreamingAsync("What is the weather like in Amsterdam?"))
{
    Console.Write(update);
}

对于非流式处理,请使用 run 该方法。

result = await agent.run("What is the weather like in Amsterdam?")
print(result.text)

对于流式处理,请使用 run 该方法和 stream=True. 这会返回 ResponseStream 可异步迭代的对象:

async for update in agent.run("What is the weather like in Amsterdam?", stream=True):
    if update.text:
        print(update.text, end="", flush=True)

ResponseStream

ResponseStream返回的对象run(..., stream=True)支持两种使用模式:

模式 1:异步迭代 - 在更新到达时处理更新,以便进行实时显示:

response_stream = agent.run("Tell me a story", stream=True)
async for update in response_stream:
    if update.text:
        print(update.text, end="", flush=True)

模式 2:直接最终化 - 跳过迭代并获取完整的响应:

response_stream = agent.run("Tell me a story", stream=True)
final = await response_stream.get_final_response()
print(final.text)

模式 3:组合 - 循环访问实时显示,然后获取聚合结果:

response_stream = agent.run("Tell me a story", stream=True)

# First, iterate to display streaming output
async for update in response_stream:
    if update.text:
        print(update.text, end="", flush=True)

# Then get the complete response (uses already-collected updates, does not re-iterate)
final = await response_stream.get_final_response()
print(f"\n\nFull response: {final.text}")
print(f"Messages: {len(final.messages)}")

如果在使用完整流之前应用程序可能停止,请使用 ResponseStream 异步上下文管理器,以便提前 break 关闭基础提供程序流:

response_stream = agent.run("Tell me a story", stream=True)

async with response_stream:
    async for update in response_stream:
        if update.text:
            print(update.text, end="", flush=True)
        if should_stop(update):
            break

完全消耗、流错误 await response_stream.close()和退出 async with 块会释放基础流。 不async with提供确定性清理的裸体break。

在消耗开始之前,可以注册有序的更新和最终结果入口以及 with_update_gate()with_result_gate()。 门返回 None 以允许值或引发异常以阻止它。 使用 with_update_transform() 和 with_result_transform() 何时必须替换内容。

在 buffer_updates() 流完成并且每个门成功之前,不应释放任何更新时调用。 如果结果转换替换最终响应,请传递 result_to_updates ,以便流可以从该权威结果重新生成缓冲更新。 较旧的 buffered_and_gated() 帮助程序已弃用。

有关入口排序、转换、缓冲、最终化和清理的完整示例,请参阅 ResponseStream 示例。

读取引文和批注

文本 Content 可以包含 annotations URL、文件和其他引用来源。 每个批注可以包含 annotated_regions 和一个 annotated_regions_coordinate_space 值:

  • "content" 表示索引引用生成的 Content.text。 当省略字段时,这是默认值。
  • "source" 表示索引引用引用的源,例如源文档字符、页面或块。

不要将源坐标区域作为生成的输出中的字符偏移量应用。 使用批注标题、URL、文件 ID 或其他元数据来呈现源。

在 Go 中, RunText 返回一 ResponseStream 个 - 迭代器对 (ResponseUpdate, error) 。

对于非流式处理,请调用 Collect() 流将所有更新收集到单个响应中:

resp, err := a.RunText(ctx, "What is the weather like in Amsterdam?").Collect()
if err != nil {
    panic(err)
}
fmt.Println(resp.String())

对于流式处理,请使用 range 循环直接循环访问流:

for update, err := range a.RunText(ctx, "What is the weather like in Amsterdam?", agent.Stream(true)) {
    if err != nil {
        panic(err)
    }
    fmt.Print(update.String())
}

代理运行选项

基本代理抽象允许为每个代理运行传递选项对象,但自定义抽象级别的运行的能力相当有限。 代理可能有很大差异,因此没有真正常见的自定义选项。

对于调用方知道其使用的代理类型的情况,可以传递特定类型选项以允许自定义运行。

例如,此处的代理是一个 ChatClientAgent ,可以传递 ChatClientAgentRunOptions 继承自 AgentRunOptions的对象。 这样,调用方就可以提供与任何代理级别选项合并的自定义 ChatOptions 项,然后再传递到 IChatClient 构建的 ChatClientAgent 代理级别选项。

var chatOptions = new ChatOptions() { Tools = [AIFunctionFactory.Create(GetWeather)] };
Console.WriteLine(await agent.RunAsync("What is the weather like in Amsterdam?", options: new ChatClientAgentRunOptions(chatOptions)));

Python代理支持通过 options 参数自定义每个运行。 选项作为 TypedDict 传递,可在构造时(通过 default_options)和每运行(通过 options)设置。 每个提供程序都有自己的 TypedDict 类,该类提供提供程序特定设置的完整 IDE 自动完成和类型检查。

常见选项包括:

  • max_tokens:要生成的令牌的最大数目
  • temperature:控制响应生成的随机性
  • model:覆盖此特定运行的模型
  • top_p:核采样参数
  • response_format:指定响应格式(例如结构化输出)

注释

参数toolsinstructions保持为直接关键字参数,不会通过options字典传递。

from agent_framework.openai import OpenAIChatClient, OpenAIChatOptions

# Set default options at construction time
agent = OpenAIChatClient().as_agent(
    instructions="You are a helpful assistant",
    default_options={
        "temperature": 0.7,
        "max_tokens": 500
    }
)

# Run with custom options (overrides defaults)
# OpenAIChatOptions provides IDE autocomplete for all OpenAI-specific settings
options: OpenAIChatOptions = {
    "temperature": 0.3,
    "max_tokens": 150,
    "model": "gpt-4o",
    "presence_penalty": 0.5,
    "frequency_penalty": 0.3
}

result = await agent.run(
    "What is the weather like in Amsterdam?",
    options=options
)

# Streaming with custom options
async for update in agent.run(
    "Tell me a detailed weather forecast",
    stream=True,
    options={"temperature": 0.7, "top_p": 0.9},
    tools=[additional_weather_tool]  # tools is still a keyword argument
):
    if update.text:
        print(update.text, end="", flush=True)

每个提供程序都有自己的 TypedDict 类(例如 OpenAIChatOptions,, AnthropicChatOptions), OllamaChatOptions该类公开该提供程序支持的完整选项集。

default_options如果同时提供每运行和按运行options,则按运行选项优先,并与默认值合并。

将代理级和运行级别工具组合在一起时,单个映射(例如 {"type": "web_search"} 被视为一个提供程序工具)。 映射不会扩展到其键中。

选项作为可变 agent.Option 参数传递。 可用选项包括:

  • agent.Stream(true) - 启用流式处理
  • agent.WithSession(session) - 为多轮对话附加会话
  • agent.WithStructuredOutput(&v) - 将结构化输出请求到类型化值
  • agent.WithResponseFormat(format) - 指定响应格式
  • agent.WithTool(tool) - 为此运行添加工具
  • agent.AllowBackgroundResponses(true) - 启用后台响应
resp, err := a.RunText(ctx, "Tell me a joke.",
    agent.Stream(true),
    agent.WithSession(session),
).Collect()

响应类型

来自代理的流式处理和非流式处理响应都包含代理生成的所有内容。 内容可能包括来自代理的结果(即用户问题的答案)的数据。 返回的其他数据的示例包括函数工具调用、函数工具调用的结果、推理文本、状态更新等。

由于并非所有返回的内容都是结果,因此在尝试将结果与其他内容隔离时查找特定内容类型非常重要。

若要从响应中提取文本结果,需要聚合来自所有项的所有TextContentChatMessages项。 为了简化此作,属性 Text 可用于聚合所有 TextContent响应类型。

对于非流式处理情况,所有内容均在一个 AgentResponse 对象中返回。 AgentResponse 允许通过 Messages 属性访问生成的消息。

var response = await agent.RunAsync("What is the weather like in Amsterdam?");
Console.WriteLine(response.Text);
Console.WriteLine(response.Messages.Count);

对于流式处理情况, AgentResponseUpdate 对象在生成时进行流式处理。 每个更新可能包含来自代理的结果的一部分,以及各种其他内容项。 与非流式处理情况类似,可以使用 Text 该属性获取更新中包含的结果部分,并通过属性钻取详细信息 Contents 。

await foreach (var update in agent.RunStreamingAsync("What is the weather like in Amsterdam?"))
{
    Console.WriteLine(update.Text);
    Console.WriteLine(update.Contents.Count);
}

对于非流式处理情况,所有内容均在一个 AgentResponse 对象中返回。 AgentResponse 允许通过 messages 属性访问生成的消息。

若要从响应中提取文本结果,需要聚合来自所有项的所有TextContentMessage项。 为了简化此作,属性 Text 可用于聚合所有 TextContent响应类型。

response = await agent.run("What is the weather like in Amsterdam?")
print(response.text)
print(len(response.messages))

# Access individual messages
for message in response.messages:
    print(f"Role: {message.role}, Text: {message.text}")

对于流式处理情况,AgentResponseUpdate对象通过返回的对象ResponseStream进行run(..., stream=True)流式传输。 每个更新可能包含来自代理的结果的一部分,以及各种其他内容项。 与非流式处理情况类似,可以使用 text 该属性获取更新中包含的结果部分,并通过属性钻取详细信息 contents 。

response_stream = agent.run("What is the weather like in Amsterdam?", stream=True)
async for update in response_stream:
    print(f"Update text: {update.text}")
    print(f"Content count: {len(update.contents)}")

    # Access individual content items
    for content in update.contents:
        if hasattr(content, 'text'):
            print(f"Content: {content.text}")

# Get the aggregated final response after streaming
final = await response_stream.get_final_response()
print(f"Complete text: {final.text}")

ResponseStream 生成 *agent.ResponseUpdate 值。 每个更新都包含:

  • Contents - 值的切片 message.Content ,如文本、函数调用和用法
  • Role - 消息角色,例如助理或系统
  • MessageID / ResponseID - 消息和响应的标识符

若要从非流式处理响应中获取全文结果,请使用 Collect():

resp, err := a.RunText(ctx, "What is the weather like in Amsterdam?").Collect()
if err != nil {
    panic(err)
}
fmt.Println(resp.String())

消息类型

代理的输入和输出表示为消息。 消息细分为内容项。

Microsoft Agent Framework 使用 Microsoft.Extensions.AI 抽象提供的消息和内容类型。 消息由 ChatMessage 类表示,所有内容类都继承自基 AIContent 类。

存在各种 AIContent 子类,用于表示不同类型的内容。 有些作为基本Microsoft.Extensions.AI抽象的一部分提供,但提供程序还可以根据需要添加自己的类型。

下面是来自 Microsoft.Extensions.AI 的一些常用类型:

类型 说明
TextContent 文本内容可以是输入,例如,来自用户或开发人员,以及代理的输出。 通常包含代理的文本结果。
DataContent 可以是输入和输出的二进制内容。 可用于向代理传入和传出图像、音频或视频数据(其中受支持)。
UriContent 通常指向托管内容(如图像、音频或视频)的 URL。
FunctionCallContent 推理服务调用函数工具的请求。
FunctionResultContent 函数工具调用的结果。

Python Agent Framework 使用来自 agent_framework 包的消息和内容类型。 消息由 Message 类表示,所有内容项都由 Content 属性区分的 type 类表示。

所有内容都由统一 Content 类表示,其中包含每种内容类型的工厂方法。 使用 type 属性检查内容类型。 以下内容类型可用:

内容类型 工厂方法 说明
"text" Content.from_text() 输入和输出的文本内容。 通常包含代理的文本结果。
"text_reasoning" Content.from_text_reasoning() 从支持思考链推理的模型中推理文本。 可能包括受保护的数据。
"data" Content.from_data()、Content.from_uri() 编码为数据 URI 的二进制内容。 用于图像、音频、视频和文档。
"uri" Content.from_uri() 指向托管内容的 URL,如图像、音频或视频。
"error" Content.from_error() 处理失败时的错误信息。 包括可选的错误代码和详细信息。
"function_call" Content.from_function_call() AI 服务调用函数工具的请求。
"function_result" Content.from_function_result() 函数工具调用的结果。
"usage" Content.from_usage() AI 服务的令牌使用情况和计费信息。
"hosted_file" Content.from_hosted_file() 对提供程序托管的文件的引用(例如上传到 OpenAI)。
"hosted_vector_store" Content.from_hosted_vector_store() 对提供程序托管的向量存储的引用。
"code_interpreter_tool_call" Content.from_code_interpreter_tool_call() AI 服务通过代码解释器执行代码的请求。
"code_interpreter_tool_result" Content.from_code_interpreter_tool_result() 代码解释器执行的结果。
"image_generation_tool_call" Content.from_image_generation_tool_call() AI 服务发出生成图像的请求。
"image_generation_tool_result" Content.from_image_generation_tool_result() 映像生成请求的结果。
"mcp_server_tool_call" Content.from_mcp_server_tool_call() 在 MCP 服务器上调用工具的请求。
"mcp_server_tool_result" Content.from_mcp_server_tool_result() MCP 服务器工具调用的结果。
"shell_tool_call" Content.from_shell_tool_call() AI 服务执行 shell 命令的请求。
"shell_tool_result" Content.from_shell_tool_result() shell 工具调用的聚合结果。
"shell_command_output" Content.from_shell_command_output() 单个 shell 命令执行的输出。
"function_approval_request" Content.from_function_approval_request() 在执行函数调用之前请求用户审批。
"function_approval_response" Content.from_function_approval_response() 用户对函数审批请求的响应。
"oauth_consent_request" Content.from_oauth_consent_request() 请求用户通过提供的链接完成 OAuth 同意。

当工具箱或托管 MCP 工具需要用户同意时,Foundry 流式处理和非流式处理响应都可以包含 oauth_consent_request 内容。 检查响应内容,或者 user_input_requests 假定非流式处理响应仅包含文本。 有关工具箱设置和限制,请参阅 Foundry 工具箱。

函数调用内容还公开执行所有权。 hosted=True 表示提供程序或服务执行调用,因此代理框架不会在本地执行它。 server_name 描述托管服务器边界,但不自行进行托管的调用。

框架拥有的提供程序和协议元数据属于一级命名空间,additional_properties例如core,openai或 foundrya2a。 with_namespaced_value()使用get_namespaced_value()和更新命名空间值时,以便适配器保留框架的副本和合并规则。

可合并的Content流式处理和AgentResponseUpdateChatResponseUpdate值可以设置为merge_mode"append"增量增量或"replace"权威有效负载或消息快照。 最终响应聚合使用流式处理指令并清除内容级别 merge_mode。

提供商拒绝仍然可见。Content(type="text") 当提供程序公开拒绝语义时,Python保留实验性的可序列化标记additional_properties["core"]["model_output_kind"] == "refusal"。 结构化输出提取不会分析携带此标记的文本。

下面介绍如何使用不同的内容类型:

from agent_framework import Message, Content

# A bare string creates one text content item
text_message = Message(role="user", contents="Hello!")

# Create a message with multiple content types
image_data = b"..."  # your image bytes
mixed_message = Message(
    role="user",
    contents=[
        Content.from_text("Analyze this image:"),
        Content.from_data(data=image_data, media_type="image/png"),
    ]
)

# Access content from responses
response = await agent.run("Describe the image")
for message in response.messages:
    for content in message.contents:
        if content.type == "text":
            print(f"Text: {content.text}")
        elif content.type == "data":
            print(f"Data URI: {content.uri}")
        elif content.type == "uri":
            print(f"External URI: {content.uri}")

裸字符串和单项字符串列表等效: Message("user", "Hello!")Message("user", ["Hello!"]) 每个列表创建一个文本内容项。

Go 代理框架使用包中的 message 消息和内容类型。 响应更新可以包含多个内容项;检查每个项,了解所需的内容类型。

对于流式处理,在更新到达时单独处理更新:

for update, err := range a.RunText(ctx, "Tell me a story.", agent.Stream(true)) {
    if err != nil {
        panic(err)
    }
    for _, c := range update.Contents {
        if text, ok := c.(*message.TextContent); ok {
            fmt.Print(text.Text)
        }
    }
}

Tip

有关完整的可运行示例,请参阅 完整示例 。

在运行期间注入消息

agent.Config.MessageInjector在主机或工具中配置agent.MessageInjector并保留对它的引用。 调用 EnqueueMessages(session, messages...) 并处理其错误,以队列延迟到达该会话的上下文。

在运行中的后续提供程序调用之前使用排队消息;它们不会中断正在进行的请求。 允许 RequirePerServiceCallHistoryPersistence 在调用无状态服务之间保留注入的消息和早期响应。

Go 工具默认配置消息注入器。 有关在同一代理运行期间排队传送更新的工具,请参阅 消息注入示例 。

后续步骤