OpenAI Agents SDK 中文文档 中文教程 (6)

 英文文档原文详见 OpenAI Agents SDKhttps://openai.github.io/openai-agents-python/

本文是OpenAI-agents-sdk-python使用翻译软件翻译后的中文文档/教程。分多个帖子发布,帖子的目录如下:

(1) OpenAI 代理 SDK, 介绍及快速入门

(2)OpenAI agents sdk, agents,运行agents,结果,流,工具,交接

(3) OpenAi agents sdk, 跟踪,上下文管理,护栏

(4) Openai agents sdk, 编排多个代理,模型,配置SDK

(5)(6)..等等,后面的都放到openai agents sdk的这个专栏https://blog.csdn.net/wtsolutions/category_12916751.html里面了,大家可以到专栏里面看到所有的目录,欢迎订阅这个专栏。

Tools

工具 module-attribute

可在代理中使用的工具。

FunctionTool 数据类

包装函数的工具。在大多数情况下,您应该使用帮助程序来 创建一个 FunctionTool,因为它们让你可以轻松地包装一个 Python 函数。function_tool

源码 src/agents/tool.py
 
            
name 实例属性
name: str

工具的名称,如 LLM 所示。通常是函数的名称。

描述 instance-attribute
description: str

工具的描述,如 LLM 所示。

params_json_schema instance-attribute
params_json_schema: dict[str, Any]

工具参数的 JSON 架构。

on_invoke_tool instance-attribute
on_invoke_tool: Callable[
    [RunContextWrapper[Any], str], Awaitable[str]
]

使用给定上下文和参数调用工具的函数。传递的参数 是: 1. 工具运行上下文。 2. 来自 LLM 的参数,以 JSON 字符串形式。

您必须返回工具输出的字符串表示。如果出现错误,您可以执行以下任一作 引发 Exception (这将导致运行失败) 或返回字符串错误消息 (该 将被发送回 LLM)。

strict_json_schema 类属性 instance-attribute
strict_json_schema: bool = True

JSON 架构是否处于严格模式。我们强烈建议将此设置为 True, 因为它增加了正确 JSON 输入的可能性。

FileSearchTool 数据类

一个托管工具,允许 LLM 在向量存储中进行搜索。目前仅支持 OpenAI 模型,使用响应 API。

源码 src/agents/tool.py
 
            
vector_store_ids instance-attribute
vector_store_ids: list[str]

要搜索的向量存储的 ID。

max_num_results 类属性 instance-attribute
max_num_results: int | None = None

要返回的最大结果数。

include_search_results 类属性实例属性
include_search_results: bool = False

是否将搜索结果包含在 LLM 生成的输出中。

ranking_options 类属性 instance-attribute
ranking_options: RankingOptions | None = None

搜索的排名选项。

filters 类-属性 instance-attribute
filters: Filters | None = None

要根据文件属性应用的过滤器。

WebSearchTool 数据类

一个托管工具,可让 LLM 搜索 Web。目前仅支持 OpenAI 模型, 使用响应 API。

源码 src/agents/tool.py
 
            
user_location 类属性 instance-attribute
user_location: UserLocation | None = None

搜索的可选位置。允许您自定义结果以与位置相关。

search_context_size 类属性实例属性
search_context_size: Literal["low", "medium", "high"] = (
    "medium"
)

用于搜索的上下文量。

ComputerTool 数据类

一个托管工具,可让 LLM 控制计算机。

源码 src/agents/tool.py
 
            
computer instance-attribute
computer: Computer | AsyncComputer

计算机实现,描述计算机的环境和尺寸, 以及实现单击、屏幕截图等计算机作。

default_tool_error_function

default_tool_error_function(
    ctx: RunContextWrapper[Any], error: Exception
) -> str

默认工具 error 函数,它只返回一般错误消息。

源码 src/agents/tool.py
 
            

function_tool

function_tool(
    func: ToolFunction[...],
    *,
    name_override: str | None = None,
    description_override: str | None = None,
    docstring_style: DocstringStyle | None = None,
    use_docstring_info: bool = True,
    failure_error_function: ToolErrorFunction | None = None,
) -> FunctionTool
function_tool(
    *,
    name_override: str | None = None,
    description_override: str | None = None,
    docstring_style: DocstringStyle | None = None,
    use_docstring_info: bool = True,
    failure_error_function: ToolErrorFunction | None = None,
) -> Callable[[ToolFunction[...]], FunctionTool]
function_tool(
    func: ToolFunction[...] | None = None,
    *,
    name_override: str | None = None,
    description_override: str | None = None,
    docstring_style: DocstringStyle | None = None,
    use_docstring_info: bool = True,
    failure_error_function: ToolErrorFunction
    | None = default_tool_error_function,
) -> (
    FunctionTool
    | Callable[[ToolFunction[...]], FunctionTool]
)

Decorator 从函数创建 FunctionTool。默认情况下,我们将: 1. 解析函数签名,为工具的参数创建 JSON 架构。 2. 使用函数的文档字符串填充工具的描述。 3. 使用函数的文档字符串填充参数描述。 系统会自动检测文档字符串样式,但您可以覆盖它。

如果函数将 a 作为第一个参数,则它必须与 使用该工具的代理程序的 context 类型。RunContextWrapper

参数:

名字类型描述违约
funcToolFunction[...] | None

要包装的函数。

None
name_overridestr | None

如果提供,请为工具使用此名称,而不是函数的名称。

None
description_overridestr | None

如果提供,请对工具使用此描述,而不是 函数的 docString 中。

None
docstring_styleDocstringStyle | None

如果提供,请将此样式用于工具的文档字符串。如果未提供,则 我们将尝试自动检测样式。

