|
| 1 | +import json |
| 2 | +import os |
| 3 | + |
| 4 | +from mcp import ClientSession |
| 5 | +from openai import OpenAI |
| 6 | + |
| 7 | +MODEL = "gpt-4o-mini" |
| 8 | +MAX_TOKENS = 1000 |
| 9 | + |
| 10 | + |
| 11 | +class OpenAIQueryHandler: |
| 12 | + """Handle OpenAI API interaction and MCP tool execution.""" |
| 13 | + |
| 14 | + def __init__(self, client_session: ClientSession): |
| 15 | + self.client_session = client_session |
| 16 | + if not (api_key := os.getenv("OPENAI_API_KEY")): |
| 17 | + raise RuntimeError( |
| 18 | + "Error: OPENAI_API_KEY environment variable not set", |
| 19 | + ) |
| 20 | + self.openai = OpenAI(api_key=api_key) |
| 21 | + |
| 22 | + async def process_query(self, query: str) -> str: |
| 23 | + """Process a query using OpenAI and available MCP tools.""" |
| 24 | + # Get initial Model's response and decision on tool calls |
| 25 | + messages = [{"role": "user", "content": query}] |
| 26 | + initial_response = self.openai.chat.completions.create( |
| 27 | + model=MODEL, |
| 28 | + max_tokens=MAX_TOKENS, |
| 29 | + messages=messages, |
| 30 | + tools=await self._get_tools(), |
| 31 | + ) |
| 32 | + |
| 33 | + current_message = initial_response.choices[0].message |
| 34 | + result_parts = [] |
| 35 | + |
| 36 | + if current_message.content: |
| 37 | + result_parts.append(current_message.content) |
| 38 | + |
| 39 | + # Handle tool usage if present |
| 40 | + if tool_calls := current_message.tool_calls: |
| 41 | + messages.append( |
| 42 | + { |
| 43 | + "role": "assistant", |
| 44 | + "content": current_message.content or "", |
| 45 | + "tool_calls": tool_calls, |
| 46 | + } |
| 47 | + ) |
| 48 | + |
| 49 | + # Execute tools |
| 50 | + for tool_call in tool_calls: |
| 51 | + tool_result = await self._execute_tool(tool_call) |
| 52 | + result_parts.append(tool_result["log"]) |
| 53 | + messages.append(tool_result["message"]) |
| 54 | + |
| 55 | + # Get final Model's response after tool execution |
| 56 | + final_response = self.openai.chat.completions.create( |
| 57 | + model=MODEL, |
| 58 | + max_tokens=MAX_TOKENS, |
| 59 | + messages=messages, |
| 60 | + ) |
| 61 | + |
| 62 | + if content := final_response.choices[0].message.content: |
| 63 | + result_parts.append(content) |
| 64 | + |
| 65 | + return "Assistant: " + "\n".join(result_parts) |
| 66 | + |
| 67 | + async def _get_tools(self) -> list: |
| 68 | + """Get MCP tools formatted for OpenAI.""" |
| 69 | + response = await self.client_session.list_tools() |
| 70 | + return [ |
| 71 | + { |
| 72 | + "type": "function", |
| 73 | + "function": { |
| 74 | + "name": tool.name, |
| 75 | + "description": tool.description or "No description", |
| 76 | + "parameters": getattr( |
| 77 | + tool, |
| 78 | + "inputSchema", |
| 79 | + {"type": "object", "properties": {}}, |
| 80 | + ), |
| 81 | + }, |
| 82 | + } |
| 83 | + for tool in response.tools |
| 84 | + ] |
| 85 | + |
| 86 | + async def _execute_tool(self, tool_call) -> dict: |
| 87 | + """Execute an MCP tool call and return formatted result.""" |
| 88 | + tool_name = tool_call.function.name |
| 89 | + tool_args = json.loads(tool_call.function.arguments or "{}") |
| 90 | + |
| 91 | + try: |
| 92 | + result = await self.client_session.call_tool(tool_name, tool_args) |
| 93 | + content = result.content[0].text if result.content else "" |
| 94 | + log = f"[Used {tool_name}({tool_args})]" |
| 95 | + except Exception as e: |
| 96 | + content = f"Error: {e}" |
| 97 | + log = f"[{content}]" |
| 98 | + |
| 99 | + return { |
| 100 | + "log": log, |
| 101 | + "message": { |
| 102 | + "role": "tool", |
| 103 | + "tool_call_id": tool_call.id, |
| 104 | + "content": content, |
| 105 | + }, |
| 106 | + } |
0 commit comments