give a code example of using a RAG as a knowledge ...
# ask-ai
p
give a code example of using a RAG as a knowledge base for the llm to retrieve information from, and what its impact on the latency
t
Thanks for reaching out, Yasser. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Here's a friendly example of how you can use Retrieval-Augmented Generation (RAG) as a knowledge base for an LLM:
Copy code
class RAGEnrichedAgent(Agent):
    def __init__(self):
        super().__init__(instructions="You are a helpful assistant.")
        self._index_path = "path_to_index"
        self._data_path = "path_to_data"
        self._embeddings_model = "text-embedding-3-small"
        self._annoy_index = AnnoyIndex.load(self._index_path)
        with open(self._data_path, "rb") as f:
            self._paragraphs_by_uuid = pickle.load(f)

    async def search(self, query):
        query_embedding = await openai.create_embeddings(input=[query], model=self._embeddings_model)
        results = self._annoy_index.query(query_embedding[0].embedding, n=5)
        context = [self._paragraphs_by_uuid.get(r.userdata, "") for r in results]
        return "\n".join(context)
What this does is pull in relevant info from a pre-built knowledge base using embeddings and vector search, then feeds that context into the LLM prompt to help generate a great response. About Latency: • The main factors that add to latency are embedding generation, vector search, and adding context into the LLM prompt. • To help with perceived wait times, you can try things like friendly status updates (think: "Let me look that up..."), dynamic feedback, and streamlining your pipeline. • Also, using unified models like GRIT can cut down on extra steps, speeding things up by over 60% in some cases. If you want me to dive deeper or help out with anything else, just let me know—I’m here for you! Sources: rag/main.py | examples/voice_agents/llamaindex-rag/README.md | External data and RAG | LiveKit Docs | README.md | External data and RAG | LiveKit Docs
p
yes go deeper
t
Let's take a closer look at how to implement and optimize RAG together: 1. Latency Optimization: • Try placing your agent servers close to the LLM, STT, and TTS service endpoints to keep network delays to a minimum. • Using streaming APIs and parallel processing can really help speed things up during retrieval and response generation. 2. Handling Delays: • Keeping users engaged during lookups is key! Here are some friendly options: ◦ Simple static messages like "Let me look that up..." can do the trick. ◦ Or, you could have the LLM generate dynamic responses that fit the specific query. ◦ Adding audio feedback, like typing sounds or progress indicators, makes the wait feel more interactive. ◦ And don’t forget system prompt instructions to gently set user expectations. 3. Performance Monitoring: • Keep an eye on important metrics like Time To First Token (TTFT) and Time To First Byte (TTFB) to see where you can speed things up. • The Agents metrics API is a handy tool to monitor latency and spot any bottlenecks in your pipeline. 4. Context Management: • Focus your RAG lookups on the user’s latest input to keep responses relevant. • Inject the retrieved context right into the LLM’s prompt to boost the quality of answers. • Vector search is a great way to quickly find and pull in the most relevant info from your knowledge base. If you want me to dive deeper into any part or have more questions, just let me know—I’m here to help! Sources: External data and RAG | LiveKit Docs | Agent Testing & Evaluation | livekit/livekit_composite | DeepWiki | delay-handling/README.mdoc | Voice Assistants | livekit/livekit_composite | DeepWiki
p
what does this noise_cancellation do in livekit agent
t
The noise_cancellation module in LiveKit agents is here to help improve your audio quality by cutting out background noise—and sometimes even background voices—from inbound audio streams. This is super handy for voice AI apps where having clear audio is key for accurate speech-to-text (STT) transcription and turn detection. Key Features: • Noise Cancellation (NC): Takes away common background noises like traffic, music, or ambient sounds. • Background Voice Cancellation (BVC): Removes both background noise and other voices that might confuse STT or turn detection models. • BVCTelephony: A special version fine-tuned for telephony applications. How to Use It: Noise cancellation works on inbound audio streams and you can easily turn it on using the
RoomInputOptions
when you start an
AgentSession
. Here’s a quick example:
Copy code
from livekit.plugins import noise_cancellation

await session.start(
    room=ctx.room,
    room_input_options=RoomInputOptions(
        noise_cancellation=noise_cancellation.BVC(),  # or NC(), BVCTelephony()
    )
)
Compatibility: • Works with Python and Node.js for inbound audio processing. • Not available for outbound audio on Web, Swift, or Android platforms. Just a couple of things to keep in mind: • Avoid enabling noise cancellation on both the agent (inbound) and frontend (outbound) at the same time, since that can actually hurt performance. • LiveKit’s AI-based models do a better job than the usual WebRTC noise suppression, especially when things get noisy or there are multiple speakers. If you have any questions or want me to walk you through anything, just let me know—I’m happy to help! Sources: Audio and video | LiveKit Docs | Noise & echo cancellation | LiveKit Docs | Enhanced noise cancellation | LiveKit Docs | AI noise cancellation | LiveKit Docs
p
tell more details about BVCTelephony
t
BVCTelephony is a noise cancellation model in LiveKit that's specially tuned for telephony applications, like SIP-based or narrow-band audio setups. It’s part of LiveKit’s AI-powered noise cancellation suite, using models licensed from Krisp to help cut out background noise and make calls clearer in telephony scenarios. Key Features: • Tailored for telephony audio traits, such as lower bandwidth and specific encoding profiles. • Effectively removes background noise and boosts clarity for SIP or telephony-connected participants. • Built to work smoothly in server-side SDKs (Python and Node.js) within LiveKit Agents. Usage: If you want to apply
BVCTelephony
as an inbound noise cancellation filter, here’s a simple example to get you started:
Copy code
await session.start(
    agent=MyAgent(),
    room=ctx.room,
    room_input_options=RoomInputOptions(
        noise_cancellation=noise_cancellation.BVCTelephony(),
    ),
)
Dynamic Model Selection: In environments where you have different participant types, you can pick the right model on the fly like this:
Copy code
participant = await ctx.wait_for_participant()
filter = noise_cancellation.BVC()
if participant.kind == rtc.ParticipantKind.PARTICIPANT_KIND_SIP:
    filter = noise_cancellation.BVCTelephony()
This way, you’ll get the best audio quality and transcription accuracy whether folks are joining via telephony or WebRTC. If you have any questions or want me to walk you through anything else, just let me know — I’m here to help! Sources: Voice AI quickstart | LiveKit Docs | AI noise cancellation | LiveKit Docs | Using Noise Cancellation for SIP and WebRTC Participants | Enhanced noise cancellation | LiveKit Docs