|
| 1 | +import asyncio |
| 2 | +from datetime import datetime |
| 3 | + |
| 4 | +from openai.types.responses.tool import WebSearchToolFilters |
| 5 | +from openai.types.shared.reasoning import Reasoning |
| 6 | + |
| 7 | +from agents import Agent, ModelSettings, Runner, WebSearchTool, trace |
| 8 | + |
| 9 | +# import logging |
| 10 | +# logging.basicConfig(level=logging.DEBUG) |
| 11 | + |
| 12 | + |
| 13 | +async def main(): |
| 14 | + agent = Agent( |
| 15 | + name="WebOAI website searcher", |
| 16 | + model="gpt-5-nano", |
| 17 | + instructions="You are a helpful agent that can search openai.com resources.", |
| 18 | + tools=[ |
| 19 | + WebSearchTool( |
| 20 | + # https://platform.openai.com/docs/guides/tools-web-search?api-mode=responses#domain-filtering |
| 21 | + filters=WebSearchToolFilters( |
| 22 | + allowed_domains=[ |
| 23 | + "openai.com", |
| 24 | + "developer.openai.com", |
| 25 | + "platform.openai.com", |
| 26 | + "help.openai.com", |
| 27 | + ], |
| 28 | + ), |
| 29 | + search_context_size="medium", |
| 30 | + ) |
| 31 | + ], |
| 32 | + model_settings=ModelSettings( |
| 33 | + reasoning=Reasoning(effort="low"), |
| 34 | + verbosity="low", |
| 35 | + # https://platform.openai.com/docs/guides/tools-web-search?api-mode=responses#sources |
| 36 | + response_include=["web_search_call.action.sources"], |
| 37 | + ), |
| 38 | + ) |
| 39 | + |
| 40 | + with trace("Web search example"): |
| 41 | + today = datetime.now().strftime("%Y-%m-%d") |
| 42 | + query = f"Write a summary of the latest OpenAI Platform updates for developers in the last few weeks (today is {today})." |
| 43 | + result = await Runner.run(agent, query) |
| 44 | + |
| 45 | + print() |
| 46 | + print("### Sources ###") |
| 47 | + print() |
| 48 | + for item in result.new_items: |
| 49 | + if item.type == "tool_call_item": |
| 50 | + if item.raw_item.type == "web_search_call": |
| 51 | + for source in item.raw_item.action.sources: # type: ignore [union-attr] |
| 52 | + print(f"- {source.url}") |
| 53 | + print() |
| 54 | + print("### Final output ###") |
| 55 | + print() |
| 56 | + print(result.final_output) |
| 57 | + |
| 58 | + |
| 59 | +if __name__ == "__main__": |
| 60 | + asyncio.run(main()) |
0 commit comments