Create an OpenAI Python client with LM Studio’s loopback base URL and use the local server’s exact model identifier. The SDK builds the Chat Completions request for you. A small script can verify that the model is visible, show whether a request reached the service, and check the generated text before you adapt an existing project.
This example assumes LM Studio’s local server is running on the same Mac as Python. It uses a standard text chat request and a fictional shipping notice. If your server requires a token, use its locally issued token in the environment variable shown below. The script passes the destination explicitly and uses its own token variable, so an unrelated service configuration in your shell has no bearing on this test. LM Studio OpenAI-compatible endpoints.
Check the listener and model before installing anything
Read the local address and port from LM Studio’s Developer interface. This guide uses port 1234 and the IPv4 loopback address. Both values must agree with the running listener. If the interface shows a different port, use that address consistently in the Terminal commands and Python script.
Use the model list to check the address before installing the client. The response includes IDs understood by the API. Copy one exact chat model ID from the list. If the response requires authorization, repeat it using the server’s local bearer token or first run the authenticated SDK listing in the next section. The following request shows the simple loopback configuration whose local authentication setting allows calls without a token. LM Studio model listing.
curl -sS --connect-timeout 2 http://127.0.0.1:1234/v1/models
If you receive a connection refusal, inspect the server address and state. This problem occurs before the Python package or the chat request. If you receive a response but the model you expected is absent, check LM Studio’s running or advertised models. A chat display label can differ from the API identifier. Pointing a script at a short guessed name can lead to a model error even while the same checkpoint is available in the application.
Install the SDK in an isolated environment
Create a practice directory outside your application’s source tree. Start with a clean virtual environment so that the install stays separate from other Python projects. Use the activated Python to install and inspect the SDK. Consult the SDK’s current Python requirements if the installation reports that your interpreter is too old. OpenAI Python SDK installation and configuration.
mkdir -p ~/lm-studio-python-client-practice
cd ~/lm-studio-python-client-practice
python3 -m venv .venv
. .venv/bin/activate
python -m pip install openai
python -m pip show openai
Save the installed version if you intend to reproduce the integration on a second Mac. Use the same environment when running the sample. If the editor cannot import the SDK but Terminal can, compare the Python interpreter selected in the editor with the activated environment. Reinstalling into several Python installations makes it harder to check which version the project actually imports.
The SDK takes a base URL ending in the version prefix. Use the base address, such as http://127.0.0.1:1234/v1, because the SDK appends resource paths itself. A URL ending in the entire Chat Completions path can cause duplicated route segments. The next script supplies a harmless sentinel value for a loopback listener with local authentication disabled. For a protected listener, supply the LM Studio token and leave the same address explicit. The vendor describes local token creation and use. LM Studio API authentication.
Make one checked request from Python
Save the script as check-local-chat.py and replace the model placeholder with the exact ID returned by the local service. The client has a finite timeout and disables automatic retries during the exercise so that a single run corresponds to one observable request after a successful listing. The first call checks model visibility. The second sends two short facts and expects the value associated with one of them.
import os
import sys
from openai import APIConnectionError, APIStatusError, OpenAI
base_url = "http://127.0.0.1:1234/v1"
model_id = "REPLACE_WITH_LOCAL_MODEL_ID"
token = os.environ.get("LM_STUDIO_LOCAL_TOKEN", "loopback-placeholder")
client = OpenAI(
base_url=base_url,
api_key=token,
timeout=60.0,
max_retries=0,
)
try:
available = {item.id for item in client.models.list().data}
if model_id not in available:
sys.exit(f"Model ID missing from {base_url}: {model_id}")
completion = client.chat.completions.create(
model=model_id,
messages=[
{
"role": "user",
"content": (
"Dispatch note: Mailing tubes are in drawer 19. "
"Foam envelopes are in drawer 23. "
"Reply with only the drawer number for foam envelopes."
),
}
],
max_tokens=64,
stream=False,
)
except APIConnectionError as error:
sys.exit(f"Connection failed: {error}")
except APIStatusError as error:
sys.exit(f"Server returned HTTP {error.status_code}: {error.message}")
if not completion.choices:
sys.exit("No chat choices returned.")
choice = completion.choices[0]
answer = (choice.message.content or "").strip()
if answer != "23":
sys.exit(f"Unexpected answer {answer!r}; finish reason {choice.finish_reason!r}")
print(f"Local model {model_id} returned the expected drawer: {answer}")
Run the script with the activated interpreter. For an unauthenticated service, the examples need only the local address and ID. For an authenticated service, make your local token available to this process as LM_STUDIO_LOCAL_TOKEN using the secret-loading method already in use for your projects. The SDK uses it in the authorization header. Keep the raw token out of your source file, terminal screenshots, and examples sent to other people.
python check-local-chat.py
The expected success line ends with the drawer value 23. The assertion requires exactly the specified answer apart from surrounding whitespace. A full sentence that cites drawer 23 can still demonstrate a working connection, but it fails the consumer’s strict formatting requirement here. Record the raw output when that happens. If a reasoning model returns a length finish with no visible answer, try a compatible direct instruction checkpoint or increase the output budget for this diagnostic.
Change the foam envelope drawer to 31 and adjust the expected value in the check. Keep drawer 19 unchanged. A fresh execution should produce the changed answer, which confirms it received the current script’s input. Then, in a temporary copy, use an ID that is absent from the list. The checker should report that it cannot find the model before submitting the chat. Restore the original script and valid ID when finished.
Match the exception to the stage that failed
Connection errors indicate that the client did not obtain an HTTP response for the attempted call. Confirm that the server is running and the script uses the correct port. A timed-out request and an immediate refusal can require different checks. The first can happen while a model is loading or generating. The second commonly points to an unavailable listener. The short listing call is a convenient comparison because it does far less work than an inference request.
An API status error means a server responded. Check its status and useful error description. An unauthorized response points toward the local authentication settings and token used for this process. A route error calls for looking at the base URL and the method the SDK calls. If the listing works but generation receives an unsupported request error, reduce the example to plain user messages before testing other request options. The set of features supported by a particular model and server version can differ from another endpoint that uses the same SDK.
A normal chat response moves the question to generation. Confirm the chosen ID, prompt, and finish reason. The request may have produced valid text that fails a downstream format check, or exhausted its response allowance before finishing. Preserve the model and prompt if you first investigate the output cap. Otherwise several changes happen together and the cause of the earlier result is harder to tell. LM Studio Chat Completions reference.
Move one known call into an existing app
Keep the loopback base URL, local token choice, and verified model ID in the part of the application that constructs this client. Give it a distinct settings entry if the same project also talks to another provider. Two client objects can share the SDK but point at different destinations. A single clearly named local profile makes it easier to review which object a background task or command uses.
Before enabling the application’s usual prompts, run a test route with the two-drawer exercise. Check the application log for a corresponding request without printing secrets or complete private messages. If the script works but the application fails, compare the environment in which each process runs. A separate Python process on the same host can use the same loopback socket. A container or remote execution target can interpret loopback as its own address. Identify that boundary before changing a known working server.
Finally, preserve the short recognition test alongside any migration notes. An upgrade to the SDK or a model reload should still return the correct changed drawer from a fresh process. The test gives a practical line between a functioning client configuration and a later application feature that needs its own verification.
Preserve evidence without reusing secrets or prompts
For each synthetic test run, record the base host and port, model ID, operation, and one outcome line. Start by noting whether the listing returned and then whether Chat Completions returned. On errors, record the status category and the finish reason if there is one. Keep headers containing authorization out of this note. A shared bug report can normally use the exact synthetic inventory example. It provides the reader enough data to reproduce the branch without including customer records or extracts from private files.
It is useful to exercise the two error paths without submitting a real application prompt. First, use a locally confirmed unused port in a temporary copy and check that it reports a connection failure. Restore the correct address. Then use an absent model ID, where the server can answer the listing but the client rejects the value before generating. The two runs should be easy to distinguish in the script’s output. Passing both checks also shows why connection failure should be reported separately from configuration that names a missing model.
If you add a response formatter later, keep a copy of a normal example during development. Run the formatter using that copy as its input and use the actual server call for a separate smoke test. A swapped number, blank visible content, and a transport failure deserve different handling in an application that will reuse the answer. Keeping those differences visible makes it easier to adjust the formatter or timeout policy without changing a working provider configuration.
When you upgrade the SDK, run the fixture before opening the regular project. Confirm whether the current version still accepts the same constructor options and exposes the same response fields, and record any migration. This keeps a small, independent way to test the route across package updates.
Keep the local client selection explicit in a multi-provider project
Suppose your existing application uses one provider for long-running jobs and a local script for short inventory extracts. A shared environment may define an ordinary SDK base URL already. Pass the loopback base explicitly when constructing this separate client, as the example does. Store the local model ID with that address. This makes the difference auditable when a background process runs with a different shell or inherited environment.
During a migration, look for another initialization of the SDK in the file that dispatches the current task. If the script is known to work and the app sends no request to the local listener, the app might still call the previous client object. An explicit local profile and a short fixture make it easy to see which branch is wired to it. For a first application-level test, send the drawer question through the app’s execution path and compare the server log with the standalone script’s run. Keep any resulting secret out of diagnostic output.
For a later release, capture a failure on the local profile without changing the rest of the app’s configuration. Stop the practice listener briefly or use the already identified unused port, then restore the direct local address after checking the error. If an application feature reports a successful reply during that specific failure test, review whether it selected a different provider or reused old output before relying on its routing.