Skip to content

Commit 2ca0e0a

Browse files
style: format code with ruff
- Fix line length and whitespace issues - Remove trailing whitespace from JavaScript files - Ensure consistent code formatting across the project
1 parent f45ee62 commit 2ca0e0a

28 files changed

+311
-380
lines changed

docs/scripts/translate_docs.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -266,7 +266,9 @@ def translate_single_source_file(file_path: str) -> None:
266266

267267
def main():
268268
parser = argparse.ArgumentParser(description="Translate documentation files")
269-
parser.add_argument("--file", type=str, help="Specific file to translate (relative to docs directory)")
269+
parser.add_argument(
270+
"--file", type=str, help="Specific file to translate (relative to docs directory)"
271+
)
270272
args = parser.parse_args()
271273

272274
if args.file:

examples/basic/hello_world_jupyter.ipynb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
"agent = Agent(name=\"Assistant\", instructions=\"You are a helpful assistant\")\n",
3131
"\n",
3232
"# Intended for Jupyter notebooks where there's an existing event loop\n",
33-
"result = await Runner.run(agent, \"Write a haiku about recursion in programming.\") # type: ignore[top-level-await] # noqa: F704\n",
33+
"result = await Runner.run(agent, \"Write a haiku about recursion in programming.\") # type: ignore[top-level-await] # noqa: F704\n",
3434
"print(result.final_output)"
3535
]
3636
}

