-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py.backup1
More file actions
249 lines (201 loc) · 8.57 KB
/
client.py.backup1
File metadata and controls
249 lines (201 loc) · 8.57 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
from __future__ import annotations
import asyncio
import os
import traceback
import logging
from typing import Union, Optional
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from mcp_use import MCPAgent, MCPClient
# Načítanie environment variables
load_dotenv()
def setup_detailed_logging():
"""Nastavenie detailného logovania pre sledovanie nástrojov"""
# Vytvorte custom formatter
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
# Nastavte hlavný logger
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
# Nastavte špecifické loggery
logger = logging.getLogger("mcp_use")
logger.setLevel(logging.DEBUG)
# Znížte HTTP logy aby neboli príliš hlučné
logging.getLogger("httpx").setLevel(logging.WARNING)
return logger
class ToolTracker:
"""Trieda pre sledovanie volaní nástrojov"""
def __init__(self, agent):
self.agent = agent
self.tool_calls = []
async def run_with_tracking(self, user_input, **kwargs):
"""Spustenie agenta s detailným sledovaním nástrojov"""
print(f"\n🔍 [TRACKER] Začínam sledovanie nástrojov...")
# Zobrazenie dostupných nástrojov
if hasattr(self.agent, '_tools') and self.agent._tools:
tool_names = [tool.name for tool in self.agent._tools]
print(f"🔧 [TRACKER] Dostupné nástroje ({len(tool_names)}): {tool_names}")
# Zobrazenie detailov o nástrojoch
for tool in self.agent._tools:
print(f" 📝 {tool.name}: {tool.description if hasattr(tool, 'description') else 'Bez popisu'}")
else:
print("❌ [TRACKER] Agent nemá dostupné nástroje!")
print(f"🚀 [TRACKER] Spúšťam agent...")
# Spustenie agenta
result = await self.agent.run(user_input, **kwargs)
print(f"✅ [TRACKER] Agent dokončil spracovanie")
return result
async def main():
# Nastavenie detailného logovania
logger = setup_detailed_logging()
config = {
"mcpServers": {
"wordpress_server": {
"url": os.getenv("MCP_BASE_URL"),
"headers": {
"Authorization": f"Bearer {os.getenv('JWT_TOKEN')}",
"Content-Type": "application/json"
}
}
}
}
# Vytvorenie MCP klienta
client = MCPClient.from_dict(config)
# Explicitné vytvorenie sessions s error handlingom
print("🔍 Vytváram MCP sessions...")
try:
sessions = await client.create_all_sessions()
print(f"✅ Vytvorené sessions: {list(sessions.keys())}")
# Overenie dostupných nástrojov
for name, session in sessions.items():
tools = session.connector.tools
print(f"🔧 Server '{name}' má {len(tools)} nástrojov")
# Zobrazenie názvov nástrojov
if tools:
tool_names = [tool.name for tool in tools]
print(f" 📝 Nástroje: {tool_names}")
except Exception as e:
print(f"❌ Chyba pri vytváraní sessions: {e}")
traceback.print_exc()
return
# Vytvorenie OpenAI LLM
llm = ChatOpenAI(
model="gpt-4o",
api_key=os.getenv("OPENAI_API_KEY")
)
# Vytvorenie MCP agenta s explicitným error handlingom
print("🔍 Vytváram MCPAgent...")
try:
agent = MCPAgent(
llm=llm,
client=client,
max_steps=15,
memory_enabled=True,
auto_initialize=False # Nepovoliť auto-init kvôli chybe
)
print("✅ MCPAgent vytvorený")
# Manuálna inicializácia s detailným logovaním
print("🔍 Inicializujem agent...")
await agent.initialize()
print("✅ Agent inicializovaný")
# Overenie či má agent _tools atribút
if hasattr(agent, '_tools'):
print(f"✅ Agent má _tools: {len(agent._tools) if agent._tools else 0}")
# Zobrazenie detailov o nástrojoch
if agent._tools:
print("📝 Detaily nástrojov:")
for i, tool in enumerate(agent._tools, 1):
print(f" {i}. {tool.name}")
if hasattr(tool, 'description'):
print(f" 📖 {tool.description}")
if hasattr(tool, 'input_schema'):
print(f" 🔧 Schema: {tool.input_schema}")
else:
print("❌ Agent nemá _tools atribút!")
return
except Exception as e:
print(f"❌ Chyba pri vytváraní/inicializácii agenta: {e}")
traceback.print_exc()
return
# Vytvorenie tool trackera
tracker = ToolTracker(agent)
print("\n🚀 WordPress MCP Chat Bot spustený!")
print("💬 Napíšte 'exit' pre ukončenie chatu")
print("🔧 Môžete sa pýtať na WordPress funkcie, nástroje, príspevky, atď.")
print("🐛 Napíšte 'debug' pre debug informácie")
print("📋 Napíšte 'tools' pre zobrazenie dostupných nástrojov")
print("-" * 60)
try:
# Hlavný chat loop s detailným error handlingom
while True:
user_input = input("\n👤 Vy: ").strip()
# Rozšírená validácia vstupu
if not user_input or user_input.isspace():
print("⚠️ Zadajte prosím platnú otázku alebo 'exit' pre ukončenie.")
continue
if user_input.lower() in ['exit', 'quit', 'bye', 'koniec']:
print("\n👋 Ďakujem za rozhovor! Chat ukončený.")
break
if user_input.lower() in ['clear', 'reset', 'vymazat']:
if hasattr(agent, 'clear_conversation_history'):
agent.clear_conversation_history()
print("🧹 História konverzácie vymazaná.")
else:
print("⚠️ Clear history nie je dostupné")
continue
# Debug info pred spustením
if user_input.lower() == 'debug':
print(f"🔍 Debug info:")
print(f" - Agent má _tools: {hasattr(agent, '_tools')}")
print(f" - Agent._tools je: {type(getattr(agent, '_tools', None))}")
print(f" - Počet nástrojov: {len(getattr(agent, '_tools', []))}")
print(f" - Client sessions: {len(client.sessions)}")
print(f" - Sessions keys: {list(client.sessions.keys())}")
continue
# Zobrazenie dostupných nástrojov
if user_input.lower() == 'tools':
if hasattr(agent, '_tools') and agent._tools:
print(f"🔧 Dostupné nástroje ({len(agent._tools)}):")
for i, tool in enumerate(agent._tools, 1):
print(f" {i}. {tool.name}")
if hasattr(tool, 'description'):
print(f" 📖 {tool.description}")
else:
print("❌ Žiadne nástroje nie sú dostupné")
continue
print("\n🤖 Bot: ", end="", flush=True)
try:
# Overenie pred spustením
if not hasattr(agent, '_tools') or agent._tools is None:
print("\n❌ Agent nemá inicializované nástroje!")
continue
# Spustenie s detailným sledovaním
result = await tracker.run_with_tracking(
user_input,
manage_connector=False # Connector už je vytvorený
)
print(result)
except Exception as e:
print(f"\n❌ Chyba pri spracovaní otázky: {e}")
print(f"📝 Typ chyby: {type(e).__name__}")
print("\n🔍 Úplný traceback:")
traceback.print_exc()
print("\n🔄 Skúste to znovu alebo zadajte inú otázku.")
except KeyboardInterrupt:
print("\n\n⚠️ Chat prerušený používateľom (Ctrl+C)")
except Exception as e:
print(f"\n❌ Neočakávaná chyba: {e}")
traceback.print_exc()
finally:
print("\n🧹 Zatváram spojenia...")
try:
if client.sessions:
await client.close_all_sessions()
print("✅ Spojenia zatvorené.")
except Exception as e:
print(f"⚠️ Chyba pri zatváraní: {e}")
if __name__ == "__main__":
asyncio.run(main())