prehistoric-alligator-43413
11/24/2025, 3:32 PMtall-airline-16756
11/24/2025, 3:32 PMtall-airline-16756
11/24/2025, 3:32 PMknowledge_base.json in your project.
b. Load at startup (before ctx.connect()): in Python use `json.load(...)`; in Node.js use fs.readFileSync(...) or require(...).
c. Use the loaded object in your agent logic or caching layer.
• Fetch JSON from an external URL (best if KB updates often)
a. Fetch with `aiohttp`/`requests` (Python) or `fetch`/`axios` (Node.js).
b. Cache results in memory and refresh on a schedule to avoid latency during calls.
c. Ensure the runtime allows outbound HTTP.
• Pass relevant KB via job metadata (best for small, per-job context)
a. Include JSON (or a JSON string) in job.metadata when dispatching the job.
b. Inside the agent read ctx.job.metadata and json.loads(...) (or JSON.parse(...)).
c. Use for personalization or small snippets rather than full KBs.
• Integrate into a RAG flow (best for querying large KBs for relevant snippets)
a. Implement a search function over your JSON (e.g., keyword/embedding search).
b. On user turns, find relevant snippets and inject them into the chat context before LLM generation (e.g., turn_ctx.add_message(...)).
c. Load/search the KB before ctx.connect() or ensure async fetch is efficient.
If you want, I can:
• Provide a short Python or Node.js code snippet for the option you choose.
• Show an example of a simple search function for RAG integration.
• Suggest caching/refresh strategies for external KBs.
Which option and language should I show you?
Sources: Job lifecycle | LiveKit docs | External data and RAG | LiveKit Docsprehistoric-alligator-43413
11/24/2025, 3:37 PMtall-airline-16756
11/24/2025, 3:37 PMctx.connect() so runtime requests read from memory, not disk or network.
• Keep it lightweight in memory: 48 KB is small; a parsed JSON object is fine to hold in RAM.
• Index for fast lookup: build a simple map (by id or keyword) or an in-memory inverted index so queries are O(1) or O(log n) instead of scanning the whole array.
• Async background refresh (if KB updates): fetch and swap the in-memory object on a timer to avoid blocking request handling.
• RAG for relevance (optional): for longer KBs, create embeddings and a vector index and only retrieve few relevant passages to inject into LLM prompts — reduces compute and prompt size.
• Avoid per-request file I/O or long synchronous operations: always serve reads from the cached in-memory structure.
Concise patterns
• Preload + cache (recommended for 48 KB)
◦ Load file or remote JSON once at startup.
◦ Keep as a module/global variable or attach to server context.
◦ Use fast lookups (maps) for query paths.
• Background refresh
◦ Periodic async task to fetch and replace cache.
◦ Swap atomically to avoid partial reads.
• Simple indexing example ideas
◦ Map by id: { id -> entry }
◦ Inverted index for keywords: { keyword -> [entry_ids] }
◦ For semantic search, generate embeddings and use a small vector index (Annoy/HNSW/FAISS).
If you want, I’ll provide a compact Python or Node.js example showing: 1) preload + in-memory map, 2) async background refresh, 3) a tiny search function for query lookup.
Which language would you like?prehistoric-alligator-43413
11/24/2025, 3:38 PMtall-airline-16756
11/24/2025, 3:38 PMprehistoric-alligator-43413
11/24/2025, 3:39 PMtall-airline-16756
11/24/2025, 3:40 PMid, name, price, tags, and description).
import asyncio
import json
import aiohttp
from typing import Dict, List, Set
# Global cache + index
KB: List[Dict] = [] # list of items
KB_BY_ID: Dict[str, Dict] = {} # id -> item
INVERTED: Dict[str, Set[str]] = {} # token -> set(item_id)
KB_FILE = "knowledge_base.json" # local fallback
KB_URL = "https://example.com/kb.json" # remote source for refresh
REFRESH_INTERVAL = 60 # seconds
def tokenize(text: str) -> Set[str]:
text = (text or "").lower()
tokens = set(t for t in text.replace("/", " ").replace(",", " ").split() if len(t) > 1)
return tokens
def build_indexes(kb: List[Dict]):
by_id = {}
inv: Dict[str, Set[str]] = {}
for item in kb:
item_id = str(item.get("id") or item.get("name"))
by_id[item_id] = item
# index name, tags, and description
fields = [item.get("name", ""), item.get("description", "")]
fields += item.get("tags", []) or []
for f in fields:
for tok in tokenize(str(f)):
inv.setdefault(tok, set()).add(item_id)
return by_id, inv
def load_local_kb() -> List[Dict]:
with open(KB_FILE, "r", encoding="utf-8") as f:
return json.load(f)
async def fetch_remote_kb(session: aiohttp.ClientSession) -> List[Dict]:
async with session.get(KB_URL, timeout=10) as resp:
resp.raise_for_status()
return await resp.json()
async def background_refresher():
global KB, KB_BY_ID, INVERTED
async with aiohttp.ClientSession() as session:
while True:
try:
new_kb = await fetch_remote_kb(session)
except Exception:
# on failure, keep existing KB; try again later
await asyncio.sleep(REFRESH_INTERVAL)
continue
# build new indexes off-thread (cheap for 48 KB)
new_by_id, new_inv = build_indexes(new_kb)
# atomic swap
KB, KB_BY_ID, INVERTED = new_kb, new_by_id, new_inv
await asyncio.sleep(REFRESH_INTERVAL)
# Call this once at startup, before handling requests / before ctx.connect()
def preload_kb():
global KB, KB_BY_ID, INVERTED
try:
kb = load_local_kb()
except Exception:
kb = [] # fallback to empty
KB = kb
KB_BY_ID, INVERTED = build_indexes(KB)
# Example fast lookup functions used by your agent
def get_item_by_id(item_id: str) -> Dict:
return KB_BY_ID.get(item_id)
def search_items(query: str, max_results: int = 10) -> List[Dict]:
toks = tokenize(query)
if not toks:
return []
# find intersection of token result sets (simple AND)
result_ids = None
for t in toks:
ids = INVERTED.get(t, set())
result_ids = ids if result_ids is None else (result_ids & ids)
if not result_ids:
# fallback: union of tokens
result_ids = set().union(*(INVERTED.get(t, set()) for t in toks))
results = [KB_BY_ID[i] for i in list(result_ids)[:max_results]]
return results
# Example integration with LiveKit agent server lifecycle:
# 1) Preload at startup
preload_kb()
# 2) Start background refresher (run in event loop)
asyncio.create_task(background_refresher())
# 3) Use get_item_by_id() or search_items() inside your agent handler to respond quickly.
Notes and best practices:
• 48 KB is small; parsing + in-memory structures are cheap and fast.
• Preload before serving requests so handlers read from RAM (no disk/network blocking).
• Atomic swap of the entire cache avoids partial reads during refresh.
• Refresh interval can be tuned (e.g., 30–300s). If updates are frequent, reduce interval; if rare, increase it.
• For stronger search, replace the simple token index with embeddings + small vector store; for 48 KB this is optional.
Would you like a trimmed version tailored to your LiveKit agent handler showing where to call get_item_by_id or search_items inside @server.rtc_session()?
Sources: Agent server options | LiveKit docs | External data and RAG | LiveKit Docsprehistoric-alligator-43413
11/24/2025, 3:42 PMtall-airline-16756
11/24/2025, 3:42 PMprehistoric-alligator-43413
11/24/2025, 4:03 PMtall-airline-16756
11/24/2025, 4:04 PMimport asyncio
import json
from typing import Dict, List, Set
import motor.motor_asyncio # async MongoDB driver
# Globals (same shapes as before)
KB: List[Dict] = []
KB_BY_ID: Dict[str, Dict] = {}
INVERTED: Dict[str, Set[str]] = {}
MONGO_URI = "mongodb://localhost:27017"
MONGO_DB = "restaurant_db"
MONGO_COLL = "menu_items"
REFRESH_INTERVAL = 60 # seconds
# --- tokenization & index builders (same as earlier) ---
def tokenize(text: str) -> Set[str]:
text = (text or "").lower()
tokens = set(t for t in text.replace("/", " ").replace(",", " ").split() if len(t) > 1)
return tokens
def build_indexes(kb: List[Dict]):
by_id = {}
inv: Dict[str, Set[str]] = {}
for item in kb:
item_id = str(item.get("id") or item.get("_id") or item.get("name"))
by_id[item_id] = item
fields = [item.get("name", ""), item.get("description", "")]
fields += item.get("tags", []) or []
for f in fields:
for tok in tokenize(str(f)):
inv.setdefault(tok, set()).add(item_id)
return by_id, inv
# --- MongoDB access helpers ---
mongo_client = motor.motor_asyncio.AsyncIOMotorClient(MONGO_URI)
mongo_coll = mongo_client[MONGO_DB][MONGO_COLL]
async def fetch_kb_from_mongo() -> List[Dict]:
# Adjust projection if you want to skip large fields
cursor = mongo_coll.find({}, projection={"_id": 1, "name": 1, "price": 1, "tags": 1, "description": 1})
docs = await cursor.to_list(length=None) # load all matching docs
# normalize _id to string if needed
for d in docs:
if "_id" in d:
d["id"] = str(d["_id"])
return docs
# --- preload at startup (call before handling requests) ---
async def preload_kb_from_mongo():
global KB, KB_BY_ID, INVERTED
try:
kb = await fetch_kb_from_mongo()
except Exception:
kb = []
KB = kb
KB_BY_ID, INVERTED = build_indexes(KB)
# --- background refresher using Mongo ---
async def background_refresher_mongo():
global KB, KB_BY_ID, INVERTED
while True:
try:
new_kb = await fetch_kb_from_mongo()
new_by_id, new_inv = build_indexes(new_kb)
KB, KB_BY_ID, INVERTED = new_kb, new_by_id, new_inv # atomic swap
except Exception:
# keep existing cache on error
pass
await asyncio.sleep(REFRESH_INTERVAL)
# --- lookup functions (same as before) ---
def get_item_by_id(item_id: str) -> Dict:
return KB_BY_ID.get(item_id)
def search_items(query: str, max_results: int = 10) -> List[Dict]:
toks = tokenize(query)
if not toks:
return []
result_ids = None
for t in toks:
ids = INVERTED.get(t, set())
result_ids = ids if result_ids is None else (result_ids & ids)
if not result_ids:
result_ids = set().union(*(INVERTED.get(t, set()) for t in toks))
results = [KB_BY_ID[i] for i in list(result_ids)[:max_results]]
return results
# --- startup integration ---
# In your agent startup (before ctx.connect()), run:
# await preload_kb_from_mongo()
# and schedule the background refresher:
# asyncio.create_task(background_refresher_mongo())
# Then inside your agent handlers use get_item_by_id() and search_items() for low-latency responses.
Notes:
• Using Motor (motor.motor_asyncio) avoids blocking the event loop.
• Projection reduces data transferred if documents have extra fields.
• to_list(length=None) loads all results; for extremely large collections page or limit appropriately.
• Tune REFRESH_INTERVAL based on update frequency.
• If you need near-real-time updates, consider a MongoDB change stream to drive updates instead of polling. Would you like an example using change streams?prehistoric-alligator-43413
11/24/2025, 5:26 PMtall-airline-16756
11/24/2025, 5:26 PMprehistoric-alligator-43413
11/24/2025, 6:14 PMtall-airline-16756
11/24/2025, 6:15 PMFunctionContext was removed — don't import it. Define and register tools instead. Below are concise, copy‑paste-ready examples showing:
1) How to define tools with @function_tool and access your cached KB, and 2) How to run a MongoDB change stream that applies per-document updates to your in-memory cache (atomic, non-blocking) — integrate both into your LiveKit agent entrypoint.
Pick whichever part to copy; both are shown to work together.
1) Tools via @function_tool (no FunctionContext)
from livekit.agents import Agent
from livekit.agents.llm import function_tool
from livekit.agents.voice import AgentSession
from typing import List, Dict
# global cache populated elsewhere
KB_BY_ID: Dict[str, Dict] = {}
INVERTED: Dict[str, set] = {}
@function_tool()
async def get_item_by_id(item_id: str) -> Dict:
return KB_BY_ID.get(item_id)
@function_tool()
async def search_items(query: str, max_results: int = 10) -> List[Dict]:
# simple tokenized search using INVERTED/KB_BY_ID
toks = set(t.lower() for t in query.split() if len(t) > 1)
if not toks:
return []
result_ids = None
for t in toks:
ids = INVERTED.get(t, set())
result_ids = ids if result_ids is None else (result_ids & ids)
if not result_ids:
result_ids = set().union(*(INVERTED.get(t, set()) for t in toks))
return [KB_BY_ID[i] for i in list(result_ids)[:max_results]]
class RestaurantAssistant(Agent):
def __init__(self) -> None:
super().__init__(
instructions="You are a restaurant assistant. Use tools to answer menu queries."
)
Notes:
• Tools decorated with @function_tool() are auto-registered and callable by the LLM flow.
• Alternatively, you can pass tool callables via Agent(..., tools=[get_item_by_id, search_items]) if you prefer.
2) MongoDB change stream to update cache in real time (Motor)
import asyncio
from typing import Dict, List, Set
import motor.motor_asyncio
from bson import ObjectId
MONGO_URI = "mongodb://localhost:27017"
MONGO_DB = "restaurant_db"
MONGO_COLL = "menu_items"
# in-memory cache structures
KB_BY_ID: Dict[str, Dict] = {}
INVERTED: Dict[str, Set[str]] = {}
def tokenize(text: str) -> Set[str]:
text = (text or "").lower()
tokens = set(t for t in text.replace("/", " ").replace(",", " ").split() if len(t) > 1)
return tokens
def index_item(item: Dict):
item_id = str(item.get("id") or item.get("_id") or item.get("name"))
KB_BY_ID[item_id] = item
# remove previous tokens for this id from INVERTED (safe no-op if absent)
for tok, ids in list(INVERTED.items()):
ids.discard(item_id)
if not ids:
INVERTED.pop(tok, None)
# add tokens
fields = [item.get("name", ""), item.get("description", "")]
fields += item.get("tags", []) or []
for f in fields:
for tok in tokenize(str(f)):
INVERTED.setdefault(tok, set()).add(item_id)
def remove_item(item_id: str):
if item_id in KB_BY_ID:
KB_BY_ID.pop(item_id)
for tok, ids in list(INVERTED.items()):
ids.discard(item_id)
if not ids:
INVERTED.pop(tok, None)
async def initial_load(mongo_coll):
docs = await mongo_coll.find({}, projection={"_id": 1, "name": 1, "price": 1, "tags": 1, "description": 1}).to_list(length=None)
KB_BY_ID.clear()
INVERTED.clear()
for d in docs:
# normalize id
if "_id" in d:
d["id"] = str(d["_id"])
index_item(d)
async def watch_changes():
client = motor.motor_asyncio.AsyncIOMotorClient(MONGO_URI)
db = client[MONGO_DB]
coll = db[MONGO_COLL]
# initial load
await initial_load(coll)
# use change stream (requires replica set / Atlas)
async with coll.watch(full_document='updateLookup') as stream:
async for change in stream:
op = change.get("operationType")
if op == "insert":
doc = change.get("fullDocument")
if doc:
if "_id" in doc: doc["id"] = str(doc["_id"])
index_item(doc)
elif op == "replace" or op == "update":
doc = change.get("fullDocument")
if doc:
if "_id" in doc: doc["id"] = str(doc["_id"])
index_item(doc)
elif op == "delete":
doc_id = change.get("documentKey", {}).get("_id")
if doc_id:
remove_item(str(doc_id))
# other ops ignored; on error you can fall back to initial_load()
Integration into LiveKit agent entrypoint
from livekit.agents.server import server
from livekit.agents.server.job import JobContext
@server.rtc_session()
async def entrypoint(ctx: JobContext):
# start change stream watcher in background (non-blocking)
asyncio.create_task(watch_changes())
# build/start your agent session using RestaurantAssistant()
session = AgentSession(...) # configure as needed
agent = RestaurantAssistant()
await session.start(agent, ctx.room, ctx.agent)
Troubleshooting tips
• Ensure your MongoDB supports change streams (replica set or Atlas); otherwise watch() raises an error.
• If running multiple agent instances, each instance will receive change events — make sure that's acceptable or coordinate via a single updater process.
• If change streams aren't available, use the polling refresher (earlier snippet) as a fallback.
• Do not import `FunctionContext`; migrate to @function_tool or tools=.
If you want, I can:
• Provide a full single-file example showing preload, change stream, and an agent handler with tool usage, or
• Show a fallback polling refresher snippet integrated with same tool definitions.
Which would you prefer?
Sources: Agents v0.x migration guide - Node.js | LiveKit Docs