Building Your First AI Agent in Python with the OpenAI Agents SDK
Build your first AI agent in Python with the OpenAI Agents SDK, adding web search, Python tools, conversation memory, and tracing in a simple end-to-end workflow.
以下正文同步自 KDnuggets,版权归原站所有,已转换为易读排版。
import os import sys
from agents import Agent, Runner, SQLiteSession, WebSearchTool from agents.decorators import tool
@tool def calculate_total( price: float, quantity: int ) -> float: """Calculate the total cost of an order."""
return price * quantity
def main() -> None: if not os.environ.get("OPENAI_API_KEY"): sys.exit( "Error: set the OPENAI_API_KEY environment variable first." )
agent = Agent( name="Assistant", instructions=""" Help the user with research and calculations. Use the available tools when necessary. """, tools=[ WebSearchTool(), calculate_total, ], )
session = SQLiteSession( "user_1", "conversations.db" )
try: while True: try: message = input("You: ") except (EOFError, KeyboardInterrupt): print() break
command = message.strip().lower()
if command in {"exit", "quit"}: break
if not command: continue
try: result = Runner.run_sync( agent, message, session=session, ) except Exception as exc: print( f"Agent error " f"({type(exc).name}): {exc}" ) continue
print("Agent:", result.final_output)
finally: session.close()
if name == "main": main()
This gives us a small but complete conversational agent with web search, a custom Python tool, persistent memory, basic error handling, and a continuous chat interface.
The Agents SDK also enables tracing by default, which is especially useful once your workflows become more complex. Traces let you inspect the model calls, tool usage, handoffs, and other steps taken during an agent run.
正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。