OA0 = Omni AI 0
OA0 是一个探索 AI 的论坛
现在注册
已注册用户请  登录
OA0  ›  技能包  ›  ydc-openai-agent-sdk:集成 OpenAI 智能体 SDK 的开发技能

ydc-openai-agent-sdk:集成 OpenAI 智能体 SDK 的开发技能

 
  proxy ·  2026-02-19 17:19:17 · 3 次点击  · 0 条评论  

名称: ydc-openai-agent-sdk-integration
描述: 将 OpenAI Agents SDK 与 You.com MCP 服务器集成 - 为 Python 和 TypeScript 提供托管和可流式传输的 HTTP 支持。当开发者提及 OpenAI Agents SDK、OpenAI 智能体或将 OpenAI 与 MCP 集成时使用。
许可证: MIT
compatibility: Python 3.10+ 或 Node.js 18+ (需 TypeScript)
元数据:
author: youdotcom-oss
category: sdk-integration
version: "1.0.0"
keywords: openai,openai-agents,agent-sdk,mcp,you.com,integration,hosted-mcp,streamable-http,web-search,python,typescript


将 OpenAI Agents SDK 与 You.com MCP 集成

本工作流指导您将 OpenAI Agents SDK 与 You.com 的 MCP 服务器进行集成。

工作流程

  1. 询问:选择编程语言

    • Python 还是 TypeScript?
  2. 询问:MCP 配置类型

    • 托管 MCP(OpenAI 管理,提供服务器 URL):推荐使用,配置简单
    • 可流式传输的 HTTP(自管理连接):适用于自定义基础设施
  3. 安装包

    • Python: pip install openai-agents
    • TypeScript: npm install @openai/agents
  4. 询问:环境变量

    两种模式都需要:
    * YDC_API_KEY(You.com API 密钥,用于 Bearer 令牌)
    * OPENAI_API_KEY(OpenAI API 密钥)

    是否已设置?
    * 如果:指导获取密钥:
    - YDC_API_KEY: https://you.com/platform/api-keys
    - OPENAI_API_KEY: https://platform.openai.com/api-keys

  5. 询问:文件位置

    • 新建文件:询问创建位置和文件名
    • 现有文件:询问要集成到哪个文件(添加 MCP 配置)
  6. 创建/更新文件

    对于新建文件:
    * 使用下方“完整模板”部分的完整模板代码
    * 用户设置好 API 密钥后即可立即运行

    对于现有文件:
    * 将 MCP 服务器配置添加到现有代码中

    托管 MCP 配置块 (Python):
    ```python
    from agents import Agent, Runner
    from agents.mcp import HostedMCPTool

    验证:ydc_api_key = os.getenv("YDC_API_KEY")

    agent = Agent(
    name="助手",
    instructions="使用 You.com 工具来回答问题。",
    tools=[
    HostedMCPTool(
    tool_config={
    "type": "mcp",
    "server_label": "ydc",
    "server_url": "https://api.you.com/mcp",
    "headers": {
    "Authorization": f"Bearer {ydc_api_key}"
    },
    "require_approval": "never",
    }
    )
    ],
    )
    ```

    托管 MCP 配置块 (TypeScript):
    ```typescript
    import { Agent, hostedMcpTool } from '@openai/agents';

    // 验证:const ydcApiKey = process.env.YDC_API_KEY;
    const agent = new Agent({
    name: '助手',
    instructions: '使用 You.com 工具来回答问题。',
    tools: [
    hostedMcpTool({
    serverLabel: 'ydc',
    serverUrl: 'https://api.you.com/mcp',
    headers: {
    Authorization: Bearer ${ydcApiKey},
    },
    }),
    ],
    });
    ```

    可流式传输的 HTTP 配置块 (Python):
    ```python
    from agents import Agent, Runner
    from agents.mcp import MCPServerStreamableHttp

    验证:ydc_api_key = os.getenv("YDC_API_KEY")

    async with MCPServerStreamableHttp(
    name="You.com MCP 服务器",
    params={
    "url": "https://api.you.com/mcp",
    "headers": {"Authorization": f"Bearer {ydc_api_key}"},
    "timeout": 10,
    },
    cache_tools_list=True,
    max_retry_attempts=3,
    ) as server:
    agent = Agent(
    name="助手",
    instructions="使用 You.com 工具来回答问题。",
    mcp_servers=[server],
    )
    ```

    可流式传输的 HTTP 配置块 (TypeScript):
    ```typescript
    import { Agent, MCPServerStreamableHttp } from '@openai/agents';

    // 验证:const ydcApiKey = process.env.YDC_API_KEY;
    const mcpServer = new MCPServerStreamableHttp({
    url: 'https://api.you.com/mcp',
    name: 'You.com MCP 服务器',
    requestInit: {
    headers: {
    Authorization: Bearer ${ydcApiKey},
    },
    },
    });

    const agent = new Agent({
    name: '助手',
    instructions: '使用 You.com 工具来回答问题。',
    mcpServers: [mcpServer],
    });
    ```

