i would like to use qwen as llm but there's no plu...
# ask-ai
e
i would like to use qwen as llm but there's no plugin for that, how to accomplish
t
Thanks for reaching out, Aman. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're all set — you can use Qwen without a dedicated plugin. Two simple options: 1) Recommended — use LiveKit Inference (no plugin needed) • Set the LLM to
qwen/qwen3-235b-a22b-instruct
in your AgentSession. • Example (Python):
Copy code
from livekit.agents import AgentSession

session = AgentSession(
    llm="qwen/qwen3-235b-a22b-instruct",
    # other components...
)
• LiveKit handles provider routing and billing automatically and supports model options like
max_completion_tokens
. 2) If you host Qwen via an OpenAI-compatible API — use the OpenAI plugin with a custom base URL • Configure the OpenAI plugin with your provider’s
base_url
and API key. • Example (Python):
Copy code
from livekit.plugins import openai

session = AgentSession(
    llm=openai.LLM(
        model="your-qwen-model-name",
        base_url="https://api.your-qwen-provider.com/v1",
        api_key="YOUR_QWEN_API_KEY",
    )
)
Which environment are you using (Python or Node.js), and do you want an example showing how to pass model options (e.g.,
max_completion_tokens
)? Sources: Qwen LLM | LiveKit Docs | Models | LiveKit Docs
e
i would like to use direct qwen using their api
t
You can call Qwen’s API directly and use it as the LLM in your AgentSession by configuring LiveKit to talk to your Qwen endpoint via an OpenAI-compatible wrapper (the OpenAI plugin with a custom base_url) or by using your own adapter that implements the same request/response shape LiveKit expects. Quick questions to tailor the instructions: • Are you using Python or Node.js? • Do you have an OpenAI-compatible endpoint for Qwen (i.e., a base URL and API key), or do you plan to call Qwen’s native API format directly? If you’re using an OpenAI-compatible endpoint, I can provide a ready-to-use example for your language (Python or Node.js). If you plan to call Qwen’s native API, I’ll show how to write a small adapter wrapper that forwards requests/responses between LiveKit and Qwen’s API. Which would you like?
e
Qwen’s native API
t
You can do this, but LiveKit doesn't provide a built‑in connector for Qwen's native API. To use Qwen directly you need to implement a custom LLM adapter (a custom
llm_node
) that calls Qwen's API, translates requests/responses to the shape LiveKit expects, and handles auth/errors. I can provide a concrete example. Quick questions: • Do you want the example in Python or Node.js? • Do you have Qwen's endpoint and API key ready, and can you share the request/response shape (or a sample) from Qwen's docs? Sources: Qwen LLM | LiveKit Docs | Using Custom LLM Providers with the Agent
e
yes share example in Python
t
I can walk you through a minimal Python example that shows how to implement a custom
llm_node
adapter which calls Qwen’s native API and exposes the request/response shape LiveKit Agents expects. Important: LiveKit’s docs do not include a full reference for a custom
llm_node
implementation — the examples below are a practical adapter pattern you can adapt. You’ll need Qwen’s API docs for exact endpoint paths, headers, and request/response fields. 1) High-level approach • Create a class that implements the LLM interface LiveKit uses for agent nodes (accepts prompts/params, returns completions/streamed tokens and metadata). • Inside that class, call Qwen’s native HTTP API, translate LiveKit’s input into Qwen’s request body, and translate Qwen’s response back to LiveKit’s expected output. • Handle errors, timeouts, and streaming (if you want partial tokens) per Qwen’s API. 2) Minimal synchronous example (Python) • Replace placeholders with Qwen endpoint, model name, and API key.
Copy code
import os
import requests
from typing import Dict, Any

QWEN_API_URL = "https://api.qwen.provider/v1/completions"  # replace with Qwen's endpoint
QWEN_API_KEY = os.getenv("QWEN_API_KEY")
MODEL = "qwen-model-name"  # replace with the model id Qwen requires

class QwenLLMNode:
    def __init__(self, model: str = MODEL, api_url: str = QWEN_API_URL, api_key: str = QWEN_API_KEY):
        self.model = model
        self.api_url = api_url
        self.api_key = api_key

    def _headers(self) -> Dict[str, str]:
        return {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json",
        }

    def create_completion(self, prompt: str, max_tokens: int = 512, temperature: float = 0.0) -> Dict[str, Any]:
        # Map LiveKit/Agent parameters to Qwen request body format
        payload = {
            "model": self.model,
            "prompt": prompt,
            "max_tokens": max_tokens,
            "temperature": temperature,
            # add other Qwen-specific fields as required
        }

        resp = requests.post(self.api_url, json=payload, headers=self._headers(), timeout=60)
        resp.raise_for_status()
        data = resp.json()

        # Translate Qwen response into LiveKit-like completion shape
        # Adjust these fields to match what LiveKit expects
        completion_text = data.get("text") or data.get("choices", [{}])[0].get("text", "")
        return {
            "text": completion_text,
            "raw": data,
        }
3) Example usage inside an AgentSession • Where LiveKit expects an
llm_node
, pass an instance or wrapper pointing to this class (you may need to adapt to the AgentSession API to register a custom node).
Copy code
# Pseudocode — adapt to LiveKit AgentSession registration API
from livekit.agents import AgentSession

qwen_node = QwenLLMNode(model="qwen-xxx")

session = AgentSession(
    llm_node=qwen_node,
    # other components...
)
4) Streaming / chunked responses • If Qwen supports streaming, implement a streaming method that opens a streaming HTTP request (or websocket), yields tokens as they arrive, and forwards them to LiveKit’s token callback interface. • Ensure you respect backpressure and can cancel streams if the agent stops. 5) Error handling and retries • Catch and translate HTTP errors into the error shape LiveKit expects. • Implement retries with exponential backoff for transient network/errors. 6) Security and deployment • Keep your QWEN_API_KEY in env vars or a secret manager. • Ensure network egress to Qwen from where your agent runs. • Monitor latency and cost. If you want, I can: • Expand this into a streaming example (if Qwen supports SSE/websocket). • Provide a more concrete mapping for the exact LiveKit
llm_node
interface if you share the AgentSession API surface you’re using (snippet showing how
llm_node
is registered). • Convert this into a fully working example adapted to your Qwen request/response sample. Which would you like next?