web_search.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. """Web Search Example
  2. This example shows how to:
  3. - search the web with `WebSearchTool`
  4. - limit results to trusted OpenAI domains
  5. - print the source URLs used during search
  6. Run:
  7. uv run python examples/web_search.py
  8. Requires OPENAI_API_KEY (or .env). Uses live API (network + usage).
  9. """
  10. import asyncio
  11. from openai.types.responses.web_search_tool import Filters
  12. from agency_swarm import Agency, Agent, WebSearchTool
  13. from agency_swarm.utils.citation_extractor import extract_web_search_sources
  14. async def main() -> None:
  15. print("Simple WebSearch Example")
  16. print("=" * 25)
  17. research_agent = Agent(
  18. name="ResearchAgent",
  19. model="gpt-5.4-mini",
  20. instructions=(
  21. "You are a helpful assistant. Search OpenAI resources only and return a short summary "
  22. "for developers in 3 bullet points."
  23. ),
  24. tools=[
  25. WebSearchTool(
  26. filters=Filters(
  27. allowed_domains=[
  28. "openai.com",
  29. "developer.openai.com",
  30. "platform.openai.com",
  31. "help.openai.com",
  32. ]
  33. ),
  34. search_context_size="medium",
  35. )
  36. ],
  37. )
  38. agency = Agency(research_agent, shared_instructions="Demonstrate web search with sources.")
  39. query = "What are 3 recent OpenAI platform updates for developers from the last few weeks?"
  40. print(f"\n❓ Query: {query}")
  41. response = await agency.get_response(query)
  42. print("\n### Final answer ###")
  43. print(response.final_output)
  44. source_urls = extract_web_search_sources(response)
  45. print("\n### Sources ###")
  46. if not source_urls:
  47. print("No source URLs were returned.")
  48. return
  49. for url in source_urls:
  50. print(f" - {url}")
  51. print(f"\nTotal sources: {len(source_urls)}")
  52. if __name__ == "__main__":
  53. asyncio.run(main())