完整模板

为新文件使用这些完整模板。每个模板在设置好 API 密钥后即可运行。

Python 托管 MCP 模板(完整示例)

"""
OpenAI Agents SDK 与 You.com 托管 MCP
使用 OpenAI 管理基础设施的 Python 实现
"""

import os
import asyncio
from agents import Agent, Runner
from agents.mcp import HostedMCPTool

# 验证环境变量
ydc_api_key = os.getenv("YDC_API_KEY")
openai_api_key = os.getenv("OPENAI_API_KEY")

if not ydc_api_key:
    raise ValueError(
        "需要 YDC_API_KEY 环境变量。"
        "请在此处获取密钥:https://you.com/platform/api-keys"
    )

if not openai_api_key:
    raise ValueError(
        "需要 OPENAI_API_KEY 环境变量。"
        "请在此处获取密钥:https://platform.openai.com/api-keys"
    )


async def main():
    """
    示例:使用 You.com 托管 MCP 工具搜索 AI 新闻
    """
    # 使用托管 MCP 工具配置智能体
    agent = Agent(
        name="AI 新闻助手",
        instructions="使用 You.com 工具搜索并回答有关 AI 新闻的问题。",
        tools=[
            HostedMCPTool(
                tool_config={
                    "type": "mcp",
                    "server_label": "ydc",
                    "server_url": "https://api.you.com/mcp",
                    "headers": {
                        "Authorization": f"Bearer {ydc_api_key}"
                    },
                    "require_approval": "never",
                }
            )
        ],
    )

    # 使用用户查询运行智能体
    result = await Runner.run(
        agent,
        "搜索本周最新的 AI 新闻"
    )

    print(result.final_output)


if __name__ == "__main__":
    asyncio.run(main())

Python 可流式传输 HTTP 模板(完整示例)

"""
OpenAI Agents SDK 与 You.com 可流式传输 HTTP MCP
使用自管理连接的 Python 实现
"""

import os
import asyncio
from agents import Agent, Runner
from agents.mcp import MCPServerStreamableHttp

# 验证环境变量
ydc_api_key = os.getenv("YDC_API_KEY")
openai_api_key = os.getenv("OPENAI_API_KEY")

if not ydc_api_key:
    raise ValueError(
        "需要 YDC_API_KEY 环境变量。"
        "请在此处获取密钥:https://you.com/platform/api-keys"
    )

if not openai_api_key:
    raise ValueError(
        "需要 OPENAI_API_KEY 环境变量。"
        "请在此处获取密钥:https://platform.openai.com/api-keys"
    )


async def main():
    """
    示例:使用 You.com 可流式传输 HTTP MCP 服务器搜索 AI 新闻
    """
    # 配置可流式传输 HTTP MCP 服务器
    async with MCPServerStreamableHttp(
        name="You.com MCP 服务器",
        params={
            "url": "https://api.you.com/mcp",
            "headers": {"Authorization": f"Bearer {ydc_api_key}"},
            "timeout": 10,
        },
        cache_tools_list=True,
        max_retry_attempts=3,
    ) as server:
        # 使用 MCP 服务器配置智能体
        agent = Agent(
            name="AI 新闻助手",
            instructions="使用 You.com 工具搜索并回答有关 AI 新闻的问题。",
            mcp_servers=[server],
        )

        # 使用用户查询运行智能体
        result = await Runner.run(
            agent,
            "搜索本周最新的 AI 新闻"
        )

        print(result.final_output)


