Lesson 1.8: AI Agent with OpenAI SDK
OpenAI has launched a framework, accessible at the OpenAI Agents Python GitHub Repository. In this course, we will use this framework to build AI agents.
AI agents, as per the OpenAI agent SDK, function like callable functions. They take a natural language string as input and produce a string as output. During execution, these agents can interact with the external world by calling other functions.
Install the agent SDK framework with the following command on command line:
pip install openai-agents
Open Cursor AI code editor, set up a new directory "lesson1", and within that, a file called "first_agent.py".
Use the following starter code to create our first AI agent:
from agents import Agent, Runner
agent = Agent(name="Assistant", instructions="You are a helpful assistant")
result = Runner.run_sync(agent, "Write a poem about recursion in programming.")
print(result.final_output)
Hit "Command-i" on Mac, or "Ctrl-i" on windows, and type the following prompt:
Modify the script to read the OpenAI key from in ~/.mingdaoai/openai.key
Set environment variable OPENAI_API_KEY to the key
We can vary the prompt by changing it into writing a poem about technology. We should see the output file similar to the following.
import os
from pathlib import Path
# Read OpenAI API key from file
key_path = Path.home() / '.mingdaoai' / 'openai.key'
with open(key_path) as f:
api_key = f.read().strip()
os.environ['OPENAI_API_KEY'] = api_key
from agents import Agent, Runner
agent = Agent(name="Assistant", instructions="You are a helpful assistant")
result = Runner.run_sync(agent, "Write a poem about technology.")
print(result.final_output)