i have my knowledge base in json format, how can i...
# ask-ai
p
i have my knowledge base in json format, how can i access that within my livekit agent?
t
Thanks for reaching out, Vaneeza. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking how to use a JSON knowledge base inside your LiveKit agent — here are the practical options and when to use each. Which approach do you want to implement (local file, external fetch, job metadata, or RAG)? If you tell me that, I can give a concise code example for your environment (Python or Node.js). Options: • Load JSON file locally (best for static or large KB deployed with the agent) a. Include
knowledge_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 Docs
p
the json file is big 48kb which has the knowledge base. So how would the agent be able to load that and answer questions based on that without latency?
t
Thanks — you can load 48 KB without noticeable latency if you use the right approach. Below are practical, low-friction options; tell me which language (Python or Node.js) and I’ll give a short snippet. Key strategies • Preload at startup and cache in memory: load the JSON before
ctx.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?
p
im using python. and my knowledge base for a restaurant, containing its menu, different items, prices and tags etc.
t
Thanks — I'll show a concise Python pattern you can drop into your LiveKit agent to preload a 48 KB restaurant JSON, keep it in memory, provide fast lookups by item name and tags, and optionally refresh in the background without blocking requests. Which of these do you want in the example? • Plain preload + in-memory map (fast exact lookups) • Preload + simple inverted-index for tag/keyword search (fast partial lookups) • Add background async refresh from a remote URL Pick one and I’ll provide the short code snippet.
p
3rd one
t
Below is a concise Python example you can drop into your LiveKit agent. It preloads a 48 KB restaurant JSON file into memory before the session starts, builds a simple inverted index for tag/keyword lookups, and runs an async background refresh that fetches an updated JSON from a remote URL on a timer and swaps the cache atomically to avoid blocking requests. Change the paths/URL and adapt the search logic to your JSON structure (assumes each menu item has
id
,
name
,
price
,
tags
, and
description
).
Copy code
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 Docs
p
why cant i do rag for this?
t
Good question — short answer: you can use RAG, but for a 48 KB structured restaurant menu it’s usually unnecessary and adds complexity and latency. Here’s why, and when RAG still makes sense. Why RAG is often unnecessary for your case • 48 KB is small: you can load and search the whole JSON in memory very quickly, giving near-instant responses with exact lookups or a simple inverted index. • Your data is structured (name, price, tags): exact lookups, tag filters, and small tokenized search provide precise answers without LLM retrieval overhead. • RAG adds overhead: creating embeddings, running vector searches, and injecting retrieved chunks into prompts increases latency and cost compared to direct in-memory lookup. When RAG is helpful • Your KB grows large (many MBs) or contains long free‑text documents where semantic matches are needed. • You need paraphrase/semantic matches (e.g., user asks “vegetarian spicy noodle” and items aren’t tagged for that concept). • You want to rank or merge partial passages from varied documents rather than return structured item records. If you still want RAG (minimal outline) 1. Precompute embeddings for each menu item (name+description+tags) and store them in a small vector index (HNSW/Annoy/FAISS). 2. At query time: embed the user query, run a k-NN vector search to get top-N relevant items, then inject those items into the prompt for the LLM to produce a helpful natural-language answer. 3. Cache embeddings and the index, only recompute on KB refresh; keep vector search in-memory for low latency. Trade-offs • Latency: embedding + search + LLM call > direct lookup. But for semantic retrieval it's often worth it. • Cost: embeddings and larger LLM prompts increase cost. • Complexity: requires embedding pipeline, vector store, and prompt engineering. Recommendation for your restaurant KB • Start with the in-memory + inverted-index approach (fast, simple, accurate). • Add background async refresh (what I showed earlier) so updates don’t block queries. • Add a tiny RAG path later only if you need semantic matching that tokenized/indexed search can’t handle. If you want, I’ll provide: • A compact Python RAG example (embedding generation and using a small in-memory vector index), or • A tuned in-memory search snippet for fuzzy/semantic-like matching without full RAG. Which would you like?
p
im parsing and saving the json file inside mongodb as an object. so i will be loading that in cache. how can i do that with the above code snippet?
t
Thanks — below is a concise Python-ready patch to the previous snippet that replaces local/HTTP loading with MongoDB (using Motor). It preloads the KB from MongoDB into memory, builds the same inverted index, and runs an async background refresher that re-queries MongoDB and atomically swaps the cache. Change the Mongo URI, DB, and collection names to match your setup.
Copy code
import 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?
p
yes give that example too.
t
Thanks — quick clarifying questions so I give you the correct change-stream example: • Is your MongoDB a replica set or Atlas cluster that supports change streams? • Do you want per-document updates applied to the in-memory cache (preferred) or a full reload when any change occurs? • Are you running a single agent process or multiple instances? • Which Motor version are you using (or is modern Motor >= 2.x acceptable)? • Should the change stream watch the whole collection or only documents matching a filter? Answer these and I’ll provide a ready-to-run Motor example that applies inserts/updates/deletes atomically to the cache (with fallback full reload on errors) and shows integration points for your LiveKit agent.
p
whats the correct way to pass function context to agent? i keep getting errors. {"level": "ERROR", "name": "livekit.agents", "message": "unhandled exception while running the job task\nTraceback (most recent call last):\n File \"/home/appuser/.local/lib/python3.11/site-packages/opentelemetry/util/_decorator.py\", line 71, in async_wrapper\n return await func(*args, **kwargs) # type: ignore\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/home/appuser/.local/lib/python3.11/site-packages/livekit/agents/ipc/job_proc_lazy_main.py\", line 275, in _traceable_entrypoint\n await self._job_entrypoint_fnc(job_ctx)\n File \"/home/appuser/main.py\", line 1178, in entrypoint\n from livekit.agents.llm import FunctionContext\nImportError: cannot import name 'FunctionContext' from 'livekit.agents.llm' (/home/appuser/.local/lib/python3.11/site-packages/livekit/agents/llm/__init__.py)", "pid": 713, "job_id": "AJ_GhgZ7ohsYagf", "room_id": "RM_7HCL77RftEfV", "timestamp": "2025-11-24T181238.721220+00:00"}
t
You're seeing that ImportError because
FunctionContext
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)
Copy code
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)
Copy code
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
Copy code
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