None
use_docstring_infobool

如果为 True,则使用函数的文档字符串填充工具的 description 和 argument descriptions。

True
failure_error_functionToolErrorFunction | None

如果提供,请使用此函数在 工具调用失败。错误消息将发送到 LLM。如果传递 None,则 no 将发送错误消息,而是引发 Exception。

default_tool_error_function

 

Results

RunResultBase 数据类

基地:ABC

源码src/agents/result.py
 
          
input 实例属性
input: str | list[TResponseInputItem]

原始输入项,即调用 run() 之前的项。这可能是一个 mutated version (如果存在改变输入的 Handoff 输入过滤器)。

new_items instance-attribute
new_items: list[RunItem]

代理运行期间生成的新项目。这些包括新消息、工具 调用及其输出等。

raw_responses instance-attribute
raw_responses: list[ModelResponse]

模型在代理运行期间生成的原始 LLM 响应。

final_output instance-attribute
final_output: Any

最后一个代理的输出。

input_guardrail_results instance-attribute
input_guardrail_results: list[InputGuardrailResult]

输入消息的护栏结果。

output_guardrail_results instance-attribute
output_guardrail_results: list[OutputGuardrailResult]

代理的最终输出的 Guardrail 结果。

last_agent abstractmethod 属性
last_agent: Agent[Any]

运行的最后一个代理程序。

final_output_as
final_output_as(
    cls: type[T], raise_if_incorrect_type: bool = False
) -> T

一种将最终输出强制转换为特定类型的便捷方法。默认情况下,强制转换 仅适用于 Typechecker。如果设置为 True,我们将引发一个 TypeError 如果最终输出不是给定类型。raise_if_incorrect_type

参数:

名字类型描述违约
clstype[T]

要将最终输出强制转换为的类型。

必填
raise_if_incorrect_typebool

如果为 True,则如果最终输出不是 给定的类型。

False

返回:

类型描述
T

强制转换为给定类型的最终输出。

源码src/agents/result.py
 
             
to_input_list
to_input_list() -> list[TResponseInputItem]

创建新的输入列表,将原始输入与生成的所有新项合并。

源码src/agents/result.py
 
             

RunResult 数据类

基地:RunResultBase

源码src/agents/result.py
 
          
last_agent 属性
last_agent: Agent[Any]

运行的最后一个代理程序。

RunResultStreaming 数据类

基地:RunResultBase

代理在流式处理模式下运行的结果。您可以使用该方法 在生成语义事件时接收语义事件。stream_events

流式处理方法将引发: - 如果代理超过max_turns限制,则出现 MaxTurnsExceeded 异常。 - 如果护栏跳闸,则出现 GuardrailTripwireTriggered 异常。

源码src/agents/result.py
 
          
current_agent instance-attribute
current_agent: Agent[Any]

当前正在运行的代理。

current_turn instance-attribute
current_turn: int

当前轮次编号。

max_turns instance-attribute
max_turns: int

代理可以运行的最大轮次。

final_output instance-attribute
final_output: Any

代理的最终输出。在代理完成运行之前,此字段为 None。

is_complete 类属性 instance-attribute
is_complete: bool = False

代理是否已完成运行。

last_agent 属性
last_agent: Agent[Any]

运行的最后一个代理程序。随着代理运行的进行而更新,因此真正的最后一个代理 仅在代理运行完成后可用。

stream_events async
stream_events() -> AsyncIterator[StreamEvent]

在生成新项时流式传输新项的增量。我们使用的是 OpenAI 响应 API,所以这些是语义事件:每个事件都有一个字段 描述事件的类型以及该事件的数据。type

这将引发: - 如果代理超过max_turns限制,则出现 MaxTurnsExceeded 异常。 - 如果护栏跳闸,则出现 GuardrailTripwireTriggered 异常。

### OpenAI Agents SDK Documentation and Usage Guide OpenAI has announced plans to introduce additional tools and integrations aimed at assisting developers with deploying, evaluating, and optimizing Agent-based applications over the coming months[^1]. These enhancements are expected to provide comprehensive support for leveraging OpenAI’s advanced models within custom workflows. For those interested in exploring or implementing the **Agents SDK**, it is important to note that while detailed official documentation may not yet be fully available publicly, there exist preliminary resources indicating how one might interact programmatically with these services. Below is an illustrative Python function demonstrating interaction via direct API calls: ```python import openai def get_completion(prompt, model="gpt-3.5-turbo"): """ Sends a user-defined prompt to the specified GPT model. Parameters: prompt (str): Input text provided by the user. model (str): Name of the language model being used. Returns: str: Generated content from the model's response. """ messages = [{"role": "user", "content": prompt}] response = openai.ChatCompletion.create( model=model, messages=messages, temperature=0, ) return response.choices[0].message["content"] ``` This snippet exemplifies basic communication between client-side scripts and server-hosted models through structured message exchanges[^3]. Moreover, considerations around enterprise-level privacy policies dictate that business-related information processed under such frameworks will remain confidential unless explicitly consented otherwise; further details regarding this aspect reside here: https://enterprise-privacy/. Lastly, although unrelated specifically to OpenAI agents but still relevant concerning interoperability among diverse platforms—Windows Phone 8 supports mechanisms allowing third-party programs to invoke others depending upon certain conditions like encountered file types or URL schemes[^4], which could serve as inspiration when designing similar behaviors inside agent ecosystems. Additionally, other organizations have made strides towards integrating coding functionalities into their respective infrastructures too—for instance, Together AI acquired CodeSandbox aiming toward enhancing its inference system so that large-scale machine learning projects gain native scripting execution abilities useful across various domains including automated task management pipelines[^5].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值