-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
143 lines (113 loc) · 5.29 KB
/
main.py
File metadata and controls
143 lines (113 loc) · 5.29 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
from agents import Agent, Runner, SQLiteSession
from agents import AsyncOpenAI, set_default_openai_client, set_tracing_disabled, set_default_openai_api
from mcpserver_manager import MCPServerManager
from dotenv import load_dotenv
import asyncio
import os
load_dotenv()
gemini_api_key = os.environ.get("GEMINI_API_KEY")
set_tracing_disabled(True)
set_default_openai_api("chat_completions")
external_client = AsyncOpenAI(
api_key=gemini_api_key,
base_url="https://generativelanguage.googleapis.com/v1beta/openai/",
)
set_default_openai_client(external_client)
# Simple retry function for agent runs
async def run_with_retry(agent, user_input, session, max_retries=2):
for attempt in range(1, max_retries + 1):
try:
return await Runner.run(
starting_agent=agent, input=user_input, session=session
)
except Exception as e:
if attempt == max_retries:
print(f"\n❌ Error: {str(e)}")
return None
print(f"\n⚠️ Retrying... (attempt {attempt}/{max_retries})")
await asyncio.sleep(1) # Simple 1-second delay between retries
return None
async def main():
# Custom MCP Server Configs with explicit tool filtering
# Mostly matches standard MCP server config options
# Added `allowed_tools` and `cache_tools_list` specific to OpenAI Agents implementation
servers_config = {
# Github MCP server configuration
"github": {
"url": "https://api.githubcopilot.com/mcp",
"headers": {"Authorization": f'Bearer {os.environ.get("GITHUB_TOKEN")}'},
# "allowed_tools": ["search_repositories", "search_users", "get_me"],
"transport": "http",
"cache_tools_list": True,
},
# Add more server configs as needed
}
async with MCPServerManager(servers_config) as server_instances:
# Print the names of the servers that were started
print(f"Servers started: {list(server_instances.keys())}")
# Create an agent with optimized configuration
agent = Agent(
name="OpenAI + MCPs Agent",
instructions=(
"""
instructions=(
"You are a senior software engineer and GitHub expert operating through the GitHub MCP server.\n\n"
"Your primary responsibility is to help the user explore, understand, analyze, and work with GitHub data "
"using MCP tools as the FIRST and PREFERRED source of truth.\n\n"
"You have access to ALL tools exposed by the GitHub MCP server. You are allowed and encouraged to use "
"any available MCP tool whenever it can help answer the user’s request.\n\n"
"Core rules you MUST follow:\n"
"1. Always use MCP tools for GitHub-related tasks instead of guessing or using prior knowledge.\n"
"2. Never hallucinate repositories, users, issues, commits, or files.\n"
"3. If information is missing, unclear, or ambiguous, ask a clear follow-up question.\n"
"4. Prefer MCP tools over external APIs or assumptions.\n"
"5. Think step-by-step before calling a tool.\n\n"
"When working with repositories:\n"
"- Search repositories when the repo name is not exact.\n"
"- Inspect repository metadata before making conclusions.\n"
"- Explain findings clearly and simply.\n\n"
"When working with users or organizations:\n"
"- Use MCP tools to fetch verified user data.\n"
"- Do not assume ownership or permissions.\n\n"
"When the user asks for analysis:\n"
"- First gather data using MCP tools.\n"
"- Then analyze logically.\n"
"- Finally present results in a structured, easy-to-read way.\n\n"
"Response style:\n"
"- Clear and concise\n"
"- Beginner-friendly explanations\n"
"- Use bullet points or steps where helpful\n"
"- No unnecessary verbosity\n\n"
"If a request is not related to GitHub or cannot be solved using MCP tools:\n"
"- Clearly explain the limitation\n"
"- Offer the closest helpful alternative\n\n"
"Your goal is to behave like a reliable GitHub assistant that never guesses, always verifies, "
"and uses MCP tools intelligently."
)
"""
),
mcp_servers=list(server_instances.values()),
model=os.environ.get("GEMINI_MODEL"),
)
# Create a session to manage memory
# NOTE: If you have 2+ sessions running, session memory will error out with Github's MCP server
session = SQLiteSession("MCP Conversation history")
print("\nType your request (or 'exit' to quit):")
# Start an interactive session
while True:
try:
user_input = input("👶 You: ").strip()
if user_input.lower() in {"exit", "quit"}:
print("Exiting interactive session.")
break
# Replace with `await Runner.run(starting_agent=agent, input=user_input, session=session)` to go without simple retry
result = await run_with_retry(agent, user_input, session)
if result:
print(f"\n🤖 Agent: {result.final_output}\n")
except KeyboardInterrupt:
print("\n👋 Goodbye!")
break
except Exception as e:
print(f"\n❌ Error: {str(e)}")
if __name__ == "__main__":
asyncio.run(main())