examples/basic/streaming_tool_basic.py

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
- yield "字符串" 用于最终结果
1414
- 内部 agent 事件被自动包装为 StreamingToolContextEvent,实现上下文隔离
1515
"""
16+
1617
import asyncio
1718
from collections.abc import AsyncGenerator
1819
from typing import Any, TypedDict
@@ -23,6 +24,7 @@
2324

2425
class DemoConfig(TypedDict):
2526
"""演示配置的类型定义"""
27+
2628
name: str
2729
tool: StreamingTool
2830
params: str
@@ -33,6 +35,7 @@ class DemoConfig(TypedDict):
3335
# 示例1:最简单的流式工具
3436
# ============================================================================
3537

38+
3639
@streaming_tool
3740
async def simple_progress_tool(task_name: str) -> AsyncGenerator[StreamEvent | str, Any]:
3841
"""最基础的流式工具示例
@@ -66,6 +69,7 @@ async def simple_progress_tool(task_name: str) -> AsyncGenerator[StreamEvent | s
6669
# 示例2:实时倒计时工具
6770
# ============================================================================
6871

72+
6973
@streaming_tool
7074
async def countdown_tool(seconds: int) -> AsyncGenerator[StreamEvent | str, Any]:
7175
"""倒计时工具 - 演示实时更新和标签使用
@@ -97,6 +101,7 @@ async def countdown_tool(seconds: int) -> AsyncGenerator[StreamEvent | str, Any]
97101
# 示例3:错误处理演示
98102
# ============================================================================
99103

104+
100105
@streaming_tool
101106
async def error_demo_tool(should_fail: bool) -> AsyncGenerator[StreamEvent | str, Any]:
102107
"""错误处理演示工具
@@ -134,6 +139,7 @@ async def error_demo_tool(should_fail: bool) -> AsyncGenerator[StreamEvent | str
134139
# Agent配置
135140
# ============================================================================
136141

142+
137143
def create_basic_demo_agent():
138144
"""创建基础演示Agent"""
139145
return Agent(
@@ -153,6 +159,7 @@ def create_basic_demo_agent():
153159
# 演示函数
154160
# ============================================================================
155161

162+
156163
async def demo_basic_concepts():
157164
"""演示@streaming_tool的基础概念"""
158165
print("=" * 70)
@@ -164,33 +171,34 @@ async def demo_basic_concepts():
164171
print("\n说明:本演示直接调用流式工具,展示核心概念,无需配置LLM模型")
165172

166173
from agents.run_context import RunContextWrapper
174+
167175
ctx = RunContextWrapper(context=None)
168176

169177
demos: list[DemoConfig] = [
170178
{
171179
"name": "基础进度更新",
172180
"tool": simple_progress_tool,
173181
"params": '{"task_name": "数据备份"}',
174-
"description": "演示最基本的多步骤进度通知"
182+
"description": "演示最基本的多步骤进度通知",
175183
},
176184
{
177185
"name": "实时倒计时",
178186
"tool": countdown_tool,
179187
"params": '{"seconds": 3}',
180-
"description": "演示实时更新和事件标签的使用"
188+
"description": "演示实时更新和事件标签的使用",
181189
},
182190
{
183191
"name": "错误处理(成功案例)",
184192
"tool": error_demo_tool,
185193
"params": '{"should_fail": false}',
186-
"description": "演示正常执行流程"
194+
"description": "演示正常执行流程",
187195
},
188196
{
189197
"name": "错误处理(失败案例)",
190198
"tool": error_demo_tool,
191199
"params": '{"should_fail": true}',
192-
"description": "演示异常处理机制"
193-
}
200+
"description": "演示异常处理机制",
201+
},
194202
]
195203

196204
for i, demo in enumerate(demos, 1):
@@ -203,7 +211,7 @@ async def demo_basic_concepts():
203211

204212
event_count = 0
205213
try:
206-
async for event in demo['tool'].on_invoke_tool(ctx, demo['params'], f"demo_{i}"):
214+
async for event in demo["tool"].on_invoke_tool(ctx, demo["params"], f"demo_{i}"):
207215
event_count += 1
208216

209217
if isinstance(event, NotifyStreamEvent):
@@ -223,7 +231,7 @@ async def demo_basic_concepts():
223231
elif isinstance(event, str):
224232
print(f" [{event_count:2d}] 🎯 最终结果: {event}")
225233
except Exception as e:
226-
print(f" [{event_count+1:2d}] ❌ 工具执行异常: {e}")
234+
print(f" [{event_count + 1:2d}] ❌ 工具执行异常: {e}")
227235

228236
print(f"📊 事件总数: {event_count}")
229237

@@ -244,9 +252,7 @@ async def demo_direct_calls():
244252

245253
event_count = 0
246254
async for event in simple_progress_tool.on_invoke_tool(
247-
ctx,
248-
'{"task_name": "系统维护"}',
249-
"direct_call_demo"
255+
ctx, '{"task_name": "系统维护"}', "direct_call_demo"
250256
):
251257
event_count += 1
252258
if isinstance(event, NotifyStreamEvent):
@@ -315,7 +321,7 @@ async def demo_key_concepts():
315321
("事件标签", "NotifyStreamEvent(tag='success')", "用于前端UI逻辑和事件分类"),
316322
("增量输出", "NotifyStreamEvent(is_delta=True)", "用于打字机效果等流式文本"),
317323
("终结信号", "yield '字符串' 后停止", "Runner会忽略后续的yield"),
318-
("上下文隔离", "StreamingToolContextEvent", "包装内部事件,实现隔离")
324+
("上下文隔离", "StreamingToolContextEvent", "包装内部事件,实现隔离"),
319325
]
320326

321327
print(f"{'概念':<12} {'代码示例':<35} {'说明'}")
@@ -332,6 +338,7 @@ async def demo_key_concepts():
332338

333339
if __name__ == "__main__":
334340
"""运行基础演示套件"""
341+
335342
async def main():
336343
await demo_basic_concepts()
337344
await demo_direct_calls()

examples/json_object_compatibility_demo.py

Lines changed: 26 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
# 定义测试用的数据模型
3030
class UserProfile(BaseModel):
3131
"""用户个人资料信息"""
32+
3233
name: str = Field(description="用户的姓名")
3334
age: int = Field(description="用户的年龄", ge=0, le=150)
3435
city: str = Field(description="用户居住的城市")
@@ -39,6 +40,7 @@ class UserProfile(BaseModel):
3940
@dataclass
4041
class TaskItem:
4142
"""任务项目"""
43+
4244
title: str
4345
description: str
4446
priority: int # 1-5, 5 为最高优先级
@@ -67,13 +69,16 @@ def demo_json_object_output_schema():
6769

6870
print("\n验证 JSON 输出:")
6971
print("-" * 40)
70-
test_json = json.dumps({
71-
"name": "张三",
72-
"age": 25,
73-
"city": "北京",
74-
"is_active": True,
75-
"interests": ["编程", "阅读", "旅行"]
76-
}, ensure_ascii=False)
72+
test_json = json.dumps(
73+
{
74+
"name": "张三",
75+
"age": 25,
76+
"city": "北京",
77+
"is_active": True,
78+
"interests": ["编程", "阅读", "旅行"],
79+
},
80+
ensure_ascii=False,
81+
)
7782

7883
try:
7984
validated_result = output_schema.validate_json(test_json)
@@ -112,15 +117,15 @@ def demo_validation():
112117
schema = JsonObjectOutputSchema(UserProfile)
113118

114119
# 测试有效的 JSON
115-
valid_json = '''
120+
valid_json = """
116121
{
117122
"name": "张三",
118123
"age": 25,
119124
"city": "北京",
120125
"is_active": true,
121126
"interests": ["编程", "阅读", "旅行"]
122127
}
123-
'''
128+
"""
124129

125130
print("验证有效 JSON:")
126131
print("-" * 40)
@@ -132,15 +137,15 @@ def demo_validation():
132137
print(f"验证失败: {e}")
133138

134139
# 测试需要修复的 JSON(缺少引号)
135-
malformed_json = '''
140+
malformed_json = """
136141
{
137142
name: "李四",
138143
age: 30,
139144
city: "上海",
140145
is_active: true,
141146
interests: ["音乐", "运动"]
142147
}
143-
'''
148+
"""
144149

145150
print("\n验证需要修复的 JSON:")
146151
print("-" * 40)
@@ -164,14 +169,14 @@ def demo_dataclass_support():
164169
print(f"- 目标类型: {schema.target_type.__name__}")
165170

166171
# 测试验证
167-
test_json = '''
172+
test_json = """
168173
{
169174
"title": "完成项目文档",
170175
"description": "编写项目的技术文档和用户手册",
171176
"priority": 1,
172177
"completed": false
173178
}
174-
'''
179+
"""
175180

176181
print("\n验证 dataclass JSON:")
177182
print("-" * 40)
@@ -203,10 +208,7 @@ def demo_custom_instructions():
203208
Output only valid JSON with no additional text or explanations.
204209
"""
205210

206-
schema = JsonObjectOutputSchema(
207-
UserProfile,
208-
custom_instructions=custom_instructions
209-
)
211+
schema = JsonObjectOutputSchema(UserProfile, custom_instructions=custom_instructions)
210212

211213
print("自定义指令:")
212214
print("-" * 40)
@@ -223,22 +225,24 @@ def demo_agent_integration():
223225
json_object_agent = Agent(
224226
name="JsonObjectAgent",
225227
instructions="你是一个专业的用户信息处理助手",
226-
output_type=JsonObjectOutputSchema(UserProfile)
228+
output_type=JsonObjectOutputSchema(UserProfile),
227229
)
228230

229231
print("JsonObjectOutputSchema Agent:")
230232
print(f"- Agent 名称: {json_object_agent.name}")
231233
print(f"- 输出类型: {type(json_object_agent.output_type).__name__}")
232-
if json_object_agent.output_type and hasattr(json_object_agent.output_type, 'target_type'):
234+
if json_object_agent.output_type and hasattr(json_object_agent.output_type, "target_type"):
233235
print(f"- 目标类型: {json_object_agent.output_type.target_type.__name__}")
234-
if json_object_agent.output_type and hasattr(json_object_agent.output_type, 'should_inject_to_system_prompt'):
236+
if json_object_agent.output_type and hasattr(
237+
json_object_agent.output_type, "should_inject_to_system_prompt"
238+
):
235239
print(f"- 需要注入: {json_object_agent.output_type.should_inject_to_system_prompt()}")
236240

237241
# 使用标准 AgentOutputSchema 的 Agent(业务层控制)
238242
standard_agent = Agent(
239243
name="StandardAgent",
240244
instructions="你是一个标准的用户信息处理助手",
241-
output_type=AgentOutputSchema(UserProfile)
245+
output_type=AgentOutputSchema(UserProfile),
242246
)
243247

244248
print("\n标准 AgentOutputSchema Agent:")
@@ -247,9 +251,6 @@ def demo_agent_integration():
247251
print("- 说明: 业务层根据模型能力选择合适的 Schema")
248252

249253

250-
251-
252-
253254
def demo_factory_methods():
254255
"""演示工厂方法"""
255256
print("\n" + "=" * 60)
@@ -301,6 +302,7 @@ def main():
301302
except Exception as e:
302303
print(f"\n演示过程中出现错误: {e}")
303304
import traceback
305+
304306
traceback.print_exc()
305307

306308

examples/reasoning_content/main.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ async def stream_with_reasoning_content():
4444
handoffs=[],
4545
tracing=ModelTracing.DISABLED,
4646
previous_response_id=None,
47-
prompt=None
47+
prompt=None,
4848
):
4949
if event.type == "response.reasoning_summary_text.delta":
5050
print(
@@ -82,7 +82,7 @@ async def get_response_with_reasoning_content():
8282
handoffs=[],
8383
tracing=ModelTracing.DISABLED,
8484
previous_response_id=None,
85-
prompt=None
85+
prompt=None,
8686
)
8787

8888
# Extract reasoning content and regular content from the response

0 commit comments

Comments
 (0)