if __name__ == "__main__":
    asyncio.run(main())

TypeScript 托管 MCP 模板(完整示例)

/**
 * OpenAI Agents SDK 与 You.com 托管 MCP
 * 使用 OpenAI 管理基础设施的 TypeScript 实现
 */

import { Agent, run, hostedMcpTool } from '@openai/agents';

// 验证环境变量
const ydcApiKey = process.env.YDC_API_KEY;
const openaiApiKey = process.env.OPENAI_API_KEY;

if (!ydcApiKey) {
  throw new Error(
    '需要 YDC_API_KEY 环境变量。' +
      '请在此处获取密钥:https://you.com/platform/api-keys'
  );
}

if (!openaiApiKey) {
  throw new Error(
    '需要 OPENAI_API_KEY 环境变量。' +
      '请在此处获取密钥:https://platform.openai.com/api-keys'
  );
}

/**
 * 示例:使用 You.com 托管 MCP 工具搜索 AI 新闻
 */
async function main() {
  // 使用托管 MCP 工具配置智能体
  const agent = new Agent({
    name: 'AI 新闻助手',
    instructions:
      '使用 You.com 工具搜索并回答有关 AI 新闻的问题。',
    tools: [
      hostedMcpTool({
        serverLabel: 'ydc',
        serverUrl: 'https://api.you.com/mcp',
        headers: {
          Authorization: `Bearer ${ydcApiKey}`,
        },
      }),
    ],
  });

  // 使用用户查询运行智能体
  const result = await run(
    agent,
    '搜索本周最新的 AI 新闻'
  );

  console.log(result.finalOutput);
}

main().catch(console.error);

TypeScript 可流式传输 HTTP 模板(完整示例)

/**
 * OpenAI Agents SDK 与 You.com 可流式传输 HTTP MCP
 * 使用自管理连接的 TypeScript 实现
 */

import { Agent, run, MCPServerStreamableHttp } from '@openai/agents';

// 验证环境变量
const ydcApiKey = process.env.YDC_API_KEY;
const openaiApiKey = process.env.OPENAI_API_KEY;

if (!ydcApiKey) {
  throw new Error(
    '需要 YDC_API_KEY 环境变量。' +
      '请在此处获取密钥:https://you.com/platform/api-keys'
  );
}

if (!openaiApiKey) {
  throw new Error(
    '需要 OPENAI_API_KEY 环境变量。' +
      '请在此处获取密钥:https://platform.openai.com/api-keys'
  );
}

/**
 * 示例:使用 You.com 可流式传输 HTTP MCP 服务器搜索 AI 新闻
 */
async function main() {
  // 配置可流式传输 HTTP MCP 服务器
  const mcpServer = new MCPServerStreamableHttp({
    url: 'https://api.you.com/mcp',
    name: 'You.com MCP 服务器',
    requestInit: {
      headers: {
        Authorization: `Bearer ${ydcApiKey}`,
      },
    },
  });

  try {
    // 连接到 MCP 服务器
    await mcpServer.connect();

    // 使用 MCP 服务器配置智能体
    const agent = new Agent({
      name: 'AI 新闻助手',
      instructions:
        '使用 You.com 工具搜索并回答有关 AI 新闻的问题。',
      mcpServers: [mcpServer],
    });

    // 使用用户查询运行智能体
    const result = await run(
      agent,
      '搜索本周最新的 AI 新闻'
    );

    console.log(result.finalOutput);
  } finally {
    // 清理连接
    await mcpServer.close();
  }
}

main().catch(console.error);

MCP 配置类型

托管 MCP(推荐)

是什么: OpenAI 通过其 Responses API 管理 MCP 连接和工具路由。

优点:
- ✅ 配置更简单(无需管理连接)
- ✅ OpenAI 处理身份验证和重试
- ✅ 延迟更低(工具在 OpenAI 基础设施中运行)
- ✅ 自动工具发现和列表
- ✅ 无需管理异步上下文或清理

适用场景:
- 构建生产应用程序
- 希望样板代码最少
- 需要可靠的工具执行
- 不需要自定义传输层

配置:

Python:

from agents.mcp import HostedMCPTool

