tinycodinglm / lmstudio /lmstudio-0030.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 15)
b27bfb3 verified
|
Raw History Blame Contribute Delete
2.03 kB
opencode trace
System You are an expert software engineer and technical assistant. You provide accurate, detailed, and practical answers. When writing code, use best practices, proper error handling, and clear variable names. When analyzing c...

You are an expert software engineer and technical assistant. You provide accurate, detailed, and practical answers. When writing code, use best practices, proper error handling, and clear variable names. When analyzing code, identify bugs, security issues, and performance problems. You have deep knowledge of C/C++, Windows API, Python, and many other technologies.

User

How does streaming work with LM Studio's OpenAI-compatible chat completions? Show sync and async Python streaming with stream=True. Include code examples.

Assistant

Streaming sends tokens as generated - lower time-to-first-token.

python
from openai import OpenAI

client = OpenAI(base_url="http://localhost:1234/v1", api_key="lm-studio")

stream = client.chat.completions.create(
    model="model-identifier-from-lm-studio",
    messages=[{"role": "user", "content": "Write a poem about coding."}],
    stream=True,
)
for chunk in stream:
    delta = chunk.choices[0].delta.content
    if delta:
        print(delta, end="", flush=True)
print()

Async:

python
import asyncio
from openai import AsyncOpenAI

async def stream_response() -> None:
    client = AsyncOpenAI(base_url="http://localhost:1234/v1", api_key="lm-studio")
    stream = await client.chat.completions.create(
        model="model-identifier-from-lm-studio",
        messages=[{"role": "user", "content": "Explain recursion."}],
        stream=True,
    )
    async for chunk in stream:
        delta = chunk.choices[0].delta.content
        if delta:
            print(delta, end="", flush=True)
    print()

asyncio.run(stream_response())

Start the server first; model must be a loaded id from GET /v1/models.