-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopenai_stackql_agent.py
More file actions
303 lines (262 loc) · 10.4 KB
/
openai_stackql_agent.py
File metadata and controls
303 lines (262 loc) · 10.4 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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
"""
OpenAI StackQL Agent
Integrates OpenAI's GPT models with StackQL's MCP server for cloud infrastructure intelligence.
"""
import json
from typing import List, Dict, Any, Optional
from openai import OpenAI
from stackql_mcp_client import StackQLMCPClient
class OpenAIStackQLAgent:
"""Agent that uses OpenAI to interact with StackQL via MCP."""
# Define the tools available to OpenAI in OpenAI function calling format
TOOLS = [
{
"type": "function",
"function": {
"name": "greet",
"description": "Test the StackQL MCP connection with a simple greeting",
"parameters": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "The name to greet"
}
},
"required": ["name"]
}
}
},
{
"type": "function",
"function": {
"name": "list_providers",
"description": "List all available StackQL cloud providers (e.g., google, aws, azure, github, okta, etc.)",
"parameters": {
"type": "object",
"properties": {},
"required": []
}
}
},
{
"type": "function",
"function": {
"name": "list_services",
"description": "List services available in a specific cloud provider",
"parameters": {
"type": "object",
"properties": {
"provider": {
"type": "string",
"description": "The provider name (e.g., 'google', 'aws', 'azure')"
}
},
"required": ["provider"]
}
}
},
{
"type": "function",
"function": {
"name": "list_resources",
"description": "List resources available in a provider's service",
"parameters": {
"type": "object",
"properties": {
"provider": {
"type": "string",
"description": "The provider name"
},
"service": {
"type": "string",
"description": "The service name"
}
},
"required": ["provider", "service"]
}
}
},
{
"type": "function",
"function": {
"name": "list_methods",
"description": "List methods available for a specific resource",
"parameters": {
"type": "object",
"properties": {
"provider": {
"type": "string",
"description": "The provider name"
},
"service": {
"type": "string",
"description": "The service name"
},
"resource": {
"type": "string",
"description": "The resource name"
}
},
"required": ["provider", "service", "resource"]
}
}
},
{
"type": "function",
"function": {
"name": "query_stackql",
"description": "Execute a StackQL query to retrieve information about cloud resources. Use SQL-like syntax to query cloud infrastructure across multiple providers.",
"parameters": {
"type": "object",
"properties": {
"sql": {
"type": "string",
"description": "The StackQL query to execute (e.g., 'SELECT * FROM google.compute.instances WHERE project = \"myproject\"')"
}
},
"required": ["sql"]
}
}
}
]
def __init__(self, openai_api_key: str, stackql_mcp_url: str = "http://127.0.0.1:9912", model: str = "gpt-4o-mini"):
"""
Initialize the OpenAI StackQL Agent.
Args:
openai_api_key: OpenAI API key
stackql_mcp_url: URL of the StackQL MCP server
model: OpenAI model to use
"""
self.openai_client = OpenAI(api_key=openai_api_key)
self.stackql_client = StackQLMCPClient(base_url=stackql_mcp_url)
self.model = model
self.conversation_history: List[Dict[str, Any]] = []
def _execute_tool(self, tool_name: str, arguments: Dict[str, Any]) -> str:
"""
Execute a StackQL tool.
Args:
tool_name: Name of the tool to execute
arguments: Tool arguments
Returns:
Tool execution result as a string
"""
try:
if tool_name == "greet":
return self.stackql_client.greet(arguments.get("name", "World"))
elif tool_name == "list_providers":
providers = self.stackql_client.list_providers()
return "\n".join(providers)
elif tool_name == "list_services":
services = self.stackql_client.list_services(arguments["provider"])
return "\n".join(services)
elif tool_name == "list_resources":
resources = self.stackql_client.list_resources(
arguments["provider"],
arguments["service"]
)
return "\n".join(resources)
elif tool_name == "list_methods":
methods = self.stackql_client.list_methods(
arguments["provider"],
arguments["service"],
arguments["resource"]
)
return "\n".join(methods)
elif tool_name == "query_stackql":
return self.stackql_client.query(arguments["sql"])
else:
return f"Unknown tool: {tool_name}"
except Exception as e:
return f"Error executing {tool_name}: {str(e)}"
def chat(self, user_message: str, system_prompt: Optional[str] = None) -> str:
"""
Send a chat message and get a response.
Args:
user_message: The user's message
system_prompt: Optional system prompt to guide the assistant
Returns:
The assistant's response
"""
# Initialize conversation with system prompt if this is the first message
if not self.conversation_history and system_prompt:
self.conversation_history.append({
"role": "system",
"content": system_prompt
})
# Add user message to conversation
self.conversation_history.append({
"role": "user",
"content": user_message
})
max_iterations = 10 # Prevent infinite loops
iteration = 0
while iteration < max_iterations:
iteration += 1
# Get response from OpenAI
response = self.openai_client.chat.completions.create(
model=self.model,
messages=self.conversation_history,
tools=self.TOOLS,
tool_choice="auto"
)
assistant_message = response.choices[0].message
# Add assistant's response to conversation
self.conversation_history.append({
"role": "assistant",
"content": assistant_message.content,
"tool_calls": assistant_message.tool_calls
})
# Check if the assistant wants to call tools
if assistant_message.tool_calls:
# Execute each tool call
for tool_call in assistant_message.tool_calls:
function_name = tool_call.function.name
function_args = json.loads(tool_call.function.arguments)
# Execute the tool
tool_result = self._execute_tool(function_name, function_args)
# Add tool result to conversation
self.conversation_history.append({
"role": "tool",
"tool_call_id": tool_call.id,
"name": function_name,
"content": tool_result
})
# Continue the loop to get the final response
continue
# No more tool calls, return the assistant's message
return assistant_message.content or "I apologize, but I couldn't generate a response."
return "I apologize, but I reached the maximum number of iterations while processing your request."
def reset_conversation(self):
"""Reset the conversation history."""
self.conversation_history = []
def get_conversation_history(self) -> List[Dict[str, Any]]:
"""Get the conversation history."""
return self.conversation_history
if __name__ == "__main__":
import os
from dotenv import load_dotenv
load_dotenv()
# Get API key from environment
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
print("Please set OPENAI_API_KEY environment variable")
exit(1)
# Create agent
agent = OpenAIStackQLAgent(
openai_api_key=api_key,
model="gpt-4o-mini"
)
# Test the agent
system_prompt = """You are a helpful cloud infrastructure assistant powered by StackQL.
You can help users query and analyze their cloud resources across multiple cloud providers including
Google Cloud, AWS, Azure, and many others. Use the available tools to answer questions about
cloud infrastructure, resources, and configurations."""
print("Testing OpenAI StackQL Agent...")
print("-" * 50)
# Test query
response = agent.chat(
"What cloud providers are available?",
system_prompt=system_prompt
)
print(f"Response: {response}")