MarsAI developer guide
Use tool calling through MarsAI
The model requests a tool; your application validates and runs it, then returns the result for the next model call.
Reviewed . Checked against the current MarsAI /v1 behavior and published catalog.
What happens in a tool call
Your application sends a tool schema with conversation history. The model may return a call; your code validates the arguments, runs the local function, then adds the result to history. MarsAI and the model do not execute your application's function.
Choose a model whose catalog card reports Tools support. Capability syntax can differ, so test the exact public model ID before relying on it.
Send a tool definition
python -m pip install openai
import json
import os
from openai import OpenAI
client = OpenAI(
base_url="https://marsai.click/v1",
api_key=os.environ["MARSAI_API_KEY"],
)
tools = [{
"type": "function",
"function": {
"name": "count_characters",
"description": "Count the characters in a string",
"parameters": {
"type": "object",
"properties": {"text": {"type": "string"}},
"required": ["text"],
"additionalProperties": False,
},
},
}]
messages = [{"role": "user", "content": "How many characters are in MarsAI? Use the counting tool."}]
response = client.chat.completions.create(
model="YOUR_PUBLIC_MODEL_ID",
messages=messages,
tools=tools,
)
message = response.choices[0].message
if not message.tool_calls:
print(message.content)
raise SystemExit
call = message.tool_calls[0]
print(call.function.name, call.function.arguments)
Run the function and return its result
A model can answer without requesting a tool, so the first snippet handles both branches. If it requests count_characters, validate the name and JSON before running local code.
if call.function.name != "count_characters":
raise ValueError("Tool is not allowed")
args = json.loads(call.function.arguments)
text = args.get("text")
if not isinstance(text, str) or len(text) > 1000:
raise ValueError("Invalid text argument")
tool_result = {"characters": len(text)}
messages.append(message.model_dump())
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps(tool_result),
})
follow_up = client.chat.completions.create(
model="YOUR_PUBLIC_MODEL_ID",
messages=messages,
tools=tools,
)
print(follow_up.choices[0].message.content)
The local function returns six. The final model wording can vary.
Checks for an application tool
- Validate the tool name and every argument.
- Apply authorization and timeouts inside the function.
- Keep tool output small enough for the remaining model context.
- Handle a normal text answer when no tool call appears.
- Keep the assistant tool call and matching result together in replayed history.