File size: 2,463 Bytes
b27bfb3
 
 
 
1
2
3
4
5
{"type": "session", "harness": "opencode", "id": "lmstudio-0120", "name": "streaming events"}
{"type": "message", "message": {"role": "system", "content": "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."}}
{"type": "message", "message": {"role": "user", "content": "How does streaming work with LM Studio's native REST API v1 POST /api/v1/chat? List the SSE event types and show Python SSE handling. Include code examples."}}
{"type": "message", "message": {"role": "assistant", "content": "**Streaming with `POST /api/v1/chat`** - set `\\\"stream\\\": true` for Server-Sent Events (SSE). Each event is `event: <name>` + `data: <json>`.\n\n```bash\ncurl -N http://localhost:1234/api/v1/chat \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"model\": \"model-identifier\", \"input\": \"Write a haiku.\", \"stream\": true}'\n\n# event: message_start\n# data: {\"type\":\"message_start\",\"output_index\":0}\n# event: content_delta\n# data: {\"type\":\"content_delta\",\"content_index\":0,\"delta\":\"Autumn\"}\n# event: message_end\n# data: {\"type\":\"message_end\",\"stats\":{}}\n```\n\n**Event types:**\n- `message_start` - new output item started\n- `content_delta` - partial text\n- `reasoning_delta` - partial reasoning (reasoning models)\n- `tool_call_start` / `tool_call_arguments_delta` / `tool_call_end` - tool calls\n- `message_end` - generation finished, includes `stats`\n- `model_load_start` / `model_load_progress` / `model_load_end` - loading status\n\n**Python SSE:**\n\n```python\nimport json\nimport requests\n\nresp = requests.post(\n    \"http://localhost:1234/api/v1/chat\",\n    json={\"model\": \"model-identifier\", \"input\": \"Hello\", \"stream\": True},\n    stream=True,\n    timeout=60,\n)\nresp.raise_for_status()\nfor line in resp.iter_lines(decode_unicode=True):\n    if line.startswith(\"data: \"):\n        event = json.loads(line[6:])\n        if event.get(\"type\") == \"content_delta\":\n            print(event.get(\"delta\", \"\"), end=\"\", flush=True)\nprint()\n```\n\nUnlike OpenAI-compat streaming (text deltas only), v1 streaming also emits reasoning, tool-call, and model-load events."}}