Script Reference
Each tool is a Python 3.12 script. Optima adds some code before it, to read the inputs and credentials, and some after it, to send back result. This page is the contract between your script and Optima. Several of the rules fail silently if broken, so read it before you write your first tool.
Inputs
Every input you declare is an attribute of inputs, already converted to its type:
path = inputs.path # String → str
limit = inputs.limit # Number → int or float
flag = inputs.case_sensitive # Boolean → bool
opts = inputs.options # Object → dict
ids = inputs.ids # Array → list
- An optional input the model left out is its default value, if it has one, and otherwise
None. Always handleNone. - Conversion is forgiving:
"5"becomes5,"true","yes"and"1"becomeTrue, and a JSON string becomes a dictionary or list. A value that cannot be converted will stop the run before your code starts, and the model will be told which input was wrong. -
Check numbers anyway, because models send odd values. For example:
limit = max(1, min(int(inputs.limit or 20), 50))
Returning A Result
Assign the answer to a variable called result, at the top level of the script. Optima turns it into JSON, and that JSON is exactly what the model reads. For example:
result = {"path": path, "total_lines": 120, "content": "..."}
| Rule | Why |
|---|---|
result must be a top-level variable. |
Assigning it inside a function creates a local variable, and the model gets null. Write def main(): … return {…}, then result = main() |
Only JSON types: dict, list, str, int, float, bool and None. |
Convert dates (.isoformat()), bytes, sets, Decimal and Path first. Otherwise the conversion fails after your code has finished, and the call reports an error |
Never call sys.exit(), exit() or quit(). |
The code that sends result runs after yours. Exiting skips it, and the model gets a bare error |
No return outside a function. |
It is a syntax error in a script |
print() is not shown to the model. |
Only result is. Printed output appears in the debug runner, and is given to the model only when a tool times out |
Errors
There are two kinds of failure, and they are handled differently:
- An expected failure is something you can foresee — a file not found, a bad argument, the API said 404, nothing matched. Catch it and set
result = {"error": "..."}. The model will see your message. - An unexpected failure is a bug in your script. Let it raise. The model will see the exit code and the Python traceback.
Use the error form for everything you can foresee:
- Say what went wrong and what to do next — for example,
"No such file: /x/y.py. Use list_dir to see what exists."The model reads this and corrects itself. A vague error makes it try the same thing again. - A successful result never has an
errorkey. Optima relies on this: a read that returnederrordoes not count as reading the file, so it cannot unlock a write. See Path inputs. - Add a
notekey to a successful result to steer the model — for example,"No matches — check the pattern"or"40 more lines; read with offset=120".
An unhandled exception is not a disaster — the model sees the traceback, with line numbers that match your script, and usually adapts — but it is noisy and shows your internals. Wrap the body in try/except for the errors you expect, such as OSError, httpx.HTTPError, ValueError and json.JSONDecodeError.
Keeping Results Small
The model sees at most 16 KB of a result. Anything longer will be cut from the middle: the beginning and the end are kept, with a marker between them saying how much was left out. Aim for about 11,000 characters to stay well inside it.
- Limit list lengths and line counts with an input and a hard maximum.
- Shorten long values — for example,
text[:2000] + "…". - Say in
notewhat was left out and how to get it, with paging inputs such asoffsetandlimit.
Context is expensive for the model. A few well-chosen fields are better than everything.
Returning Images
A tool that makes a picture — a chart, a screenshot, a diagram — returns it in a top-level images list. Each entry has the image as base64 and its type. For example:
import base64
result = {
"summary": "Plotted 12 monthly totals; the peak is March at 4,210.",
"images": [
{"mime": "image/png", "base64": base64.b64encode(png_bytes).decode("ascii")},
],
}
- The person sees the picture; the model does not. It will be shown under the tool call in the chat. The model is only told that an image was returned, and whether it was shown. Describe the picture in the rest of the result, as
summarydoes above. - Images do not count towards the 16 KB.
- PNG, JPEG, GIF, WebP or BMP, up to 20 MB each, and at most 8 in a turn. Images are scaled and re-encoded on the way in. Anything that is not really an image will be dropped, and the model will be told it was not shown.
- Server Connectors only, for now. A Client Connector's
imagesare not lifted out, and reach the model as base64 it cannot read. - Outside a chat — on the API, in a Scheduled Task, or when an Agent runs the tool — there is nowhere to show a picture. It will be dropped and the model will be told. The rest of the result is unaffected, which is another reason to put the substance in text.
- Only this exact shape counts. An
imageskey holding anything else, such as a list of URLs, is left as you wrote it.
The Environment
Each tool runs in a controlled environment, with the following rules:
- A fresh process for every call. Nothing survives between calls: no variables, caches or open connections. Calls may run at the same time.
- The working folder. A Client tool in a conversation with a Workspace starts in that folder, and
OPTIMA_WORKSPACEholds its path. Otherwise the working folder is a shared scratch folder. Either way, treat path inputs as absolute, never write scratch files to the working folder — it may be someone's project — and usetempfilefor temporary files. - Standard input is already used by Optima. Never read from it. Run subprocesses with
stdin=subprocess.DEVNULL, and never run one that might wait for someone to type. - No questions, no progress. A tool cannot ask the person anything or report progress. It runs, then returns.
- No caller identity. A tool does not know who called it.
- Paths on a Client Connector are the person's. Their computer may run Windows, macOS or Linux, so use
os.pathorpathlibrather than writing/, andexpanduser()paths that start with~.
Environment Variables
Tools do not inherit the host's environment variables. They get only PATH, the home and temporary folders, locale and proxy settings, and a few things each platform needs. Keys and tokens in the Gateway's own environment are deliberately out of reach, and so are PYTHONPATH and the other PYTHON… variables.
If a tool needs another variable, such as JAVA_HOME, add its name under Environment variables in the Connector's details. See Creating a Connector. The Gateway's administrator can also pass variables to every tool, in Settings.
Never use a variable to reach a credential. Use an auth profile.
Packages
Tools run on Python 3.12 with the standard library and these packages, which need no setup:
httpx, requests, pydantic, psutil, python-dotenv, fastapi and uvicorn, and the packages they bring with them, such as anyio, certifi, urllib3 and idna.
For HTTP, use httpx with an explicit timeout=.
Almost every Connector that calls a web API needs nothing else: httpx covers HTTP, and json, csv, xml.etree and sqlite3 cover most formats. Add a package under Python dependencies only when you cannot reasonably do without it — for example, a vendor's SDK with signing logic. Every package is one more thing an administrator has to approve and install, and until it is installed, the Connector's tools are hidden. See Creating a Connector.
Timeouts
Each tool has a Timeout (seconds), set in its settings window. See Timeout.
Give your own network calls and subprocesses shorter timeouts than the tool's. A tool stopped by its deadline returns only what it had printed; a tool whose own HTTP call timed out can return a clean {"error": "…timed out…"}.
If a tool runs something whose length the model should choose, such as a build, give it a timeout_seconds input, enforce it in your script, and set the tool's own timeout to 0.
A Complete Example
In this example we will write a tool that searches a fictional issue tracker. It has a Constant input base_url, AI runtime inputs query, status and limit, and a Static credential profile called api.
# Search issues by text. Capped and summarised so a broad query can't flood the context.
import httpx
MAX_LIMIT = 50
MAX_TITLE = 200
def main():
base = (inputs.base_url or "").rstrip("/")
if not base.startswith(("http://", "https://")):
return {"error": "The connector's base_url setting is missing or invalid. "
"An administrator must set it in the tool's input values."}
status = (inputs.status or "open").lower()
if status not in ("open", "closed", "any"):
return {"error": f"Unknown status {status!r}. Use open, closed or any."}
limit = max(1, min(int(inputs.limit or 20), MAX_LIMIT))
try:
r = httpx.get(
f"{base}/api/v2/issues/search",
headers={**auth.api.headers(), "Accept": "application/json"},
params={**auth.api.params(), "q": inputs.query, "status": status, "per_page": limit},
timeout=30,
)
except httpx.TimeoutException:
return {"error": "Acme Tracker did not respond within 30 seconds. Try a narrower query."}
except httpx.HTTPError as e:
return {"error": f"Could not reach Acme Tracker at {base}: {e}"}
if r.status_code == 401:
return {"error": "Acme Tracker rejected the API key. An administrator must update it."}
if r.status_code >= 400:
return {"error": f"Acme Tracker returned HTTP {r.status_code}: {r.text[:300]}"}
data = r.json()
issues = [
{
"key": i.get("key"),
"title": (i.get("title") or "")[:MAX_TITLE],
"status": i.get("status"),
"assignee": (i.get("assignee") or {}).get("name"),
"updated": i.get("updated_at"),
}
for i in data.get("items", [])[:limit]
]
out = {"query": inputs.query, "total_matches": data.get("total", len(issues)),
"returned": len(issues), "issues": issues}
if not issues:
out["note"] = "No issues matched. Try fewer or different words, or status='any'."
elif out["total_matches"] > len(issues):
out["note"] = f"{out['total_matches'] - len(issues)} more matches not shown; refine the query."
return out
result = main()
Notice the following:
result = main()is at the top level.- Every expected failure returns an
errorthat says what to do next. - The list and the titles are capped.
notetells the model what it did not see.
The tool's timeout would be set to 45 seconds, above the 30-second HTTP timeout.
For Client Connectors, Optima's own Workspace Read and Workspace Write Desktop Connectors show the practices to follow. They take absolute paths, skip .git and node_modules when walking folders, refuse binary files, write through a temporary file and os.replace so that a file is never left half-written, and stop a command's whole process tree when it times out.