|
| 1 | +import asyncio |
| 2 | +import json |
| 3 | +import logging |
| 4 | +import os |
| 5 | +import time |
| 6 | +from datetime import datetime |
| 7 | + |
| 8 | +from dotenv import load_dotenv |
| 9 | +from openai import AsyncOpenAI |
| 10 | +from livekit import rtc |
| 11 | +from livekit.plugins import openai, deepgram, silero, cartesia |
| 12 | +from livekit.plugins.turn_detector.multilingual import MultilingualModel |
| 13 | +from livekit.agents import ( |
| 14 | + JobContext, |
| 15 | + WorkerOptions, |
| 16 | + cli, |
| 17 | + ChatContext, |
| 18 | + ChatMessage, |
| 19 | + Agent, |
| 20 | + AgentSession, |
| 21 | +) |
| 22 | + |
| 23 | +from moss import MossClient, DocumentInfo, QueryOptions |
| 24 | + |
| 25 | +load_dotenv() |
| 26 | + |
| 27 | +MOSS_PROJECT_ID = os.getenv("MOSS_PROJECT_ID") |
| 28 | +MOSS_PROJECT_KEY = os.getenv("MOSS_PROJECT_KEY") |
| 29 | +# Long-term, pre-loaded knowledge shared across every call. |
| 30 | +CATALOG_INDEX = os.getenv("TRAVEL_CATALOG_INDEX", "demo-travel-catalog") |
| 31 | + |
| 32 | +# Turns the traveler's raw speech into clean, standalone facts before we store them. |
| 33 | +# Questions, recall requests, and small talk yield no facts, so they never hit the session. |
| 34 | +FACT_EXTRACT_PROMPT = """You pull durable traveler preferences out of one thing the traveler just said on a trip-planning call. |
| 35 | +
|
| 36 | +Return JSON: {"facts": ["...", "..."]}. |
| 37 | +
|
| 38 | +A fact is a short, standalone statement of something true about the traveler or their trip: |
| 39 | +party size, budget, dates, interests, must-haves, or destinations they like or dislike. |
| 40 | +
|
| 41 | +Rules: |
| 42 | +- Only include preferences actually stated in this utterance. |
| 43 | +- Split multiple preferences into separate facts. |
| 44 | +- Drop filler and normalize (e.g. "our budget's around, uh, twenty five hundred a person" -> "Budget is about $2,500 per person"). |
| 45 | +- Keep each fact under about 8 words. |
| 46 | +- Return {"facts": []} for questions, recall requests, or small talk (e.g. "what did I say my budget was?", "so where should we go?").""" |
| 47 | + |
| 48 | +logging.basicConfig(level=logging.INFO) |
| 49 | +logger = logging.getLogger("moss-travel") |
| 50 | + |
| 51 | + |
| 52 | +def _docs(result): |
| 53 | + return [ |
| 54 | + {"id": getattr(d, "id", None), "text": d.text, "score": float(getattr(d, "score", 0.0))} |
| 55 | + for d in (result.docs if result and result.docs else []) |
| 56 | + ] |
| 57 | + |
| 58 | + |
| 59 | +class TravelConciergeAgent(Agent): |
| 60 | + """Answers from two Moss indexes at once: a pre-loaded catalog (long-term) |
| 61 | + and a live session that captures what the traveler says on THIS call.""" |
| 62 | + |
| 63 | + def __init__(self, moss_client: MossClient, session_index, room: rtc.Room): |
| 64 | + super().__init__( |
| 65 | + instructions=""" |
| 66 | + You are a warm, upbeat travel concierge on a voice call with one traveler. |
| 67 | + Each turn you're given two kinds of context: |
| 68 | + 1. Trip options from our catalog. |
| 69 | + 2. What the traveler has told you earlier in THIS call (their preferences). |
| 70 | + Use both: remember what they've said, and recommend trips from the catalog |
| 71 | + that fit. If they ask you to recall something they mentioned, answer from the |
| 72 | + facts in that context. Keep replies short and natural for voice. Never mention |
| 73 | + indexes, sessions, catalogs, or how you look things up. |
| 74 | + """ |
| 75 | + ) |
| 76 | + self.moss = moss_client |
| 77 | + self.session_index = session_index |
| 78 | + self.room = room |
| 79 | + self.turn = 0 |
| 80 | + # Small, fast model used only to distill the traveler's speech into facts. |
| 81 | + self._extractor = AsyncOpenAI() |
| 82 | + |
| 83 | + async def _publish(self, query, catalog, session, catalog_ms, session_ms): |
| 84 | + payload = { |
| 85 | + "query": query, |
| 86 | + "catalog": _docs(catalog), |
| 87 | + "session": _docs(session), |
| 88 | + "catalog_ms": round(catalog_ms, 2), |
| 89 | + "session_ms": round(session_ms, 2), |
| 90 | + } |
| 91 | + try: |
| 92 | + await self.room.local_participant.publish_data( |
| 93 | + json.dumps(payload).encode("utf-8"), reliable=True, topic="moss.retrieval" |
| 94 | + ) |
| 95 | + except Exception as e: |
| 96 | + logger.warning(f"Failed to publish retrieval data: {e}") |
| 97 | + |
| 98 | + async def on_user_turn_completed(self, turn_ctx: ChatContext, new_message: ChatMessage) -> None: |
| 99 | + query = new_message.text_content |
| 100 | + logger.info(f"Traveler: {query}") |
| 101 | + try: |
| 102 | + # 1. Recall prior turns from the live session (short-term memory). |
| 103 | + t = time.perf_counter() |
| 104 | + session_results = await self.session_index.query(query, QueryOptions(top_k=3)) |
| 105 | + session_ms = (time.perf_counter() - t) * 1000.0 |
| 106 | + |
| 107 | + # 2. Look up matching trips in the pre-loaded catalog (long-term knowledge). |
| 108 | + t = time.perf_counter() |
| 109 | + catalog_results = await self.moss.query(CATALOG_INDEX, query, QueryOptions(top_k=3)) |
| 110 | + catalog_ms = (time.perf_counter() - t) * 1000.0 |
| 111 | + |
| 112 | + # 3. Show both in the UI. |
| 113 | + await self._publish(query, catalog_results, session_results, catalog_ms, session_ms) |
| 114 | + |
| 115 | + # 4. Inject both into the model's context, clearly labeled. |
| 116 | + blocks = [] |
| 117 | + if catalog_results.docs: |
| 118 | + blocks.append("Trip options from our catalog:\n" + "\n".join(f"- {d.text}" for d in catalog_results.docs)) |
| 119 | + if session_results.docs: |
| 120 | + blocks.append("Facts the traveler shared earlier in this call:\n" + "\n".join(f"- {d.text}" for d in session_results.docs)) |
| 121 | + if blocks: |
| 122 | + turn_ctx.add_message(role="system", content="\n\n".join(blocks) + "\n\nUse this to help the traveler.") |
| 123 | + |
| 124 | + # 5. Distill this turn into facts and store only those in the live session, in the |
| 125 | + # background so it never delays the reply. Questions/recall add nothing. |
| 126 | + asyncio.create_task(self._remember_facts(query)) |
| 127 | + except Exception as e: |
| 128 | + logger.error(f"Moss lookup failed: {e}", exc_info=True) |
| 129 | + |
| 130 | + await super().on_user_turn_completed(turn_ctx, new_message) |
| 131 | + |
| 132 | + async def _extract_facts(self, text: str) -> list[str]: |
| 133 | + """Pull clean, standalone facts out of one traveler utterance. [] if it states none.""" |
| 134 | + try: |
| 135 | + resp = await self._extractor.chat.completions.create( |
| 136 | + model="gpt-4o-mini", |
| 137 | + temperature=0, |
| 138 | + response_format={"type": "json_object"}, |
| 139 | + messages=[ |
| 140 | + {"role": "system", "content": FACT_EXTRACT_PROMPT}, |
| 141 | + {"role": "user", "content": text}, |
| 142 | + ], |
| 143 | + ) |
| 144 | + data = json.loads(resp.choices[0].message.content or "{}") |
| 145 | + return [f.strip() for f in data.get("facts", []) if isinstance(f, str) and f.strip()] |
| 146 | + except Exception as e: |
| 147 | + logger.warning(f"Fact extraction failed: {e}") |
| 148 | + return [] |
| 149 | + |
| 150 | + async def _remember_facts(self, text: str) -> None: |
| 151 | + for fact in await self._extract_facts(text): |
| 152 | + self.turn += 1 |
| 153 | + try: |
| 154 | + await self.session_index.add_docs( |
| 155 | + [DocumentInfo(id=f"fact-{self.turn}", text=fact, metadata={"role": "traveler"})] |
| 156 | + ) |
| 157 | + logger.info(f"Remembered: {fact}") |
| 158 | + except Exception as e: |
| 159 | + logger.warning(f"Failed to store fact: {e}") |
| 160 | + |
| 161 | + |
| 162 | +async def entrypoint(ctx: JobContext): |
| 163 | + await ctx.connect() |
| 164 | + |
| 165 | + client = MossClient(project_id=MOSS_PROJECT_ID, project_key=MOSS_PROJECT_KEY) |
| 166 | + |
| 167 | + # Long-term: the pre-loaded catalog, shared across all calls. |
| 168 | + try: |
| 169 | + await client.load_index(CATALOG_INDEX) |
| 170 | + logger.info(f"Loaded catalog index: {CATALOG_INDEX}") |
| 171 | + except Exception as e: |
| 172 | + logger.warning(f"Catalog not found ({e}). Run seed_index.py first.") |
| 173 | + |
| 174 | + # Short-term: a fresh, empty session just for this call. |
| 175 | + session_name = f"trip-session-{datetime.now():%Y%m%d-%H%M%S}" |
| 176 | + session_index = await client.session(session_name) |
| 177 | + logger.info(f"Opened live session: {session_name}") |
| 178 | + |
| 179 | + agent = TravelConciergeAgent(client, session_index, ctx.room) |
| 180 | + |
| 181 | + session = AgentSession( |
| 182 | + stt=deepgram.STT(model="nova-2", language="en-US"), |
| 183 | + llm=openai.LLM(model="gpt-4o-mini"), |
| 184 | + tts=cartesia.TTS(model="sonic-turbo", voice="9626c31c-bec5-4cca-baa8-f8ba9e84c8bc"), |
| 185 | + vad=silero.VAD.load(min_silence_duration=0.5, activation_threshold=0.6), |
| 186 | + turn_handling={ |
| 187 | + "turn_detection": MultilingualModel(), |
| 188 | + "endpointing": {"min_delay": 0.5, "max_delay": 1.5}, |
| 189 | + }, |
| 190 | + ) |
| 191 | + |
| 192 | + await session.start(agent=agent, room=ctx.room) |
| 193 | + await session.say( |
| 194 | + "Hi! I'm your travel concierge. Tell me about the trip you're dreaming of and I'll find something.", |
| 195 | + allow_interruptions=True, |
| 196 | + ) |
| 197 | + |
| 198 | + |
| 199 | +if __name__ == "__main__": |
| 200 | + cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint)) |
0 commit comments