File size: 1,920 Bytes
b27bfb3
 
 
 
1
2
3
4
5
{"type": "session", "harness": "opencode", "id": "lmstudio-0060", "name": "embeddings"}
{"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 do I generate text embeddings with LM Studio's OpenAI-compatible POST /v1/embeddings endpoint? Show single and batch embeddings with the OpenAI Python SDK. Include code examples."}}
{"type": "message", "message": {"role": "assistant", "content": "**LM Studio embeddings via OpenAI-compatible `POST /v1/embeddings`.**\nLoad an embedding model first, then use `base_url=\"http://localhost:1234/v1\"`.\n\n```python\nfrom openai import OpenAI\n\nclient = OpenAI(base_url=\"http://localhost:1234/v1\", api_key=\"lm-studio\")\n\ndef get_embedding(text: str, model: str) -> list[float]:\n    text = text.replace(\"\\n\", \" \")\n    return client.embeddings.create(input=[text], model=model).data[0].embedding\n\nMODEL = \"text-embedding-nomic-embed-text-v1.5\"  # example; use your loaded id\nemb = get_embedding(\"What is the meaning of life?\", MODEL)\nprint(f\"dim={len(emb)} first5={emb[:5]}\")\n```\n\n**Batch embeddings:**\n\n```python\nresp = client.embeddings.create(\n    model=MODEL,\n    input=[\"Hello world\", \"How are you?\", \"Goodbye!\"],\n)\nfor i, d in enumerate(resp.data):\n    print(f\"{i}: dim={len(d.embedding)}\")\n```\n\nUse cases: semantic search via cosine similarity, RAG, clustering. Dimension depends on model (e.g. 768 for nomic v1.5). Use `GET /v1/models` to confirm the embedding model id you loaded."}}