A local language model can choose a function without having permission to execute code. Tool calls through the LM Studio API let a Python application receive that choice, run an allowed function, and return its result for a final answer.

The OpenAI-compatible chat endpoint separates the model's request from the application's work. The first response contains a function name and JSON arguments; a second request carries the tool result back with the original call identifier.

Model support matters because a reply that merely mentions a function is not a parsed tool call. A tool-trained model such as Qwen2.5 Instruct can supply the structured response, while application code still has to validate its name and arguments before executing anything.

Python 3 and a running llmster daemon are required on the same machine. The client uses Python's standard library and LM Studio's local, authentication-disabled server.
Related: How to run LM Studio headlessly with llmster

Steps to run tool calls with the LM Studio API:

  1. Download the Qwen2.5 3B Instruct model in Q4_K_M quantization.
    $ lms get https://huggingface.co/Qwen/Qwen2.5-3B-Instruct-GGUF@q4_k_m --gguf --yes

    The official public GGUF repository supplies the weights. The full URL and quantization suffix select a specific download rather than an ambiguous search match.
    Related: How to download a model with lms in LM Studio

  2. Load the model under the API identifier local-tools.
    $ lms load qwen2.5-3b-instruct --identifier local-tools \
      --context-length 4096 --gpu off

    –gpu off selects CPU inference, and the 4096-token context accommodates the tool schema and both conversation turns. On Ubuntu and Debian, CPU loading requires libgomp1.
    Related: How to load a model with lms in LM Studio

  3. Start the HTTP server on the loopback interface at port 1234.
    $ lms server start --bind 127.0.0.1 --port 1234

    The client connects to this same machine. The loopback binding keeps the unauthenticated endpoint off the local network; no API key is required for this server configuration.

  4. Create a file named tool_call.py in your text editor containing the request helper and conversation.
    tool_call.py
    import json
    from urllib.request import Request, urlopen
     
    URL = "http://127.0.0.1:1234/v1/chat/completions"
    MODEL = "local-tools"
     
     
    def chat(messages, tools=None):
        payload = {
            "model": MODEL,
            "messages": messages,
            "temperature": 0,
            "max_tokens": 256,
        }
        if tools is not None:
            payload["tools"] = tools
        request = Request(
            URL,
            data=json.dumps(payload).encode(),
            headers={"Content-Type": "application/json"},
        )
        with urlopen(request, timeout=120) as response:
            return json.load(response)["choices"][0]["message"]
     
     
    messages = [
        {"role": "system", "content": "Use the multiply tool for multiplication. "
         "After receiving its result, answer with the product."},
        {"role": "user", "content": "What is 19 times 23?"},
    ]

    The model value matches the identifier assigned during loading. The helper sends a non-streaming request and returns the assistant message; max_tokens bounds each generated reply.

  5. Append the function schema and multiplication function to tool_call.py.
    tools = [{
        "type": "function",
        "function": {
            "name": "multiply",
            "description": "Multiply two integers from 0 to 1000.",
            "parameters": {
                "type": "object",
                "properties": {
                    "a": {"type": "integer"},
                    "b": {"type": "integer"},
                },
                "required": ["a", "b"],
                "additionalProperties": False,
            },
        },
    }]
     
     
    def multiply(a, b):
        return {"product": a * b}

    The schema describes the tool to the model. The Python function performs the calculation locally; supplying the schema does not execute it.
    Tool: Function Calling Schema Generator

  6. Append the tool-call validation and result handoff to tool_call.py.

    Model output is untrusted input. This handler permits only multiply with two bounded integers; executing a returned name as shell code or with eval could give the model access to files, credentials, or network services.

    assistant = chat(messages, tools)
    calls = assistant.get("tool_calls") or []
    if len(calls) != 1:
        raise ValueError("Expected one parsed tool call; check model tool support.")
    call = calls[0]
    if call["type"] != "function" or call["function"]["name"] != "multiply":
        raise ValueError("Tool is not allowed.")
    args = json.loads(call["function"]["arguments"])
    if not isinstance(args, dict) or set(args) != {"a", "b"}:
        raise ValueError("Expected exactly a and b.")
    if any(type(value) is not int or not 0 <= value <= 1000
           for value in args.values()):
        raise ValueError("Arguments must be integers from 0 to 1000.")
    result = multiply(**args)
    print("Tool call:", call["function"]["name"], json.dumps(args))
    print("Tool result:", json.dumps(result))
    messages.append(assistant)
    messages.append({
        "role": "tool",
        "tool_call_id": call["id"],
        "content": json.dumps(result),
    })

    The application parses the JSON argument string and checks it before calling the function. The conversation retains the model's assistant message, followed by a tool message whose tool_call_id matches that returned call. A response without a parsed call stops here instead of being treated as executable code.

  7. Append the final-answer request to tool_call.py.
    answer = chat(messages)
    if answer.get("tool_calls") or not answer.get("content"):
        raise ValueError("Expected a final text answer.")
    print("Answer:", answer["content"])

    This second request sends the conversation and calculated result without offering further tools. LM Studio generates the final answer from that history.
    Related: LM Studio tool-use API reference

  8. Save tool_call.py in your editor.
  9. Run tool_call.py to confirm a parsed call, a calculated result, and a generated answer containing 437. Example output:
    $ python3 tool_call.py
    Tool call: multiply {"a": 19, "b": 23}
    Tool result: {"product": 437}
    Answer: The product of 19 times 23 is 437.

    The answer wording can vary. A prose-only first response, an exception, or an answer that disagrees with the tool result does not complete the round trip.

Share this guide