chore: import upstream snapshot with attribution

This commit is contained in:
wehub-resource-sync
2026-07-13 12:39:17 +08:00
commit 4ed4e9ff99
1368 changed files with 334957 additions and 0 deletions
View File
+63
View File
@@ -0,0 +1,63 @@
import argparse
import asyncio
import json
import os
from datetime import datetime
from agents import Agent, HostedMCPTool, Runner, RunResult, RunResultStreaming
# import logging
# logging.basicConfig(level=logging.DEBUG)
async def main(verbose: bool, stream: bool):
# 1. Visit https://developers.google.com/oauthplayground/
# 2. Input https://www.googleapis.com/auth/calendar.events as the required scope
# 3. Grab the access token starting with "ya29."
authorization = os.environ["GOOGLE_CALENDAR_AUTHORIZATION"]
agent = Agent(
name="Assistant",
instructions="You are a helpful assistant that can help a user with their calendar.",
tools=[
HostedMCPTool(
tool_config={
"type": "mcp",
"server_label": "google_calendar",
# see https://platform.openai.com/docs/guides/tools-connectors-mcp#connectors
"connector_id": "connector_googlecalendar",
"authorization": authorization,
"require_approval": "never",
}
)
],
)
today = datetime.now().strftime("%Y-%m-%d")
run_result: RunResult | RunResultStreaming
if stream:
run_result = Runner.run_streamed(agent, f"What is my schedule for {today}?")
async for event in run_result.stream_events():
if event.type == "raw_response_event":
if event.data.type.startswith("response.output_item"):
print(json.dumps(event.data.to_dict(), indent=2))
if event.data.type.startswith("response.mcp"):
print(json.dumps(event.data.to_dict(), indent=2))
if event.data.type == "response.output_text.delta":
print(event.data.delta, end="", flush=True)
print()
else:
run_result = await Runner.run(agent, f"What is my schedule for {today}?")
print(run_result.final_output)
if verbose:
for item in run_result.new_items:
print(item)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--verbose", action="store_true", default=False)
parser.add_argument("--stream", action="store_true", default=False)
args = parser.parse_args()
asyncio.run(main(args.verbose, args.stream))
+133
View File
@@ -0,0 +1,133 @@
import argparse
import asyncio
import json
from typing import Literal
from agents import (
Agent,
HostedMCPTool,
ModelSettings,
RunConfig,
Runner,
RunResult,
RunResultStreaming,
)
from agents.model_settings import MCPToolChoice
from examples.auto_mode import confirm_with_fallback
def prompt_for_interruption(
tool_name: str | None, arguments: str | dict[str, object] | None
) -> bool:
params: object = {}
if arguments:
if isinstance(arguments, str):
try:
params = json.loads(arguments)
except json.JSONDecodeError:
params = arguments
else:
params = arguments
try:
return confirm_with_fallback(
f"Approve running tool (mcp: {tool_name or 'unknown'}, params: {json.dumps(params)})? (y/n) ",
default=True,
)
except (EOFError, KeyboardInterrupt):
return False
async def _drain_stream(
result: RunResultStreaming,
verbose: bool,
) -> RunResultStreaming:
async for event in result.stream_events():
if verbose:
print(event)
elif event.type == "raw_response_event" and event.data.type == "response.output_text.delta":
print(event.data.delta, end="", flush=True)
if not verbose:
print()
return result
async def main(verbose: bool, stream: bool) -> None:
require_approval: Literal["always"] = "always"
# Use the concise question tool first, then allow the model to answer after approval instead of
# forcing the same tool again.
agent = Agent(
name="MCP Assistant",
instructions=(
"You must always use the MCP tools to answer questions. "
"Use the DeepWiki hosted MCP server to answer questions and do not ask the user for "
"additional configuration."
),
model_settings=ModelSettings(
tool_choice=MCPToolChoice(server_label="deepwiki", name="ask_question")
),
tools=[
HostedMCPTool(
tool_config={
"type": "mcp",
"server_label": "deepwiki",
"server_url": "https://mcp.deepwiki.com/mcp",
"require_approval": require_approval,
}
)
],
)
resume_config = RunConfig(model_settings=ModelSettings(tool_choice="auto"))
question = "Which language is the repository openai/codex written in?"
run_result: RunResult | RunResultStreaming
if stream:
stream_result = Runner.run_streamed(agent, question, max_turns=100)
stream_result = await _drain_stream(stream_result, verbose)
while stream_result.interruptions:
state = stream_result.to_state()
for interruption in stream_result.interruptions:
approved = prompt_for_interruption(interruption.name, interruption.arguments)
if approved:
state.approve(interruption)
else:
state.reject(interruption)
stream_result = Runner.run_streamed(
agent,
state,
max_turns=100,
run_config=resume_config,
)
stream_result = await _drain_stream(stream_result, verbose)
print(f"Done streaming; final result: {stream_result.final_output}")
run_result = stream_result
else:
run_result = await Runner.run(agent, question, max_turns=100)
while run_result.interruptions:
state = run_result.to_state()
for interruption in run_result.interruptions:
approved = prompt_for_interruption(interruption.name, interruption.arguments)
if approved:
state.approve(interruption)
else:
state.reject(interruption)
run_result = await Runner.run(
agent,
state,
max_turns=100,
run_config=resume_config,
)
print(run_result.final_output)
if verbose:
for item in run_result.new_items:
print(item)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--verbose", action="store_true", default=False)
parser.add_argument("--stream", action="store_true", default=False)
args = parser.parse_args()
asyncio.run(main(args.verbose, args.stream))
+86
View File
@@ -0,0 +1,86 @@
import argparse
import asyncio
import json
from typing import Literal
from agents import (
Agent,
HostedMCPTool,
MCPToolApprovalFunctionResult,
MCPToolApprovalRequest,
Runner,
RunResult,
RunResultStreaming,
)
from examples.auto_mode import confirm_with_fallback
def prompt_approval(request: MCPToolApprovalRequest) -> MCPToolApprovalFunctionResult:
params: object = request.data.arguments or {}
approved = confirm_with_fallback(
f"Approve running tool (mcp: {request.data.name}, params: {json.dumps(params)})? (y/n) ",
default=True,
)
result: MCPToolApprovalFunctionResult = {"approve": approved}
if not approved:
result["reason"] = "User denied"
return result
async def main(verbose: bool, stream: bool) -> None:
require_approval: Literal["always"] = "always"
agent = Agent(
name="MCP Assistant",
instructions=(
"You must always use the MCP tools to answer questions. "
"Use the DeepWiki hosted MCP server to answer questions and do not ask the user for "
"additional configuration."
),
tools=[
HostedMCPTool(
tool_config={
"type": "mcp",
"server_label": "deepwiki",
"server_url": "https://mcp.deepwiki.com/mcp",
"allowed_tools": ["ask_question"],
"require_approval": require_approval,
},
on_approval_request=prompt_approval,
)
],
)
question = "Which language is the repository openai/codex written in?"
run_result: RunResult | RunResultStreaming
if stream:
run_result = Runner.run_streamed(agent, question)
async for event in run_result.stream_events():
if verbose:
print(event)
elif (
event.type == "raw_response_event"
and event.data.type == "response.output_text.delta"
):
print(event.data.delta, end="", flush=True)
if not verbose:
print()
print(f"Done streaming; final result: {run_result.final_output}")
else:
run_result = await Runner.run(agent, question)
while run_result.interruptions:
run_result = await Runner.run(agent, run_result.to_state())
print(run_result.final_output)
if verbose:
for item in run_result.new_items:
print(item)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--verbose", action="store_true", default=False)
parser.add_argument("--stream", action="store_true", default=False)
args = parser.parse_args()
asyncio.run(main(args.verbose, args.stream))
+56
View File
@@ -0,0 +1,56 @@
import argparse
import asyncio
from agents import Agent, HostedMCPTool, ModelSettings, Runner, RunResult, RunResultStreaming
"""This example demonstrates how to use the hosted MCP support in the OpenAI Responses API, with
approvals not required for any tools. You should only use this for trusted MCP servers."""
async def main(verbose: bool, stream: bool, repo: str):
question = f"Which language is the repository {repo} written in?"
agent = Agent(
name="Assistant",
instructions=f"You can use the DeepWiki hosted MCP server to inspect {repo}.",
model_settings=ModelSettings(tool_choice="required"),
tools=[
HostedMCPTool(
tool_config={
"type": "mcp",
"server_label": "deepwiki",
"server_url": "https://mcp.deepwiki.com/mcp",
"require_approval": "never",
}
)
],
)
run_result: RunResult | RunResultStreaming
if stream:
run_result = Runner.run_streamed(agent, question)
async for event in run_result.stream_events():
if event.type == "run_item_stream_event":
print(f"Got event of type {event.item.__class__.__name__}")
print(f"Done streaming; final result: {run_result.final_output}")
else:
run_result = await Runner.run(agent, question)
print(run_result.final_output)
# The repository is primarily written in Python...
if verbose:
for item in run_result.new_items:
print(item)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--verbose", action="store_true", default=False)
parser.add_argument("--stream", action="store_true", default=False)
parser.add_argument(
"--repo",
default="https://github.com/openai/openai-agents-python",
help="Repository URL or slug that the DeepWiki MCP server should use.",
)
args = parser.parse_args()
asyncio.run(main(args.verbose, args.stream, args.repo))