My agent needs to load some pre-existing context l...
# ask-ai
m
My agent needs to load some pre-existing context like a user prompt and some user messages. How do I do that?
t
Thanks for reaching out, Fotis. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'm happy to guide you through how to load pre-existing context, like a user prompt and messages, for an agent in LiveKit. Here are some helpful methods you can try: • Load Initial Chat History: You can use the
llm.ChatContext
object to preload previous messages. This way, your agent starts with a natural dialogue flow. Here's an example to illustrate:
Copy code
from livekit.agents import llm

chat_history = [
    {"role": "assistant", "content": "Hello, I am a travel planner. How can I help you?"},
    {"role": "user", "content": "I want to go to Paris this summer."},
    {"role": "assistant", "content": "Paris is a beautiful city. How many days will you be staying?"},
]

chat_ctx = llm.ChatContext.empty()
for item in chat_history:
    chat_ctx.add_message(role=item["role"], content=item["content"])

agent = Agent(
    instructions="You are a helpful travel planner.",
    llm=openai.realtime.RealtimeModel(model="gpt-4o-mini-realtime-preview"),
    chat_ctx=chat_ctx,
)
• Inject Dynamic Context: You can also pass user-specific details like their name or preferences right into the agent’s instructions when you set it up. • Transfer Context Between Agents: If you’re working with multiple agents, you can copy and merge
chat_ctx.items
from one agent to another to keep the conversation seamless. • Load Context from External Sources: Another great option is to fetch user-specific data dynamically using databases or Retrieval-Augmented Generation (RAG). • Persist Context Across Sessions: To maintain continuity, you can save
session.history
externally and reload it whenever the user returns. If you have a particular scenario in mind or need a hand with anything specific, please don’t hesitate to ask—I’m here to help! Sources: examples/voice_agents/fast-preresponse.py | complex-agents/personal_shopper/personal_shopper.py | Pipeline nodes and hooks | LiveKit Docs | Workflows | LiveKit Docs | External data and RAG | LiveKit Docs