-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopenai-function-calling.py
More file actions
195 lines (170 loc) · 6.56 KB
/
openai-function-calling.py
File metadata and controls
195 lines (170 loc) · 6.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
"""
OpenAI Function Calling with Frostbyte APIs
============================================
Give your GPT-4 agent real-world tools: IP geolocation, crypto prices,
DNS lookups, screenshots, web scraping, and code execution.
Requirements:
pip install openai requests
Usage:
export FROSTBYTE_API_KEY="your-key" # Get free: https://ozorown.github.io
export OPENAI_API_KEY="sk-..."
python openai-function-calling.py
"""
import json
import os
import requests
from openai import OpenAI
FROSTBYTE_BASE = "https://api-catalog-three.vercel.app/v1"
API_KEY = os.environ.get("FROSTBYTE_API_KEY", "")
# --- Tool implementations ---
def geo_lookup(ip: str) -> dict:
"""Look up IP geolocation data."""
r = requests.get(f"{FROSTBYTE_BASE}/agent-geo/geo/{ip}",
headers={"Authorization": f"Bearer {API_KEY}"})
return r.json()
def crypto_price(symbol: str) -> dict:
"""Get current cryptocurrency price."""
r = requests.get(f"{FROSTBYTE_BASE}/crypto-feeds/prices/{symbol}",
headers={"Authorization": f"Bearer {API_KEY}"})
return r.json()
def dns_lookup(domain: str) -> dict:
"""Resolve DNS records for a domain."""
r = requests.get(f"{FROSTBYTE_BASE}/agent-dns/api/resolve/{domain}",
headers={"Authorization": f"Bearer {API_KEY}"})
return r.json()
def scrape_url(url: str) -> dict:
"""Scrape a webpage and extract text content."""
r = requests.post(f"{FROSTBYTE_BASE}/agent-scraper/api/scrape",
headers={"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"},
json={"url": url})
return r.json()
def run_code(language: str, code: str) -> dict:
"""Execute code in a sandboxed environment."""
r = requests.post(f"{FROSTBYTE_BASE}/agent-coderunner/api/execute",
headers={"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"},
json={"language": language, "code": code})
return r.json()
# --- OpenAI tool definitions ---
TOOLS = [
{
"type": "function",
"function": {
"name": "geo_lookup",
"description": "Look up geolocation data for an IP address (country, city, ISP, coordinates)",
"parameters": {
"type": "object",
"properties": {
"ip": {"type": "string", "description": "IP address to look up (e.g. '8.8.8.8')"}
},
"required": ["ip"]
}
}
},
{
"type": "function",
"function": {
"name": "crypto_price",
"description": "Get current price, 24h change, and market cap for a cryptocurrency",
"parameters": {
"type": "object",
"properties": {
"symbol": {"type": "string", "description": "Crypto symbol (e.g. 'bitcoin', 'ethereum', 'solana')"}
},
"required": ["symbol"]
}
}
},
{
"type": "function",
"function": {
"name": "dns_lookup",
"description": "Resolve DNS records (A, AAAA, MX, NS, TXT) for a domain",
"parameters": {
"type": "object",
"properties": {
"domain": {"type": "string", "description": "Domain name (e.g. 'google.com')"}
},
"required": ["domain"]
}
}
},
{
"type": "function",
"function": {
"name": "scrape_url",
"description": "Scrape a webpage and extract its text content, title, and metadata",
"parameters": {
"type": "object",
"properties": {
"url": {"type": "string", "description": "Full URL to scrape (e.g. 'https://example.com')"}
},
"required": ["url"]
}
}
},
{
"type": "function",
"function": {
"name": "run_code",
"description": "Execute code in a sandboxed environment. Supports python3, javascript, bash, and more.",
"parameters": {
"type": "object",
"properties": {
"language": {"type": "string", "description": "Programming language (python3, javascript, bash)"},
"code": {"type": "string", "description": "Code to execute"}
},
"required": ["language", "code"]
}
}
}
]
# Map function names to implementations
TOOL_MAP = {
"geo_lookup": geo_lookup,
"crypto_price": crypto_price,
"dns_lookup": dns_lookup,
"scrape_url": scrape_url,
"run_code": run_code,
}
def run_agent(user_message: str):
"""Run an OpenAI agent with Frostbyte tools."""
client = OpenAI()
messages = [
{"role": "system", "content": "You are a helpful assistant with access to real-time tools for IP geolocation, crypto prices, DNS lookups, web scraping, and code execution. Use tools when needed to answer questions accurately."},
{"role": "user", "content": user_message}
]
print(f"\nUser: {user_message}")
print("-" * 50)
while True:
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=TOOLS,
)
choice = response.choices[0]
if choice.finish_reason == "tool_calls":
messages.append(choice.message)
for tool_call in choice.message.tool_calls:
fn_name = tool_call.function.name
fn_args = json.loads(tool_call.function.arguments)
print(f" -> Calling {fn_name}({fn_args})")
result = TOOL_MAP[fn_name](**fn_args)
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": json.dumps(result)
})
else:
print(f"\nAssistant: {choice.message.content}")
return choice.message.content
if __name__ == "__main__":
if not API_KEY:
print("Get a free API key: https://ozorown.github.io")
print("Then: export FROSTBYTE_API_KEY='your-key'")
exit(1)
# Example queries that demonstrate the tools
run_agent("Where is the IP address 8.8.8.8 located, and what are the DNS records for google.com?")
print("\n" + "=" * 60 + "\n")
run_agent("What's the current price of Bitcoin and Ethereum? Calculate the BTC/ETH ratio using code execution.")