tools=[
    HostedMCPTool(
        tool_config={
            "type": "mcp",
            "server_label": "ydc",
            "server_url": "https://api.you.com/mcp",
            "headers": {
                "Authorization": f"Bearer {os.environ['YDC_API_KEY']}"
            },
            "require_approval": "never",
        }
    )
]

TypeScript:

import { hostedMcpTool } from '@openai/agents';

tools: [
  hostedMcpTool({
    serverLabel: 'ydc',
    serverUrl: 'https://api.you.com/mcp',
    headers: {
      Authorization: `Bearer ${process.env.YDC_API_KEY}`,
    },
  }),
]

可流式传输的 HTTP MCP

是什么: 您自己管理 MCP 连接和传输层。

优点:
- ✅ 完全控制网络连接
- ✅ 可集成自定义基础设施
- ✅ 可添加自定义头部、超时、重试逻辑
- ✅ 可在自己的环境中运行 MCP 服务器
- ✅ 更适合测试和开发

适用场景:
- 需要自定义传输配置
- 在自己的基础设施中运行 MCP 服务器
- 需要特定的网络设置
- 开发和测试场景

配置:

Python:

from agents.mcp import MCPServerStreamableHttp

async with MCPServerStreamableHttp(
    name="You.com MCP 服务器",
    params={
        "url": "https://api.you.com/mcp",
        "headers": {"Authorization": f"Bearer {os.environ['YDC_API_KEY']}"},
        "timeout": 10,
    },
    cache_tools_list=True,
    max_retry_attempts=3,
) as server:
    agent = Agent(mcp_servers=[server])

TypeScript:

import { MCPServerStreamableHttp } from '@openai/agents';

const mcpServer = new MCPServerStreamableHttp({
  url: 'https://api.you.com/mcp',
  name: 'You.com MCP 服务器',
  requestInit: {
    headers: {
      Authorization: `Bearer ${process.env.YDC_API_KEY}`,
    },
  },
});

await mcpServer.connect();
try {
  const agent = new Agent({ mcpServers: [mcpServer] });
  // 使用智能体
} finally {
  await mcpServer.close();
}

可用的 You.com 工具

配置完成后,智能体可以发现并使用以下工具:
- mcp__ydc__you_search - 网页和新闻搜索
- mcp__ydc__you_express - 结合网络上下文的 AI 驱动答案
- mcp__ydc__you_contents - 网页内容提取

环境变量

两种配置模式都需要以下两个 API 密钥:

# 添加到 .env 文件或 shell 配置文件中
export YDC_API_KEY="your-you-api-key-here"
export OPENAI_API_KEY="your-openai-api-key-here"

获取您的 API 密钥:
- You.com: https://you.com/platform/api-keys
- OpenAI: https://platform.openai.com/api-keys

验证清单

完成前请检查:

  • [ ] 包已安装:openai-agents (Python) 或 @openai/agents (TypeScript)
  • [ ] 环境变量已设置:YDC_API_KEYOPENAI_API_KEY
  • [ ] 模板已复制或配置已添加到现有文件
  • [ ] 已选择 MCP 配置类型(托管或可流式传输 HTTP)
  • [ ] 授权头部已配置 Bearer 令牌
  • [ ] 文件可执行 (Python) 或可编译 (TypeScript)
  • [ ] 准备好使用示例查询进行测试

测试您的集成

Python:

python your-file.py

TypeScript:

# 使用 tsx(推荐用于快速测试)
npx tsx your-file.ts

# 或编译后运行
tsc your-file.ts && node your-file.js

常见问题

找不到模块 @openai/agents 安装包:
# NPM
npm install @openai/agents

# Bun
bun add @openai/agents

# Yarn
yarn add @openai/agents

# pnpm
pnpm add @openai/agents
需要 YDC_API_KEY 环境变量 设置您的 You.com API 密钥:
export YDC_API_KEY="your-api-key-here"
在此处获取密钥:https://you.com/platform/api-keys
需要 OPENAI_API_KEY 环境变量 设置您的 OpenAI API 密钥: ```bash export OPENAI_API_KEY="your-api-key-
3 次点击  ∙  0 人收藏  
登录后收藏  
目前尚无回复
0 条回复
About   ·   Help   ·    
OA0 - Omni AI 0 一个探索 AI 的社区
沪ICP备2024103595号-2
Developed with Cursor