how can I directly query the openai llm on my agen...
# ask-ai
w
how can I directly query the openai llm on my agent for a completion?
t
Thanks for reaching out, Nathan. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
To help you directly query the OpenAI LLM on your agent for a completion, you can use the
openai.LLM
class either within an
AgentSession
or as a standalone service. Let me walk you through how you can do it: Standalone Usage:
Copy code
from livekit.agents import ChatContext
from livekit.plugins import openai

# Initialize the LLM
llm = openai.LLM(model="gpt-4o-mini")

# Create a ChatContext and add a user message
chat_ctx = ChatContext()
chat_ctx.add_message(role="user", content="Hello, this is a test message!")

# Stream the LLM response
async with llm.chat(chat_ctx=chat_ctx) as stream:
    async for chunk in stream:
        print("Received chunk:", chunk.delta)
Usage in an AgentSession:
Copy code
from livekit.plugins import openai

session = AgentSession(
    llm=openai.LLM(model="gpt-4o-mini")
)
Just a quick reminder to make sure you’ve installed the required plugin with:
Copy code
pip install "livekit-agents[openai]~=1.2"
And don’t forget to set your
OPENAI_API_KEY
in your environment variables or
.env
file. If you have any questions or run into any issues, please feel free to reach out—I’m here to help! Sources: Docs::Agents | Docs::Agents | OpenAI LLM integration guide | LiveKit Docs
w
Give me an example, how can I ask it what's the capitol of France?
t
Here’s a friendly example to help you ask the LLM "What’s the capital of France?" using the standalone approach:
Copy code
from livekit.agents import ChatContext
from livekit.plugins import openai

# Initialize the LLM
llm = openai.LLM(model="gpt-4o-mini")

# Create a ChatContext and add your question
chat_ctx = ChatContext()
chat_ctx.add_message(role="user", content="What is the capital of France?")

# Stream the LLM response
async with llm.chat(chat_ctx=chat_ctx) as stream:
    async for chunk in stream:
        print("Received chunk:", chunk.delta)
This snippet sends your question to the LLM and streams the response back in chunks. You can then put these chunks together to show the full answer. If anything’s unclear or you’d like a hand with this, just let me know—I’m here to help!
w
what if I don't want to receive it as a stream
t
Thanks for reaching out! The documentation mainly covers streaming responses from the OpenAI LLM in LiveKit. To better assist you, could you please let me know if you're using the LiveKit Agents SDK and specifically the
LLM
class? This info will really help us explore the best ways to achieve what you're aiming for. Sources: plugins/openai/src/realtime/realtime_model.ts | livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/real...