Repository navigation
A bug-fix release, with new docs, lllm.testing for running native agents
without a model provider, and a few additions, such as
allow_cross_site_requests, OutputSchemaError, Agent.extra_settings,
and RemoteTactic's headers=, auth=, and contract=. Some fixes
refuse requests or values that 0.4.0 accepted, raise where it did not, or
answer differently: notably browser requests and request bodies on served
tactics, a 500 for output that fails validation, parsed without its
raw key, the context manager's budget, and where the API keys you type
are stored. Each bullet says what changed and, where you need to act,
what to do. The LLLM APIs that sssn and aaax use keep their names and
signatures (create_tactic_app only gains allow_cross_site_requests),
but the changes below apply through them too, such as the cross-site
guard in create_tactic_app, the 500 that status_code_for_error() gives
for output that fails validation, and the rules for storing keys.
Tactics, agents, and prompts
format=with a Pydantic model now validates the reply with
model_validate_json, so a reply with valid JSON but wrong fields is
repaired like any parse error, with a message that names each problem
(The reply does not match Triage: team: Input should be ...). 0.4.0
only decoded the JSON, so such a reply reached your code or failed the
call at the tactic boundary.parsedis still the reply's decoded JSON
object, unfiltered, soModel.model_validate(parsed)gives the model
back (a strict model reads it with
Model.model_validate_json(json.dumps(parsed))). Invalid JSON raises
ParseErrorwith the decoder's message, and adictJSON schema as
formatneeds a JSON object, where a list used to crash. Custom
invokers that callprompt.parse()get the same.- An accepted reply's
Message.parsedno longer gets the reply text as a
rawkey: it is what theformator the parser produced (a non-dict
wrapped as{"value": ...}), so anoutput_modelwithextra="forbid"
accepts it, andPrompt.parse()with neither returns{}. 0.4.0 added
rawto a parser's result; read the text frommessage.content.
DefaultTagParserstill returns its ownraw, and a reply that fails
to parse, asinvoke_traceskeeps it, still has
parsed={"raw": <reply text>}. - The
extra_settingsagent config key reaches the agent as
Agent.extra_settings(empty by default); 0.4.0 parsed it and dropped
it. Each agent gets its own copy of the plain data in it (dicts, lists,
tuples, and sets, nested), and any other object, such as a lock or a
client, is shared as is. A value that is neither a mapping nor null
(null gives{}) raisesTypeErrorwhen the config is read, and one
nested more than 500 levels deep raisesValueError. Tactic.quick()keywords named after anAgentfield, such as
max_llm_recall,context_manager,stream_handler, orname, set
that field; the others go tomodel_args, over an explicit
model_args=. 0.4.0 sent every keyword to the provider.- Pydantic models used as tactic configs keep their
globalsection: the
field aliasedglobal(byalias,serialization_alias, or
validation_alias, includingAliasChoicesand a one-keyAliasPath)
is read asglobal, where 0.4.0 read it under its field name, such as
global_, and ignored it, so agents lost the shared settings. A field
left unset atNone, at any depth, no longer overridesglobalor the
defaults (aNoneyou set still does), and fields are read by name even
when the model serializes by alias. tactic_as_tool(..., asynchronous=True)and
Tactic.as_tool(asynchronous=True)make anasync deftool that awaits
arun(), so a Pydantic AI agent can call a tactic that runs another
Pydantic AI agent; a sync tool raisedUserErrorthere.ContextManager,DefaultContextManager,BaseStreamHandler, and
BaseInvokerare exported fromlllm.runtimes.native.copy_boundary_value()(inlllm.protocol.validation, which sssn
uses), and LLLM's copies of request envelopes and ofCallContext
metadata, copy a value nested deeper than Python's recursion limit,
where 0.4.0 raisedRecursionError.
Dialogs, sessions, and cost
- Dialogs no longer keep the agent loop's working copies.
respond()
answered each model call ondialog.fork(), so every working copy,
repairs included, stayed a child of your dialog:childrenand
tree_overview()listed them, andto_dict()saved them all, growing
quadratically with the number of turns. A dialog's messages are, as
before, the accepted exchange, and the working copies, repair prompts
included, are not kept. The rejected replies and the parse errors that
sent them back stay in the call'sAgentCallSession(invoke_traces,
exception_retries). Forks you make withfork()are listed as before. - Images go to the model with their media type (PNG, JPEG, WebP, or GIF,
read from the first bytes;image/jpegotherwise), not always
image/jpeg.put_image()uses the same check, so base64 RIFF data
that is not WebP (a WAV file, say) now raisesValueError.
Dialog.overview()shows an image as<image/png, 2.0 KB>and its
caption instead of its base64 data. - A
respond()that raises (repairs or provider retries used up, the
tool budget spent) is recorded: the exception'sagent_sessionis the
call'sAgentCallSession, withstate="failure"and nodelivery,
holding every reply, repair, and provider-error retry (rate-limit waits
are not recorded), and a tactic's session records it too. So
agent_sessions,agent_call_count, andtotal_costnow include
failed calls, which 0.4.0 left out. AgentCallSession.tool_callslists every tool call of arespond(),
with its arguments and result; a repeated identical call, which is not
run again, has no result.- Agents on OpenAI's Responses API (
api_type="response") report their
prompt, completion, cached, and reasoning tokens, and prompt and
completion costs; 0.4.0 left these at 0. str(InvokeCost)shows rates per million tokens (In: $0.15/1M tok)
instead of per token with seven decimals, and a tactic's completion log
line showscost=$0.000040instead of a raw float.- A deeply nested input no longer crashes the process that runs a native
tactic, or fails the call. Naming the session calledrepr()on the
task, which raisedRecursionErrorfor a task nested deeply enough
(from about 1,000 levels on Python 3.10 and 3.11), and on CPython 3.12
and 3.13 segfaulted on a small thread stack (1 MiB on python:alpine)
for a dict a few thousand levels deep, as one 18 KB request to a served
tactic could send. The name now hashes a bounded preview of the task
(20 levels, 10,000 values). Native tactics also run on FIPS-mode Python
and with a string task that holds a lone surrogate, which both failed
in 0.4.0. Session names keep their{tactic}_{hash}_{timestamp}form.
Strings,None, booleans, and most numbers hash as before; containers,
Pydantic models, dataclasses, bytes, and other objects hash differently
from 0.4.0.
Context manager
DefaultContextManagertrims to the model's context window:
max_tokensif given, else LiteLLM'smax_input_tokens(128,000 for
gpt-4o-mini), remembered per model once found. 0.4.0 used the output
limit fromlitellm.get_max_tokens()(16,384 for gpt-4o-mini), or 4,096
for a model LiteLLM does not know, which is below the 5,000-token
margin, so such agents sent only the system prompt. Now an unknown
model's calls are not trimmed, with one warning, andmax_tokensreads
None: setmax_tokens, or register the model withmax_input_tokens,
to trim them. An unknown model is looked up again on each call, so
registering it later takes effect. For a Hugging Face model, LiteLLM's
max_tokens(the context length in the model's config on the hub) is
still the window, as in 0.4.0, and registering the model does not
change it: setmax_tokenswhen the hub does not give it. For other
models, LiteLLM'smax_tokenscan be the output limit, so it is not
used.- The default margin kept free for the reply, 5,000 tokens, now shrinks to
half of a budget under 10,000:min(5000, max_tokens // 2). 0.4.0 always
kept 5,000, so a budget of 5,000 or less sent only the system prompt. A
SAFETY_BUFFERyou set, on an instance, a subclass, or
DefaultContextManageritself (which config-built agents use), is used
as set. - Messages are counted as they are sent, tool calls included, and whether
to trim is decided by one count of the whole dialog, as in 0.4.0. LLLM
sizes images itself: an image in a data URL is read with Pillow from its
header and costed with OpenAI's high-detail formula (765 tokens for a
1024x768 photo), and any other content part (an image whose size cannot
be read, an image URL, audio) counts asIMAGE_TOKENS(1,500), with
nothing fetched. 0.4.0 counted an image as its base64 text, about
330,000 tokens for a 356 KB photo. A message LiteLLM cannot count gets
an estimate, so counting never fails a call. - The newest message is always sent whole, with a warning when it alone
is over the budget, and a tool call and its results are kept or dropped
together, since OpenAI-compatible APIs reject a result without its
call. An older message that only partly fits keeps its end, after the
[...earlier content truncated...]marker, where 0.4.0 kept its start.
Images are never cut, which corrupted their data in 0.4.0: one that does
not fit is dropped whole, with a warning.
Testing
lllm.testinganswers native agents' model calls without a provider:
ScriptedModelreplies in order,FunctionModelanswers from each
ModelRequest, andToolCallreplies run your real tools, also for
agents that stream and agents on OpenAI's Responses API. The rest of the
agent loop runs for real. It needs thenativeextra.
Serving
- Served tactics refuse, with a 403
CrossSiteRequestErrorin the
services error envelope, a cross-sitePOSTwhoseContent-Typeis not
JSON (application/jsonor a+jsontype) to/run,/stream, their
/tactics/{name}/forms, or a custom endpoint, and a cross-siteGETto
a custom endpoint. Among them are the forms and text any web page can
make a visitor's browser send without a CORS preflight, which 0.4.0 ran,
so any page a visitor opened could run a tactic served on their
127.0.0.1. Types a browser preflights, such as
application/octet-stream, are refused too, whatever the app's CORS
settings. Send JSON, or call from the app's own origin. Sec-Fetch-Sitedecides whether a request is cross-site when present
(cross-siteandsame-siteare); otherwise anOriginthat is
null, is not http(s), or names another host and port thanHost.
Clients that are not browsers send neither header and are not affected.
PUT,PATCH, andDELETEare never refused, and the read routes
(/info,/health,/tactics, the docs) answer anyone. A cross-site
POSTwith a JSONContent-Typeneeds only the app's CORS settings;
an app whose pages on other origins must send it otherPOSTs, or
GETa custom endpoint, passesallow_cross_site_requests=True(a
bool) tocreate_tactic_apporcreate_service_app.lllm serve
keeps the guard on a tactic, but serves such an app as it is
(lllm serve module:app). The guard does not stop DNS rebinding: a
local service also needs a host allowlist or a token.- Request bodies are decoded strictly as UTF-8. A body that is not UTF-8
is a 400SchemaErrorunless itsContent-Typeis
application/octet-stream, which the tactic still gets as bytes; 0.4.0
passed such a body on as bytes unless it parsed as JSON, so JSON
holding UTF-8-encoded surrogates reached the tactic as lone surrogates.
JSON in UTF-16 or UTF-32, which 0.4.0 parsed, is no longer read as
JSON: send UTF-8 (a UTF-8 byte order mark is fine). An escaped lone
surrogate ("\ud800") is also a 400, and so is a body whose first value
nests arrays and objects more than 500 levels deep, since code that
walks such a value recursively can crash the server. - A large request body holds up other requests less: it is decoded,
depth-checked, and parsed, and an envelope in it validated and its call
context built, in a worker thread instead of on the event loop. The
tactic's input-schema validation and the trace's copy of the context
metadata still run on the event loop, in time proportional to their
size, so a public service should cap request size at its proxy. - A result that fails the tactic's output schema is a 500
OutputSchemaError, whose message starts
The output of tactic '<name>' failed validation:; 0.4.0 answered it
with a 400, as if the input were bad. Calling the tactic in process
raises it too. It is aSchemaErrorsubclass, exported fromlllmand
lllm.protocol, soexcept SchemaErrorstill catches it, and
status_code_for_error()gives 500 for it and 403 for
CrossSiteRequestError(exported fromlllm.services). - Failures that were bare 500s get the error envelope: an unknown tactic
name with;,:,%, or\, a name that is.or.., or one of
only whitespace is a 404TacticNotFound, whosetacticfield is null
since the envelope cannot hold such a name; a result that cannot be
encoded (bytes that are not UTF-8, a lone surrogate) is a 500; and a
lone surrogate in an error message is written as an escape. RemoteTactictakesheaders=andauth=(any httpx auth), sent with
every run, stream, and/inforequest; headers passed to one call are
added to them.RemoteTactic.from_service(url)(orafrom_service)
fetches/infoonce and passes it as the newcontract=: the tactic
takes the service's name (unless you passname=), andinfo()its
description, schemas, and examples wherever it has none of its own, so
a native tool made withtactic_as_function()gets the service's
parameters. A Pydantic AI tool fromtactic_as_tool()still takes its
signature frominput_type, so it gets only the description unless you
passinput_type=. The tactic's capabilities follow the service's, with
streamandeventscounted as one.RemoteTacticError.messageis
also filled from a plain FastAPI{"detail": "..."}body.
CLI and API keys
lllm serve module:attrserves a FastAPI or Starlette app, or a factory
that returns one, as it is, andlllm inspectreports it as an app with
its routes; 0.4.0 wrapped a FastAPI app in a tactic that failed on
every request, and stopped with aSchemaErrortraceback for a plain
Starlette app. A factory that returns nothing usable now stops the
command with a message that says what it returned and what it must
return.load_tactic_entrypoint()raisesTypeErrorfor an app.- A tactic or a class is never taken for an ASGI app, even one with
routesandrouterattributes, such as a routing tactic; with
Starlette installed, an app is a Starlette instance (FastAPI apps are).
0.4.0 handed such a tactic, built by a package's service entry, to
uvicorn as the app. lllm serve PKG --resource channels.NAMEwith a channel the package
does not declare is an error that lists the declared ones; 0.4.0 served
the package's whole store whatever the name. Missing services, tactics,
and runs list the declared ones too.lllm inspectbuilds a channel
package's app over a throwaway store, so it no longer creates
<pkg>/.lllm/network, and its help no longer lists--store, which it
ignores.--credentials auto, the default forlllm serveandlllm setup,
stores the keys you type in the OS keyring only when a usable one
exists, and in the env file otherwise. 0.4.0 chose the keyring whenever
keyringimported, so on headless hosts, in CI, and in containers,
where its backend cannot store anything, the key you typed was lost and
lllm serveexited 2.--credentials keyringwithout a usable keyring
stops with an error before any key is asked for.lllm serve --no-keyringstores the keys you type in the env file,
which its key check reads; 0.4.0 stored them in the keyring, then missed
them and exited 2.--no-keyring --credentials keyringis refused when
serve checks a package's keys.- Keys you type are no longer lost to an env file that cannot be written:
the file, or the folder it goes in, is checked before any key is asked
for, and it is opened without following links and emptied only after
its checks pass. A new env file is readable only by you, and an
existing one is made so only if you own it, so a shared file you can
write keeps its owner and mode. Every failure, a file that is not UTF-8
and a~that cannot be expanded included, is aCredentialError,
which the commands report with exit status 2. - An env file that is a symlink is refused even when the link is dangling
or loops: 0.4.0 read such a link as no file, then wrote the keys you
typed through it, or lost them. Sincelllm serve,inspect, and
setupread the env file (.env.localby default) for a package, a
broken.env.locallink now stops them with exit status 2; remove it,
or pass another--env-file. lllm serve,inspect,setup, andinitexit 2 with a message
instead of a traceback for a~that cannot be expanded (~typo/pkg,
or./~pkg, which pathlib reads as~pkg) in their target or
--env-file, and so doeslllm hubfor one in a--hubor--dest
path or the package path ofhub initorhub publish;serveand
inspectdo the same for a target that cannot be read
(cannot read <target>: <reason>). Called from Python,
load_manifest(),init_package(),LocalHub(), and
LocalHub.download()raiseValueErrorfor such a~, and
load_launch_app()andload_launch_api_key_requirements()raise
LaunchErrorfor one in the target, instead of pathlib's
RuntimeError. A--storepath still goes to sssn as it is, so such a
~there still ends in a traceback. Amodule:attr
target now runs from a working folder that cannot be searched (0.4.0
failed there with aPermissionErrortraceback before Python 3.14), and
one with too many dotted parts to import exits 2.
Packages and hub
lllm serveand the hub's config templates pick a resource's port by
one rule: its ownport, in itsmetadatatable or written directly
in its[services.NAME]or[tactics.NAME]table; else, for a tactic,
the first port declared by a service that serves it (bytacticor
tactics), in manifest order; else 8000.lllm serveused to read only
metadata.port, and for a tactic only services naming it intactic;
the template ignored a tactic's own port and numbered services without
one 8000, 8001, ..., so its URLs could point elsewhere. Aport
written directly in a[channels.NAME]table now counts too:
lllm serveandlllm inspectuse it where 0.4.0 used 8000.- A
[tactics.NAME]entry that is a FastAPI or Starlette app, or a
factory of one, is refused:lllm serveandlllm inspectstop with a
LaunchError, andlllm hub validatereportstactic_entry_is_app
for an app (it does not call factories), solllm hub publishrefuses
the package. 0.4.0 served a FastAPI app as a broken tactic, and stopped
on a Starlette one with aSchemaErrortraceback. Serve apps from a
[services.NAME]entry. A factory that returns nothing usable, such as
None, also stops both commands with aLaunchErrorthat says what it
returned and what it must return; 0.4.0 served the factory itself as a
tactic that failed on every request, or, when the factory's return
annotation (such as-> FastAPIor-> Tactic) has no JSON Schema,
stopped with aSchemaErrortraceback. install_package(..., alias=...)accepts underscores, as in the names
lllm createwrites (my_glossary); an alias still starts and ends
with a lowercase letter or a digit.- Agent cards put a blank line before
## Resourcesafter tags, safety,
or latency lines.
Proxies and run_python
run_pythoncaptures each call's output on its own: calls that run at
once, as underbcall, no longer mix their output, your program's
prints no longer end up in a call, and when the last call's code ends,
sys.stdoutis your program's stream again (after overlapping calls,
0.4.0 could leave it at a finished call's buffer, losing later prints).
A call captures what its code prints, including endpoint methods
CALL_APIruns and threads the code starts; your program's other
threads print to your program. The code's own redirects
(redirect_stdout, doctest) work, but are process-wide while they last.
The first call installs athreading.Thread.starthook that stays for
the life of the process, and a timed-out call's output is dropped until
its code ends. The Proxies page lists the rules and their limits.- Long
run_pythonoutput keeps its start and its end, half of
max_output_charseach, around the truncation indicator, so the end of
a traceback survives; 0.4.0 kept only the start. The interpreter-mode
proxy prompt and therun_pythontool description now tell the model
so, where they said to print the most important data first. use_cache=Falseskips writing the HTTP cache too, not just reading it,
incall_apiand in the Exa proxy's own cache. POST responses are never
cached: 0.4.0 cached them and answered repeats from the cache, so
repeated POSTs now reach the API. Plain (non-JSON) responses are not
cached; writing one failed, which broke the Wolfram Alpha proxy on every
call.- A POST endpoint whose API key is a query parameter sends the key in the
URL; 0.4.0 put it in the JSON body. - A params value that
dict()cannot take stands for the endpoint's only
parameter, or its only required one, so
CALL_API("tools/summarize", text)works; 0.4.0 failed indict().
Params are anythingdict()takes: a mapping, a Pydantic model, an
object withkeys(), or(name, value)pairs; 0.4.0 also needed a
truth value, so it failed on apandas.Series. Where the endpoint takes
no lone value, a falsy one still means no params, and any other raises
aTypeErrorthat lists the endpoint's parameters. CALL_APImerges keyword params into the positional params, a lone
value included: 0.4.0 dropped them, so
CALL_API("tools/summarize", {"text": text}, style="short")lost
style. More than one positional params value raisesTypeError
instead of being ignored.- A name in
activate_proxiesthat matches no registered proxy logs a
warning that names it, lists the registered proxies, and points to
load_builtin_proxies(); 0.4.0 skipped it silently. - Proxies work under test doubles: an endpoint method wrapped by a spy
(mock.patch.object(proxy, name, wraps=...)) keeps its endpoint
metadata, and a proxy whosecallis replaced by a mock still lists
its endpoints. 0.4.0 listed the spy's made-up metadata, or raised
TypeErrorwhen the proxy had other endpoints, and failed to list
endpoints next to the mock. Amocker.spyof an endpoint method still
hides the endpoint, as in 0.4.0: its autospec stand-in carries no
endpoint metadata, so spy withwraps=instead.
Sandbox
JupyterSession.launch_server()finds Notebook 7's server URL
(/tree?token=..., or one without a token) and returns the notebook's
URL; 0.4.0 could hang there. The wait has a real deadline,
launch_server(timeout=20), and the server's log is drained after
startup, so a chatty server cannot block on a full pipe.
Extras
- The
sandboxextra installsipykernel; without a kernel, Jupyter
sessions could not run cells. lllm-core[all]lists PyYAML, which thenativeextra needs. It was
only installed as a dependency of other packages.
Docs
- New docs at lllm.one, organized by task: Get started, a guide (agents,
prompts, tools, dialogs, tactics, typed I/O, configuration, streaming,
models, inference hints, proxies, sandbox), production (serving,
testing, observability, packages, the hub), integrations (Pydantic AI,
other runtimes), four complete examples, and an API reference whose
Python pages are generated from the code (thedocsextra adds
mkdocstrings[python]). Nearly every Python example runs in the test
suite, which checks the output each page shows. The old tutorial, core,
protocol, packages, and reference pages redirect to their new homes. - The pages state this release's rules: Serving covers requests from
browsers and DNS rebinding (with aTrustedHostMiddlewareexample),
the body rules, and the status codes; Dialogs covers what the context
manager counts and sends, and when LiteLLM downloads a tokenizer for
Llama and Replicate models and how to stop it; Proxies covers what
run_pythoncaptures; Observability covers what sessions and dialogs
hold.
pip install -U "lllm-core[native]" # the native runtime
pip install -U "lllm-core[native,network,shell]" # with SSSN and AAAXDocs: https://lllm.one · SSSN: https://sssn.one · AAAX: https://aaax.one
🤖 Generated with Claude Code