OpenAI
OpenAI
AgentOps로 OpenAI API 호출을 추적하고 분석하는 방법을 소개해요. 설치, API 키 설정, 그리고 스트리밍·함수 호출 예제까지 알아볼게요.
출처: 문서
본문
AgentOps는 OpenAI의 Python SDK와 원활하게 통합되어, 모든 OpenAI API 호출을 자동으로 추적하고 분석할 수 있게 해줍니다.
설치 (Installation)
poetry add agentops openai
uv pip install agentops openai
API 키 설정 (Setting Up API Keys)
OpenAI를 AgentOps와 함께 사용하기 전에 API 키를 설정해야 해요. 다음을 얻을 수 있습니다.
- OPENAI_API_KEY: OpenAI Platform에서
- AGENTOPS_API_KEY: AgentOps Dashboard에서
그런 다음 환경 변수로 내보내거나 .env 파일에 설정할 수 있어요.
OPENAI_API_KEY="your_openai_api_key_here"
AGENTOPS_API_KEY="your_agentops_api_key_here"
그리고 Python 코드에서 환경 변수를 로드합니다.
from dotenv import load_dotenv
import os
# Load environment variables from .env file
load_dotenv()
# Set up environment variables with fallback values
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")
os.environ["AGENTOPS_API_KEY"] = os.getenv("AGENTOPS_API_KEY")
사용법 (Usage)
애플리케이션 시작 시 AgentOps를 초기화하면 모든 OpenAI API 호출이 자동으로 추적됩니다.
import agentops
from openai import OpenAI
# Initialize AgentOps
agentops.init()
# Create OpenAI client
client = OpenAI()
# Make API calls as usual - AgentOps will track them automatically
response = client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "What is the capital of France?"}
]
)
print(response.choices[0].message.content)
예제 (Examples)
Initialize AgentOps
agentops.init()
Create OpenAI client
client = OpenAI()
Make a streaming API call
stream = client.chat.completions.create( model="gpt-4o-mini", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Write a short poem about AI."} ], stream=True )
Process the streaming response
for chunk in stream: if chunk.choices[0].delta.content is not None: print(chunk.choices[0].delta.content, end="")
```python Function Calling theme={null}
import json
import agentops
from openai import OpenAI
# Initialize AgentOps
agentops.init()
# Create OpenAI client
client = OpenAI()
# Define tools
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather in a given location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA",
}
},
"required": ["location"],
},
},
}
]
# Function implementation
def get_weather(location):
return json.dumps({"location": location, "temperature": "72", "unit": "fahrenheit", "forecast": ["sunny", "windy"]})
# Make a function call API request
messages = [
{"role": "system", "content": "You are a helpful weather assistant."},
{"role": "user", "content": "What's the weather like in Boston?"}
]
response = client.chat.completions.create(
model="gpt-4",
messages=messages,
tools=tools,
tool_choice="auto",
)
# Process response
response_message = response.choices[0].message
messages.append({"role": "assistant", "content": response_message.content, "tool_calls": response_message.tool_calls})
if response_message.tool_calls:
# Process each tool call
for tool_call in response_message.tool_calls:
function_name = tool_call.function.name
function_args = json.loads(tool_call.function.arguments)
if function_name == "get_weather":
function_response = get_weather(function_args.get("location"))
# Add tool response to messages
messages.append(
{
"role": "tool",
"tool_call_id": tool_call.id,
"name": function_name,
"content": function_response,
}
)
# Get a new response from the model
second_response = client.chat.completions.create(
model="gpt-4",
messages=messages,
)
print(second_response.choices[0].message.content)
else:
print(response_message.content)