-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathagent.py
More file actions
1525 lines (1340 loc) · 65.6 KB
/
Copy pathagent.py
File metadata and controls
1525 lines (1340 loc) · 65.6 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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# import suppress_warnings # Must be first to suppress warnings
"""Travel assistant agent integrating Mem0 long-term memory, Redis-backed chat
history, Tavily web search, and simple calendar (.ics) generation.
This module defines the `TravelAgent` used by the Gradio UI:
- Per-user memory via Mem0 with Redis storage and retrieval
- Two scoped web search tools (logistics vs general) powered by Tavily
- A small sanitizer wrapper for OpenAI tool-call message ordering
- Streaming chat utilities that surface structured UI events for the side panel
"""
import warnings
warnings.filterwarnings("ignore")
import os
import sys
import asyncio
import json
import re
import traceback
from dataclasses import dataclass
from datetime import datetime, timezone, timedelta
from pathlib import Path
from typing import Any, Dict, List, Optional, AsyncGenerator
import re
import hashlib
from queue import Queue
# ------------------------------
# Global debugging helpers: always print full tracebacks
# ------------------------------
def _global_excepthook(exc_type, exc_value, exc_traceback):
try:
if issubclass(exc_type, KeyboardInterrupt):
return sys.__excepthook__(exc_type, exc_value, exc_traceback)
print("\ud83d\udea9 Unhandled exception in agent.py", flush=True)
traceback.print_exception(exc_type, exc_value, exc_traceback)
except Exception:
pass
def _asyncio_exception_handler(loop, context):
try:
msg = context.get("message")
exc = context.get("exception")
if msg:
print(f"\ud83d\udea9 Unhandled asyncio exception: {msg}", flush=True)
else:
print("\ud83d\udea9 Unhandled asyncio exception", flush=True)
if exc:
traceback.print_exception(type(exc), exc, getattr(exc, "__traceback__", None))
except Exception:
pass
try:
sys.excepthook = _global_excepthook # type: ignore[assignment]
try:
loop = asyncio.get_event_loop()
loop.set_exception_handler(_asyncio_exception_handler)
except Exception:
pass
except Exception:
pass
from tavily import TavilyClient
from ics import Calendar, Event, DisplayAlarm
from ics.grammar.parse import ContentLine
# Agent Framework imports
from agent_framework.azure import AzureOpenAIResponsesClient
from agent_framework import ChatMessage, Role, TextContent
from agent_framework import FunctionCallContent, FunctionResultContent
from agent_framework._middleware import agent_middleware, AgentRunContext
from agent_framework._tools import ai_function
from agent_framework_mem0 import Mem0Provider
from agent_framework_redis._chat_message_store import RedisChatMessageStore
from agent_framework.exceptions import ServiceResponseException
from mem0 import AsyncMemoryClient, AsyncMemory
from mem0.configs.base import MemoryConfig
from config import AppConfig
from utils.ui_events import emit_ui_event
class NonBlockingMem0Provider(Mem0Provider):
"""Mem0 provider that performs post-invoke add in the background.
Uses the framework's invoked hook to capture messages and schedules the
Mem0 add on a background task so streaming isn't blocked.
"""
async def invoked(self, request_messages, response_messages=None, invoke_exception=None, **kwargs): # type: ignore[override]
try:
asyncio.create_task(super().invoked(request_messages, response_messages, invoke_exception, **kwargs))
except Exception:
# Best-effort: background scheduling failed; don't block user flow
pass
async def invoking(self, messages, **kwargs): # type: ignore[override]
# Retrieve context from base provider, then truncate to keep token usage bounded
ctx = await super().invoking(messages, **kwargs)
try:
MAX_LINES = 12
MAX_CHARS = 2000
if not ctx:
return ctx
txt_parts = []
# Prefer messages content if present (Mem0Provider uses messages field)
try:
for m in list(getattr(ctx, "messages", []) or []):
t = getattr(m, "text", None)
if t:
txt_parts.append(t)
except Exception:
pass
full_text = "\n".join([p for p in txt_parts if p])
if not full_text:
return ctx
lines = [ln for ln in full_text.splitlines() if ln.strip()]
trimmed = "\n".join(lines[:MAX_LINES])
if len(trimmed) > MAX_CHARS:
trimmed = trimmed[:MAX_CHARS] + "…"
from agent_framework import ChatMessage # local import to avoid top-level cycles
new_msg = ChatMessage(role="user", text=trimmed)
from agent_framework import Context # type: ignore
return Context(messages=[new_msg]) if trimmed else ctx
except Exception:
return ctx
class _SanitizingChatMessageStore:
"""Wrapper for `RedisChatMessageStore` that enforces OpenAI tool-call ordering.
Why this exists
OpenAI expects any tool (role="tool") messages to be preceded by an
assistant message that declared the corresponding tool call(s). Some SDKs and
UIs may write tool results without the matching assistant call IDs, which can
cause API errors. This wrapper sanitizes history to avoid that.
Behavior
- Drops leading tool-role messages.
- Filters tool results (`FunctionResultContent`) whose `call_id` does not
match any prior assistant `FunctionCallContent` in the conversation.
"""
def __init__(self, inner_store: RedisChatMessageStore) -> None:
self._inner = inner_store
async def list_messages(self) -> List[ChatMessage]:
raw = await self._inner.list_messages()
return self._sanitize_messages(raw)
async def add_messages(self, messages: List[ChatMessage]) -> None:
await self._inner.add_messages(messages)
async def serialize(self, **kwargs: Any) -> Any:
return await self._inner.serialize(**kwargs)
@classmethod
async def deserialize(cls, serialized_store_state: Any, **kwargs: Any) -> "_SanitizingChatMessageStore":
inner = await RedisChatMessageStore.deserialize(serialized_store_state, **kwargs)
return cls(inner)
async def update_from_state(self, serialized_store_state: Any, **kwargs: Any) -> None:
await self._inner.update_from_state(serialized_store_state, **kwargs)
async def clear(self) -> None:
await self._inner.clear()
def _sanitize_messages(self, messages: List[ChatMessage]) -> List[ChatMessage]:
"""Return messages pruned to a sequence valid for OpenAI tool-calls."""
if not messages:
return []
# 1) Drop leading tool-role messages
start_idx = 0
for i, m in enumerate(messages):
role_val = m.role.value if hasattr(m.role, "value") else str(m.role)
if role_val != "tool":
start_idx = i
break
else:
return []
msgs = messages[start_idx:]
# 2) Track valid tool call ids from preceding assistant messages
valid_call_ids: set[str] = set()
sanitized: List[ChatMessage] = []
for m in msgs:
role_val = m.role.value if hasattr(m.role, "value") else str(m.role)
if role_val == "assistant":
for c in m.contents:
if isinstance(c, FunctionCallContent) and getattr(c, "call_id", None):
valid_call_ids.add(c.call_id)
sanitized.append(m)
continue
if role_val == "tool":
filtered_contents = [
c for c in m.contents
if isinstance(c, FunctionResultContent) and getattr(c, "call_id", None) in valid_call_ids
]
if filtered_contents:
sanitized.append(
ChatMessage(
role=m.role,
contents=filtered_contents,
author_name=m.author_name,
message_id=m.message_id,
additional_properties=m.additional_properties,
raw_representation=m.raw_representation,
)
)
continue
sanitized.append(m)
return sanitized
@dataclass
class UserCtx:
"""User-specific context containing Mem0 provider and agent instances.
Attributes:
mem0_provider: Mem0 provider instance for user-specific memory management
agent: Main chat agent with tools and memory integration
"""
mem0_provider: Mem0Provider
agent: Any
class TravelAgent:
"""Travel planning agent with Mem0-powered personalized memory capabilities.
This agent provides personalized travel planning services by maintaining
separate Mem0 memory contexts for each user. Each user gets their own Mem0
memory instance and supervisor agent that are cached for performance.
Features:
- Per-user memory isolation using Mem0 with Redis backend
- Semantic memory search and retrieval via Mem0
- Web search integration for current travel information
- Chat history management with configurable buffer sizes
- Automatic memory extraction and personalized recommendations
Attributes:
- config: Application configuration containing API keys and model settings
- tavily_client: Web search client for travel information
- chat_client: OpenAI client that creates the chat agent
"""
def __init__(self, config: Optional[AppConfig] = None):
"""Initialize the TravelAgent with configuration and shared resources.
Args:
config: Application configuration. If None, loads default config.
"""
if config is None:
from config import get_config
config = get_config()
self.config = config
# Set environment variables for SDK clients
os.environ["OPENAI_API_KEY"] = config.azure_openai_api_key
os.environ["TAVILY_API_KEY"] = config.tavily_api_key
# Azure OpenAI specific
os.environ["AZURE_OPENAI_API_KEY"] = config.azure_openai_api_key
os.environ["AZURE_OPENAI_ENDPOINT"] = config.azure_openai_endpoint
os.environ["AZURE_OPENAI_API_VERSION"] = config.azure_openai_api_version
# Also set OpenAI v1 compatibility vars for libraries expecting base_url/version
os.environ["OPENAI_API_VERSION"] = config.openai_api_version
os.environ["OPENAI_BASE_URL"] = config.azure_openai_base_url or (config.azure_openai_endpoint.rstrip("/") + "/openai/v1")
try:
os.environ["MEM0_API_KEY"] = config.MEM0_API_KEY
except Exception:
pass
# Initialize shared clients
self.tavily_client = TavilyClient(api_key=config.tavily_api_key)
self.chat_client = AzureOpenAIResponsesClient(
endpoint=config.azure_openai_endpoint,
deployment_name=config.travel_agent_model,
api_version=config.azure_openai_api_version,
api_key=config.azure_openai_api_key
)
# Initialize user context cache
self._user_ctx_cache = {}
async def initialize_seed_data(self) -> None:
"""Initialize seed users with their memories. Call this after creating the agent."""
await self._init_seed_users()
# ------------------------------
# User Context Management
# ------------------------------
def _create_mem0_provider(self, user_id: str) -> Mem0Provider:
"""Create a Mem0 provider instance bound to a specific user/thread."""
print(f"🧠 Creating Mem0 provider for user: {user_id}")
mem0_client = self._build_mem0_client()
return NonBlockingMem0Provider(
user_id=user_id,
thread_id=f"user:{user_id}",
context_prompt=(
"Relevant durable traveler facts and preferences (use to personalize replies):"
),
mem0_client=mem0_client,
)
def _build_mem0_client(self):
"""Create a Mem0 client according to configuration (cloud vs local)."""
if getattr(self.config, "mem0_cloud", False):
# Mem0 Cloud
return AsyncMemoryClient(api_key=self.config.MEM0_API_KEY)
# Local Mem0 with Redis vector store
cfg = {
"vector_store": {
"provider": "redis",
"config": {
"collection_name": "mem0",
"embedding_model_dims": self.config.mem0_embedding_model_dims,
"redis_url": self.config.redis_url
}
},
"embedder": {
"provider": "azure_openai",
"config": {
"model": self.config.mem0_embedding_model
}
},
"llm": {
"provider": "azure_openai",
"config": {
"model": self.config.mem0_model
}
}
}
mem_cfg = MemoryConfig(**cfg)
return AsyncMemory(config=mem_cfg)
def _get_or_create_user_ctx(self, user_id: str) -> UserCtx:
"""Return a cached or new `UserCtx` with memory, agent, and history store.
Creates and caches a complete user context including Mem0 memory,
chat history management, and supervisor agent.
Args:
user_id: Unique identifier for the user
Returns:
UserCtx: Complete user context with Mem0 memory initialized
"""
if user_ctx := self._user_ctx_cache.get(user_id):
return user_ctx
# Create Mem0 provider instance
mem0_provider = self._create_mem0_provider(user_id)
# Prepare Redis chat message store factory bound to user thread id
def _store_factory() -> RedisChatMessageStore:
base = RedisChatMessageStore(
redis_url=self.config.redis_url,
thread_id=f"{user_id}",
key_prefix="chat_messages",
max_messages=self.config.max_chat_history_size,
)
# Wrap with sanitizer so history is valid for OpenAI
return _SanitizingChatMessageStore(base) # type: ignore[return-value]
# Create chat agent with tools, context provider, and Redis-backed history
agent = self._create_agent(
user_id=user_id,
mem0_provider=mem0_provider,
chat_message_store_factory=_store_factory,
)
# Provide minimal model_context adapter for UI clear()
class _ModelContextAdapter:
def __init__(self, redis_url: str, thread_id: str):
base = RedisChatMessageStore(
redis_url=redis_url,
thread_id=thread_id,
key_prefix="chat_messages",
max_messages=self.config.max_chat_history_size,
)
self._store = _SanitizingChatMessageStore(base)
async def clear(self) -> None:
await self._store.clear()
# Attach adapter to agent for backward compatibility with UI
try:
setattr(agent, "model_context", _ModelContextAdapter(self.config.redis_url, f"user:{user_id}"))
except Exception:
pass
# Cache and return user context
self._user_ctx_cache[user_id] = UserCtx(
mem0_provider=mem0_provider,
agent=agent,
)
return self._user_ctx_cache[user_id]
def _load_seed_data(self) -> Dict[str, Any]:
"""Load seed data from `context/seed.json` adjacent to this module."""
seed_file = Path(__file__).parent / "context" / "seed.json"
with open(seed_file, 'r', encoding='utf-8') as f:
return json.load(f)
def get_all_user_ids(self) -> List[str]:
"""Return a unified list of user IDs from currently cached contexts."""
return self._user_ctx_cache.keys()
async def _init_seed_users(self) -> None:
"""Initialize seed users by inserting their memories into Mem0."""
seed_data = self._load_seed_data()
user_memories = seed_data.get("user_memories", {})
for user_id, memories in user_memories.items():
try:
ctx = self._get_or_create_user_ctx(str(user_id))
print(f"🌱 Seeding memory for user: {user_id}")
for memo in memories:
try:
await ctx.mem0_provider.mem0_client.add(
messages=[{"role": "user", "content": memo.get("insight", "")}],
user_id=str(user_id),
run_id=ctx.mem0_provider.thread_id,
metadata={"source": "seed"},
)
except Exception as _e:
print(f" ⚠️ Skipping seed entry due to error: {_e}")
print(f"✅ Seeded {len(memories)} memories via Mem0 for user: {user_id}")
except Exception as e:
print(f"❌ Failed to seed memory for user {user_id}: {e}")
try:
traceback.print_exc()
except Exception:
pass
continue
def _create_agent(
self,
*,
user_id: str,
mem0_provider: Mem0Provider,
chat_message_store_factory,
) -> Any:
"""Create the chat agent with tools, Mem0 context, and Redis-backed history."""
print("🤖 Creating ChatAgent with tools...", flush=True)
try:
agent = self.chat_client.create_agent(
name="agent",
instructions=self._get_system_message(),
tools=self._get_tools(),
chat_message_store_factory=chat_message_store_factory,
context_providers=mem0_provider,
)
print("✅ ChatAgent created successfully", flush=True)
return agent
except Exception as e:
print(f"❌ Failed to create ChatAgent: {e}", flush=True)
print(f" Full traceback: {traceback.format_exc()}", flush=True)
raise
def _get_tools(self) -> List[Any]:
"""Return the list of tool-callable functions exposed to the agent."""
tools: List[Any] = []
tools.append(
ai_function(
self.search_logistics,
name="search_logistics",
description=(
"Time-aware logistics search ONLY: flights, hotels, and intercity/local transport. "
"Use for availability, schedules, prices, carriers/properties, or routes. "
"Arguments: query (required), start_date (optional, YYYY-MM-DD), end_date (optional, YYYY-MM-DD). "
"Always include dates when the user mentions a travel window; if ambiguous, ask for dates before booking guidance. "
"NEVER use this for activities, attractions, neighborhoods, or dining. "
"Results are restricted to reputable flight/hotel/transport sources; top URLs are deeply extracted."
),
)
)
tools.append(
ai_function(
self.search_general,
name="search_general",
description=(
"Time-aware destination research: activities, attractions, neighborhoods, dining, events, local tips. "
"Use for up-to-date things to do, cultural context, and planning inspiration. "
"Arguments: query (required). "
"Scope searches to the relevant season/year when possible and prefer recent sources. "
"NEVER use this for flights, hotels, or transport logistics. "
"Example: 'things to do in Lisbon in June 2026'."
),
)
)
tools.append(
ai_function(
self.generate_calendar_ics,
name="generate_calendar_ics",
description=(
"📅 Generate a downloadable calendar file (.ics) from a simple travel itinerary. "
"Use when you have a finalized schedule with dates and times. "
"Arguments: either events (array) OR a single event via title+date; plus trip_name (optional). "
"Single event fields: title, date (YYYY-MM-DD), start_time (optional), end_time (optional), location (optional), notes (optional). "
"Examples: date='2026-06-05', start_time='14:30', end_time='16:00'. "
"Returns file_path for user to open."
),
)
)
tools.append(
ai_function(
self.testing_tool_call,
name="testing_tool_call",
description=(
"Diagnostic tool to verify tool-calling and UI event rendering. "
"Emits progress updates and a final result."
),
)
)
print(f"🏁 Tool creation complete. {len(tools)} tools ready.", flush=True)
return tools
def _get_system_message(self) -> str:
"""Return the supervisor system message with roles, tool guidance, and style."""
today = datetime.utcnow().strftime("%Y-%m-%d")
return (
f"You are an expert, time-aware, friendly Travel Concierge AI. Today is {today} (UTC). Always be aware that this is the current date and time."
"Assume your built in knowledge may be outdated; for anything time-sensitive, verify with tools.\n\n"
"ROLE:\n"
"- Discover destinations, plan itineraries, recommend accommodations, and organize logistics on behalf of the user.\n"
"- Research current options, prices, availability, and on-the-ground activities using your tools.\n"
"- Produce clear, actionable itineraries and booking guidance.\n"
"- Regardless of your prior knowledge, always use search tools for current or future-state information.\n\n"
"TOOL USAGE: You have access to the following helpful tools.\n"
"- Use search_logistics ONLY for flights, hotels, or transport. Include start_date/end_date (YYYY-MM-DD) when known.\n"
"- Use search_general for activities, attractions, neighborhoods, dining, events, or local tips. Include dates when relevant.\n"
"- Use generate_calendar_ics when you have a finalized itinerary. Pass simple events array with title, date, optional times/location/notes.\n"
"- Use testing_tool_call when the user asks you to verify tool calling capability or to run a diagnostic test.\n"
"- Prefer recent sources (past 12–24 months) and pass explicit dates to tools whenever the user provides a time window.\n"
"DISCOVERY:\n"
"- Lead with leading questions to discover user's likes, dislikes, travel-related preferences, and more.\n"
"- These can be related to flights, hotels, locations, dates, seasons, types of activities, etc...\n"
"- If missing details, ask targeted questions (exact dates or window, origin/destination, budget, party size, interests,\n"
" lodging preferences, accessibility, loyalty programs).\n\n"
"OUTPUT STYLE:\n"
"- Be concise and prescriptive with your suggestions, followups, and recommendations.\n"
"- Seek to be the best and friendliest travel agent possible. You are the expert after all.\n"
"- Cite sources with titles and URLs for any tool-based claim.\n"
"- Normalize to a single currency if prices appear; state assumptions.\n"
"- For itineraries, list day-by-day with times and logistics.\n\n"
"MEMORY:\n"
"- Consider any appended important insights (long-term memory) from the user before answering and adapt to them.\n"
"- Consider any relevant memories as helpful context but treat current session state as priority since it's current."
)
async def testing_tool_call(
self,
message: Optional[str] = None,
steps: int = 5,
delay_ms: int = 250,
) -> Dict[str, Any]:
"""🧪 Emit a series of progress logs to validate tool-calling and UI event rendering.
Args:
message: Optional message to include in logs
steps: Number of progress steps to emit
delay_ms: Delay in milliseconds between steps
Returns:
Dict containing a simple success payload
"""
txt = (message or "Running diagnostic").strip()
emit_ui_event("tool_log", "🧪", "testing_tool_call", f"start: {txt}")
print(f"🔧 TEST TOOL: start - {txt}", flush=True)
steps = max(1, min(steps, 50))
delay = max(0, delay_ms) / 1000.0
for i in range(1, steps + 1):
pct = int(i * 100 / steps)
msg = f"step {i}/{steps} ({pct}%)"
# Structured UI event for reliable rendering
emit_ui_event("tool_log", "🧪", "testing_tool_call", msg, progress=pct)
# Plain log line fallback
print(f"🧪 TEST TOOL: {msg}", flush=True)
try:
await asyncio.sleep(delay)
except Exception:
pass
emit_ui_event("tool_result", "🧪", "testing_tool_call finished", "success")
print("✅ TEST TOOL: complete", flush=True)
return {"status": "ok", "steps": steps, "message": txt}
# -----------------
# Tools
# -----------------
def _perform_search(
self,
query: str,
search_type: str,
include_domains: Optional[List[str]] = None,
start_date: Optional[str] = None,
end_date: Optional[str] = None,
) -> Dict[str, Any]:
"""Shared search logic with optional URL extraction.
Args:
query: Search query
search_type: "logistics" or "general" for logging
include_domains: Optional domain restrictions
start_date: Optional start date for query enhancement
end_date: Optional end date for query enhancement
Returns:
Dictionary with results and extractions
"""
title = f"{search_type.upper()} SEARCH"
# print(f"🔧 {title}: {query}", flush=True)
try:
emit_ui_event("tool_log", "🔧", title, query)
except Exception:
pass
try:
# Augment query with dates if provided
enhanced_query = query
if start_date:
enhanced_query += f" from {start_date}"
if end_date and end_date != start_date:
enhanced_query += f" to {end_date}"
search_kwargs = {
"query": enhanced_query,
"topic": "general",
"search_depth": "advanced",
"max_results": self.config.max_search_results,
}
if include_domains:
search_kwargs["include_domains"] = include_domains
results = self.tavily_client.search(**search_kwargs)
if not results:
print(f"⚠️ Empty results from Tavily", flush=True)
return {"results": [], "extractions": []}
# Filter results by score
all_results = results.get("results", [])
filtered_results = [r for r in all_results if r.get("score", 0) > 0.2]
found_msg = f"Found {len(filtered_results)}/{len(all_results)} quality results"
# print(f"📊 {found_msg}", flush=True)
try:
emit_ui_event("tool_log", "📊", title, found_msg, results=len(filtered_results), total=len(all_results))
except Exception:
pass
results["results"] = filtered_results
# Extract top 2 URLs for deeper context
top_urls = [r.get("url") for r in filtered_results[:2] if r.get("url")]
extractions: List[Dict[str, Any]] = []
if top_urls:
try:
extracted = self.tavily_client.extract(urls=top_urls)
if isinstance(extracted, dict) and extracted.get("results"):
extractions = extracted.get("results", [])
elif isinstance(extracted, list):
extractions = extracted
extract_msg = f"Extracted {len(extractions)} content blocks"
# print(f"📄 {extract_msg}", flush=True)
try:
emit_ui_event("tool_log", "📄", title, extract_msg, extractions=len(extractions))
except Exception:
pass
except Exception as extract_e:
print(f"⚠️ URL extraction failed: {extract_e}", flush=True)
results["extractions"] = extractions
complete_msg = f"{len(filtered_results)} results + {len(extractions)} extractions"
# print(f"✅ {title} COMPLETE: {complete_msg}", flush=True)
try:
emit_ui_event("tool_result", "✅", f"{title} finished", complete_msg, results=len(filtered_results), extractions=len(extractions))
except Exception:
pass
return results
except Exception as e:
error_msg = f"❌ {search_type.upper()} ERROR: {str(e)}"
print(error_msg, flush=True)
try:
traceback.print_exc()
except Exception:
pass
try:
emit_ui_event("tool_log", "❌", f"{title} error", str(e))
except Exception:
pass
return {"error": error_msg, "results": [], "extractions": []}
async def search_logistics(
self,
query: str,
start_date: Optional[str] = None,
end_date: Optional[str] = None,
) -> Dict[str, Any]:
"""✈️🏨🚆 Logistics search: flights, hotels, and transport only.
What it is for
- Airfare and airline schedules, hotels/stays, and intercity transport (train/bus/ferry/car rental).
How to use
- Provide a concise query that includes the route or destination and constraints, e.g.:
"JFK to LHR, nonstop preferred" or "hotels in Kyoto near Gion, mid-range" or "train Paris to Amsterdam".
- Optionally include start_date and end_date as YYYY-MM-DD strings to guide availability windows.
Behavior
- Restricts sources to reputable flight/hotel/transport providers and aggregators.
- Returns the strongest matches first and deeply extracts the top URLs for rich context.
"""
include_domains = [
# Flights / OTAs
"expedia.com", "kayak.com", "travel.google.com",
# Hotels / stays
"booking.com", "hotels.com",
]
return await asyncio.to_thread(
self._perform_search,
query,
"logistics",
include_domains,
start_date,
end_date,
)
async def search_general(
self,
query: str,
) -> Dict[str, Any]:
"""📍 General destination research: activities, attractions, neighborhoods, dining, events.
What it is for
- Up-to-date things to do, local highlights, neighborhoods to stay, dining ideas, and cultural context.
How to use
- Provide a destination/time-focused query, e.g., "things to do in Lisbon in June",
"Barcelona food tours", "best neighborhoods to stay in Tokyo".
Behavior
- Runs an open web search (no logistics domains restriction) with raw content for context.
"""
# print(f"🔧 {general} SEARCH: {query}", flush=True)
return await asyncio.to_thread(
self._perform_search,
query,
"general",
None,
None,
None,
)
async def generate_calendar_ics(
self,
events: Optional[List[Dict[str, Any]]] = None,
trip_name: Optional[str] = None,
title: Optional[str] = None,
date: Optional[str] = None,
start_time: Optional[str] = None,
end_time: Optional[str] = None,
location: Optional[str] = None,
notes: Optional[str] = None,
) -> Dict[str, Any]:
"""📅 Generate a simple .ics calendar file from travel events (non-blocking)."""
def _generate_calendar_ics_sync() -> Dict[str, Any]:
print(f"🔧 CALENDAR GENERATION: Creating simple .ics file", flush=True)
try:
emit_ui_event("tool_log", "🔧", "generate_calendar_ics", "Creating .ics file")
except Exception:
pass
try:
_events = events
if not _events:
if title and date:
single_event: Dict[str, Any] = {
"title": title,
"date": date,
}
if start_time:
single_event["start_time"] = start_time
if end_time:
single_event["end_time"] = end_time
if location:
single_event["location"] = location
if notes:
single_event["notes"] = notes
_events = [single_event]
else:
return {"error": "No events provided", "file_path": None, "events_count": 0}
calendar = Calendar()
calendar.extra.append(ContentLine("X-WR-CALNAME", value=trip_name or "Travel Itinerary"))
user_id = getattr(self, '_current_user_id', 'default')
for event_data in _events:
event = self._create_simple_event(event_data, user_id)
if event:
calendar.events.add(event)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
safe_name = re.sub(r'[^\w\-_]', '_', (trip_name or 'itinerary'))[:30]
filename = f"{timestamp}_{safe_name}.ics"
calendar_dir = Path(__file__).parent / "assets" / "calendars" / user_id
calendar_dir.mkdir(parents=True, exist_ok=True)
file_path = calendar_dir / filename
with open(file_path, 'w', encoding='utf-8') as f:
f.write(str(calendar))
print(f"✅ CALENDAR COMPLETE: {len(_events)} events in {filename}", flush=True)
try:
emit_ui_event(
"tool_result",
"✅",
"generate_calendar_ics finished",
f"{len(_events)} events in {filename}",
file_path=str(file_path.absolute()),
filename=filename,
events_count=len(_events),
)
except Exception:
pass
return {
"file_path": str(file_path.absolute()),
"filename": filename,
"events_count": len(_events)
}
except Exception as e:
error_msg = f"❌ CALENDAR ERROR: {str(e)}"
print(error_msg, flush=True)
try:
traceback.print_exc()
except Exception:
pass
try:
emit_ui_event("tool_log", "❌", "generate_calendar_ics error", str(e))
except Exception:
pass
return {"error": error_msg, "file_path": None, "events_count": 0}
return await asyncio.to_thread(_generate_calendar_ics_sync)
def _create_simple_event(self, event_data: Dict[str, Any], user_id: str) -> Optional[Event]:
"""Create a simple ICS event from basic event data.
Args:
event_data: Dict with title, date, optional start_time/end_time/location/notes
user_id: User ID for UID generation
Returns:
Event object or None if creation failed
"""
try:
title = event_data.get("title", "").strip()
date_str = event_data.get("date", "").strip()
if not title or not date_str:
print(f" ⚠️ Skipping event: missing title or date", flush=True)
return None
event = Event()
event.name = title
# Parse date (YYYY-MM-DD format)
event_date = datetime.fromisoformat(date_str).date()
# Check if we have times
start_time = event_data.get("start_time", "").strip()
end_time = event_data.get("end_time", "").strip()
if start_time:
# Timed event
start_hour, start_min = map(int, start_time.split(':'))
event.begin = datetime.combine(event_date, datetime.min.time().replace(hour=start_hour, minute=start_min))
if end_time:
end_hour, end_min = map(int, end_time.split(':'))
event.end = datetime.combine(event_date, datetime.min.time().replace(hour=end_hour, minute=end_min))
else:
# Default 1 hour duration
event.end = event.begin + timedelta(hours=1)
# Add default reminder for timed events (30 minutes before)
alarm = DisplayAlarm()
alarm.trigger = event.begin - timedelta(minutes=30)
alarm.description = f"Reminder: {title}"
event.alarms.append(alarm)
else:
# All-day event
event.begin = event_date
event.make_all_day()
# Add optional fields
if location := event_data.get("location", "").strip():
event.location = location
if notes := event_data.get("notes", "").strip():
event.description = notes
# Simple UID
uid_source = f"{user_id}:{title}:{date_str}:{start_time}"
uid_hash = hashlib.md5(uid_source.encode()).hexdigest()[:12]
event.uid = f"{uid_hash}@travel-agent"
return event
except Exception as e:
print(f" ⚠️ Event creation failed: {e}", flush=True)
try:
traceback.print_exc()
except Exception:
pass
return None
# -----------------
# Chat and Memory Interface
# -----------------
async def stream_chat_turn_with_events(self, user_id: str, user_message: str) -> AsyncGenerator[tuple[str, dict | None], None]:
"""
Yield (growing assistant reply, normalized event | None) pairs as the agent streams.
Uses Agent Framework middleware to robustly detect and tag events on streaming updates.
"""
# ------------------------------
# Capture stdout/stderr prints as live UI events (start early)
# Use a thread-safe Queue because tools may run in worker threads
# ------------------------------
log_queue: Queue[str | None] = Queue()
class _StreamTee:
def __init__(self, original_stream, queue: Queue[str | None]):
self._original = original_stream
self._queue = queue
self._buffer = ""
def write(self, data: str) -> int:
# First, capture lines to the async UI queue so UI isn't blocked by original sink buffering
self._buffer += data
while "\n" in self._buffer:
line, self._buffer = self._buffer.split("\n", 1)
line = line.strip()
if line:
try:
self._queue.put_nowait(line)
except Exception:
pass
# Then, mirror to the original stream best-effort
try:
written = self._original.write(data)
try:
self._original.flush()
except Exception:
pass
except Exception:
written = len(data)
return written
def flush(self) -> None:
try:
self._original.flush()
except Exception:
pass
original_stdout = sys.stdout
original_stderr = sys.stderr
sys.stdout = _StreamTee(original_stdout, log_queue) # type: ignore[assignment]
sys.stderr = _StreamTee(original_stderr, log_queue) # type: ignore[assignment]
ctx = self._get_or_create_user_ctx(user_id)
# Store current user ID for calendar generation
self._current_user_id = user_id