In lmstudio-python, what does model.act() handle that a hand-rolled tool loop over LM Studio's OpenAI-compatible endpoint makes you write, and what stays your job?
answer
- functions become tool definitions
- rounds until no tool call
- tools run in your process
- one call at a time by default
- errors go back as text
basics
~20 smodel.act() turns typed, documented Python functions into tool definitions, runs prediction rounds, executes requested tools in your process and feeds results back until the model stops calling tools; round limits, parallelism, error policy and side-effect safety stay yours.
solid answer
~40 sWith the OpenAI-compatible route you write the loop: build JSON schemas, send, parse `tool_calls`, run functions, append results, resend. `model.act(chat, [add, is_prime], on_message=chat.append)` does that natively. Plain functions with type hints and docstrings become tool definitions (`ToolFunctionDef` when you need another name or description), arguments are coerced to the hinted types, and each round runs the requested tools **in your Python process** before the next prediction. Defaults to know: `max_parallel_tool_calls` is 1 since SDK 1.4.0 (`None` scales with CPU cores); exceptions from a tool go back to the model as text since 1.3.0, and `handle_invalid_tool_request` changes that; `max_prediction_rounds` is unbounded unless you set it, and when set, the last round withholds tools to force a final answer. Your job: bounds, safe tools, and anything with side effects.
code
python · 23 linesimport lmstudio as lms
def add(a: int, b: int) -> int:
"""Given two numbers a and b, returns the sum of them."""
return a + b
def is_prime(n: int) -> bool:
"""Given a number n, returns True if n is a prime number."""
if n < 2:
return False
return all(n % i for i in range(2, int(n ** 0.5) + 1))
model = lms.llm("qwen2.5-7b-instruct")
chat = lms.Chat("You are a careful assistant.")
chat.add_user_message("Is 12345 + 45668 a prime?")
model.act(
chat,
[add, is_prime],
on_message=chat.append, # assistant and tool-result messages
max_prediction_rounds=4, # the 4th round is offered no tools
)
print(chat)
model.unload()go deeper
Remember that .act() takes plain Python functions as tools and repeats predict, run tool, return result until the model answers without calling a tool.
Explain rounds, on_message for keeping a chat history, argument coercion from type hints, and the defaults for parallel calls and tool exceptions.
Show the production edges: set max_prediction_rounds, keep parallelism at 1 for unsafe tools, choose an error policy with handle_invalid_tool_request, and treat tools as code the model can trigger.
Weigh tying an application to LM Studio's SDK loop against a provider-neutral loop over the compatible API, considering portability, control over each round and how many runtimes you must support.
## The loop you would otherwise write Against LM Studio's OpenAI-compatible chat route, tool use is a client-side loop: describe each tool as a JSON schema, send the messages, read the tool calls in the reply, run the matching functions, append each result as a tool message, send again, and stop when the model answers without calling anything. Every step is code you own, including parsing malformed calls and deciding when to give up. (How tool calls and results pair up on the wire is a general function-calling subject; this question is about what the LM Studio SDK does with them.) The LM Studio SDKs wrap that loop in `.act()`, which the documentation calls an automatic **multi-round** tool-calling API. A **round** is: predict, run any requested tools, hand their results back, and predict again. ## What `.act()` does for you - **Tool definitions from functions.** A function with type hints and a docstring can be passed directly; its name, docstring and parameters are what the model sees. `lmstudio.ToolFunctionDef.from_callable(fn, name=..., description=...)` renames or redescribes it, and `ToolFunctionDef(name=..., description=..., parameters=..., implementation=...)` wraps a function without hints. - **Argument coercion.** The SDK coerces arguments to the hinted types before calling your function. - **The rounds.** It keeps predicting until a round ends with no tool call, or until a round limit you set. - **Execution.** It runs each requested tool **in your process**, through a thread pool sized by `max_parallel_tool_calls`. - **History.** `on_message` receives each assistant message and each tool-result message, so `on_message=chat.append` keeps a `lms.Chat` complete for the next turn. - **Progress hooks.** `on_round_start`, `on_round_end`, `on_prediction_completed`, `on_prediction_fragment` and `on_prompt_processing_progress` receive round indexes for logging or a UI. ## Defaults that decide behaviour | Setting | Default | Effect | |---|---|---| | `max_parallel_tool_calls` | `1` (since SDK 1.4.0) | several calls in one reply run one after another; `None` scales with CPU cores | | tool exceptions | sent to the model as text (since 1.3.0) | the model can retry or explain; `handle_invalid_tool_request` can raise locally or substitute text | | `max_prediction_rounds` | `None` | no round cap; when set to N, round N is predicted **without tools**, forcing a final answer | Two consequences follow. First, a tool that is not thread-safe is safe by default and slow by default; raise the parallelism only for tools you know tolerate it. Second, with no round cap a model that keeps calling tools keeps the loop running, so production code should set `max_prediction_rounds`. ## What stays your job 1. **Bounding the loop.** Pick a round limit; decide what a partial result means for the caller. 2. **Tool safety.** Functions run with your process's permissions. A tool that writes files or calls an API is an action the model can trigger; validate its arguments and keep destructive operations behind checks you control. How much approval such actions need is an agent-design question beyond the SDK. 3. **Error policy.** Decide which failures the model should see as text and which should abort, and implement that in `handle_invalid_tool_request` or in the tool itself. 4. **Model choice.** The documentation warns that not every model is capable of tool use and that larger models generally do better. 5. **Structured output.** In lmstudio-python 1.5.0, `.act()` sets no response format: the source notes that tool calling cannot yet be combined with structured responses, so parse the final text yourself or make a separate structured call. ## The TypeScript twin lmstudio-js offers the same loop: `tool({ name, description, parameters, implementation })` with Zod parameter schemas, then `await model.act(chat, [tool1, tool2], { onMessage })`. Its options include `maxPredictionRounds` and `allowParallelToolExecution`, which defaults to `false`. ## When a hand-rolled loop is still right Choose the HTTP route when the client is not Python or TypeScript, must run against several providers with one code path, or needs control the SDK does not expose. Choose `.act()` when the app runs next to LM Studio and you want rounds, coercion and history handled natively.
- The model asks for three tool calls in one reply. How does lmstudio-python run them by default, and when would you change it?One at a time: `max_parallel_tool_calls` defaults to 1 since SDK 1.4.0. Raise it, or pass `None` to scale with CPU cores, only when the tools are thread-safe and slow enough that waiting matters, such as independent network lookups.
- How do you make a tool failure abort .act() instead of being shown to the model?Pass `handle_invalid_tool_request` and raise the exception it receives; returning `None` sends the original error text to the model, and returning a string sends that string instead. Raising stops the prediction and propagates the exception to your code.
- LM Studio runs the tool functions inside its own process
- act() runs every requested tool call in parallel by default
- A tool exception always crashes the act() call
- act() stops after a fixed default number of rounds
- You must write JSON schemas for every Python tool
Assumes lmstudio-python 1.5.0; one-at-a-time tool execution became the default in 1.4.0 and tool exceptions are reported to the model since 1.3.0.