Point an OpenAI Python client at the loopback base URL of the MLX-Serve server already running on your Mac. List the server’s models, select an exact text model ID, and send one short chat-completions request. A small known answer and a matching request in the local server give you a check before integrating the client with an app.
Confirm which MLX-Serve address to use
This guide uses David Dalcu’s MLX-Serve and a text chat model already ready to run on the same Apple silicon Mac. Record the endpoint and port that the running server advertises. Its documented default base URL for an OpenAI-compatible client is http://127.0.0.1:11234/v1. Change only the port in the example if your local server uses another one. Keep the host as a loopback address when the Python program and the server run on the same Mac. MLX-Serve connection settings
The client needs the base URL, which ends in /v1. The SDK appends the path for each operation. Its model list request ends in /v1/models and a chat request ends in /v1/chat/completions. Keeping the base URL and full request paths separate helps when you compare an error in Python with a request sent from Terminal. MLX-Serve HTTP API
If you already know the model name from a graphical app, get the server’s exact identifier too. A label shown in a library can include formatting or spacing that differs from the ID returned by the API. Select a model that is served for text chat. A catalog can expose more than one capability, so the first item the server lists may be set up for a different task. For initial testing, a short reply from a loaded chat model is enough.
Check the HTTP response before debugging Python
When the address is uncertain, make a direct call to the model list from the Mac with the server. The header output shows whether the service returned an HTTP status. If your local installation requires a credential, use the server credential for this request too.
curl --noproxy 127.0.0.1 -i -sS http://127.0.0.1:11234/v1/models
The useful result is a successful status and a JSON response with a model collection. An HTML page can mean you reached a web interface or a service on the wrong port. A connection error means the direct client could not reach the endpoint from this Mac. If the model catalog is accessible but empty, check which model the server is currently serving. Leave the Python code alone until you know which of those cases you are handling.
Write down the result in terms of the request you made. For example, an empty model list is different from a successful text answer. Copying the ID and making a separate chat request checks the part your application needs. You can also compare the first status in Terminal with the SDK result from the same moment. That helps you separate a service problem from the setup of one Python environment.
Prepare the client in a local Python environment
Use an existing Python environment with the OpenAI package installed, or create a small one just for the test. Installing the package may need internet access once for any packages your environment lacks. The requests in this guide are then made to the local server. From a directory reserved for the exercise:
python3 -m venv .venv
source .venv/bin/activate
python -m pip install openai
Use the same terminal and interpreter when running the script. If you work in an editor, select this environment for the project too. Run python -m pip show openai if you need to check which package installation that interpreter can see. If this needs to be repeatable across machines, record the package version you verified. Official OpenAI Python library
The SDK expects an API key value when constructing the client. The upstream MLX-Serve integration guide documents a local placeholder for current loopback connections. The script uses one for that case. If your own server configuration or a local gateway requires a real token, supply that specific local credential through a separate environment variable. Leave cloud credentials out of this test. The base URL is explicit and the client disables proxy lookup from its environment for this local request path.
List models and make a first local request
Save the following as ask_mlx.py. Update the port in the base URL if needed. With no model argument, the script lists exact identifiers and exits. For a test reply, pass the chosen ID as a single command-line argument.
import os
import sys
from openai import (
APIConnectionError,
APIStatusError,
APITimeoutError,
DefaultHttpxClient,
OpenAI,
)
BASE_URL = "http://127.0.0.1:11234/v1"
EXPECTED = "RIVET-41"
def main():
try:
with OpenAI(
base_url=BASE_URL,
api_key=os.environ.get("MLX_SERVE_API_KEY") or "local-mlx-serve",
timeout=45.0,
max_retries=0,
http_client=DefaultHttpxClient(trust_env=False),
) as client:
model_ids = [model.id for model in client.models.list().data]
if len(sys.argv) == 1:
print("\n".join(model_ids) or "The server returned an empty model list.")
return 0 if model_ids else 1
model_id = sys.argv[1]
if model_id not in model_ids:
print("That exact ID is absent. Run the script without a model argument.", file=sys.stderr)
return 1
reply = client.chat.completions.create(
model=model_id,
messages=[{"role": "user", "content": f"Reply with {EXPECTED} only."}],
max_tokens=64,
stream=False,
)
if not reply.choices:
print("The server returned no choices.", file=sys.stderr)
return 1
choice = reply.choices[0]
text = choice.message.content or ""
print("Requested model:", model_id)
print("Reported model:", reply.model)
print("Finish reason:", choice.finish_reason)
print("Reply:", text)
return 0 if text.strip() == EXPECTED else 1
except APITimeoutError:
print("The local request timed out.", file=sys.stderr)
except APIConnectionError:
print("Could not connect to the loopback API.", file=sys.stderr)
except APIStatusError as error:
print(f"The server returned HTTP {error.status_code}.", file=sys.stderr)
return 1
if __name__ == "__main__":
sys.exit(main())
Run the discovery call first, then copy the ID that belongs to the text model you intend to use. Replace the placeholder between the quotes in the second command:
python ask_mlx.py
python ask_mlx.py "paste-the-exact-text-model-id-here"
The short test uses a bounded output and a non-streaming reply so the program can read the assistant’s full message together. Before involving a real app, confirm that the expected port is still serving the model you selected. The SDK can report network failures and HTTP failures separately. This example prints the status or failure category without exposing the local token. A timeout is set for this diagnostic and retries are disabled so that one invocation gives you one attempt per operation.
Check the reply and its origin
The expected message is RIVET-41. The script returns success when the assistant’s text matches exactly after removing leading or trailing whitespace. Look at the finish reason too. If it shows a length limit, the response may have ended before the final text. Choose a model already suited to simple text instructions, inspect the host’s model state, and rerun the short check.
The requested model field records the ID you sent and the reported model field shows what the server returned. If they differ, check how your server reports aliases. Confirm the actual served model using the original model list or the server console. Match a local chat request to the time you launched the second command. When other clients share the same server, repeat once with a different expected code while they are idle and observe which local request appears.
A usable connection can still return a sentence that fails the exact test. For example, a small model might put quotes around the code or add a greeting. The response and server entry still help diagnose routing. Adjust the prompt or choose a different text model, then check the literal output again before building a program around it. Save the host and model ID in your project notes without saving the credential.
Decide what a program should accept
In this diagnostic, the presence of a successful HTTP response is one check. The presence of a nonempty assistant message is another. The expected test answer gives you a third check. Use those outcomes separately when deciding what to fix. A Python script that reached the wrong local service might receive a normal status with a different model list. A reply that contains the right code with extra text shows the model read the prompt. A program with an exact output contract should still flag the extra text.
When extending the test, keep the same model and repeat with a value that has a different shape, such as PLATE-06. Change both the expected answer and the prompt together. With two inputs, you can see whether the second reply reflects the new request. If you later ask the model to return a record with several fields, check the particular fields your application will read. Keep unsuitable output available for inspection when using synthetic inputs before connecting the response to another action.
Troubleshoot from the first failing check
- Python imports fail. Check that the intended environment is active and that the same interpreter installed the SDK. Confirm the environment before changing server settings.
- Listing fails to connect. Check the port in the MLX-Serve window or terminal. Confirm both processes are running on the same Mac. If client code runs inside a container or remote session, loopback refers to that environment.
- The server responds with an HTTP error. Check authentication first for an authorization error or a base path first for a missing endpoint. Compare the actual endpoint path in the server log with the API documentation.
- The list opens and the model has gone missing. Check the model’s current state in MLX-Serve and copy the ID from a fresh listing. The SDK’s list can only reflect what the server exposes at request time.
- The server lists the model and the chat times out. Keep the prompt short and try the same request when the model is ready. Watch the server’s current activity before increasing the client timeout. A long wait can reflect loading or another active request.
Connect the script to the application
Once both calls work, use the same explicit loopback base URL and model ID when wiring the Python client into your app. Give the local client its own configuration entry if the application also uses remote providers. Display the chosen endpoint and model label in your test output so a developer can check which path the application selected. Keep token storage out of that output. Run the synthetic prompt through the application once before adding a document, conversation history, or other source data.
If the standalone script succeeds and the exact same prompt fails inside the application, check what the application sends. Compare the endpoint selection, the final model ID, the length of the messages list, and the reply format requested. A second SDK instance with a different base URL can route the request differently. A program may also be expecting a streamed reply when the verified test used one complete response. Keep the current request format while checking the route first. Once the app returns the expected text, you can change its parsing or add history one step at a time.
Keep the initial example available as a way to separate a client integration failure from a server issue. If the server itself needs attention, check the existing guide to its local interface. Connect to the MLX-Serve API on a Mac