-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
160 lines (131 loc) · 5.32 KB
/
client.py
File metadata and controls
160 lines (131 loc) · 5.32 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
from __future__ import annotations
import asyncio
import os
import traceback
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()
async def main():
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")
except Exception as e:
print(f"❌ Chyba pri vytváraní sessions: {e}")
traceback.print_exc()
return
# Vytvorenie OpenAI LLM
llm = ChatOpenAI(
model="gpt-4.1",
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}")
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
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("-" * 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)}")
continue
print("\n🤖 Bot: ", end="", flush=True)
try:
# Detailné logovanie pred agent.run
print(f"[DEBUG] Spúšťam agent.run s inputom: '{user_input[:50]}...'")
# Overenie pred spustením
if not hasattr(agent, '_tools') or agent._tools is None:
print("\n❌ Agent nemá inicializované nástroje!")
continue
result = await agent.run(
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())