split_model_path
def split_model_path(
model, model_path:NoneType=None
):Split a model name, minus any runtime prefix, into (model_id, model_path): a Hub repo id or a local file path.
Split a model name, minus any runtime prefix, into (model_id, model_path): a Hub repo id or a local file path.
Cancel the pending read nxt, then close the async iterator ait, and return True when the read ended without an error of its own and the close finished cleanly, within wait seconds in all. Nothing here cancels a wait, since a cancelled close would cut short the SDK’s own grace, terminate and kill. A read or close that fails or runs past wait gives False; the close task is left running.
Wait until task is done, timeout seconds pass or the threading.Event cancel is set, and return whether task is done. Never cancels task.
A oneshot or oneshot_stream call ended because cancel() was called, or because its provider stream could not be confirmed closed. elapsed is the seconds it ran, read after the close. stopped is False when the provider call did not end within the wait and may still finish and spend. Nothing is retried, and text yielded before it is a partial reply, never a successful one.
One call’s UsageStats from a usage dict as norm_claude_usage or norm_completion gives it; empty when u is empty.
The base class for rishi backends that drive Urai’s tool loop, with the usage, tool-reminder and sliding-window callbacks on by default.
Backend modules import the shared types, such as Chat, ChatOpts and Resp, from urai directly. The tests below check that importing rishi.core registers the runtimes and does not copy Urai’s namespace.
RishiToolLoop is the base class for the backends that drive Urai’s tool loop. These are llama.cpp, MLX, Ollama, the hosted API and Claude Code. Copilot uses it through the hosted API class. LiteRT-LM does not use it, because the LiteRT-LM engine runs tools itself. RishiToolLoop turns on three callbacks by default. UsageCallback counts token usage. ToolReminderCallback reminds the model which tools it has. SlidingWindowCallback removes old messages when the context window is full.
split_model_path turns a model name into a Hugging Face repo id or a local file path. It removes any runtime prefix first. An explicit model_path argument takes priority over a path in the name. The LiteRT-LM, llama.cpp and MLX backends call it. The Ollama backend does not.
import importlib, importlib.util, threading
from fastcore.aio import run_sync
import rishi, rishi.core, urai
test_eq(rishi.Chat is urai.Chat, True)
test_eq(hasattr(rishi.core, 'Chat'), False)
for mod in ('llama', 'mlx', 'remote', 'claude', 'copilot', 'ollama'):
if mod == 'mlx' and not importlib.util.find_spec('mlx'): continue # Apple Silicon only
public = importlib.import_module(f'rishi.{mod}').__all__
assert 'Chat' not in public and 'UsageStats' not in publictest_eq(split_model_path(None), (None, None))
test_eq(split_model_path('mlx-community/Qwen3-4B-4bit'), ('mlx-community/Qwen3-4B-4bit', None))
test_eq(split_model_path('mlx/mlx-community/Qwen3-4B-4bit'), ('mlx-community/Qwen3-4B-4bit', None))
test_eq(split_model_path('model.gguf'), (None, 'model.gguf'))
test_eq(split_model_path('repo/id', 'given/path.gguf'), ('repo/id', 'given/path.gguf'))OneShotCancelled is what oneshot and oneshot_stream raise when cancel() ends them, from any thread and whether the call waits for its first chunk or a later one. Text a stream yielded before it is a partial reply, and a cancelled oneshot returns nothing. stopped is False when the provider call did not end within CLOSE_WAIT seconds and may still spend. shut_stream closes a stream within that bound and never cancels the close: Claude Code’s SDK shields its close from anyio cancellation, not from asyncio cancellation, so a cancelled close skips its terminate and kill.
done = []
async def _slow_close():
try: yield 1; await asyncio.sleep(10)
finally: await asyncio.sleep(.4); done.append('closed')
async def _probe():
ait = _slow_close().__aiter__()
await ait.__anext__()
t = time.monotonic()
ended = await shut_stream(ait, wait=.1)
early = time.monotonic() - t < .3
await asyncio.sleep(.6)
return ended, early, done[:]
# a close that outlasts its wait is reported as unfinished and left running, not cancelled
test_eq(run_sync(_probe()), (False, True, ['closed']))
async def _poll():
flag = threading.Event(); t = asyncio.ensure_future(asyncio.sleep(10))
flag.set()
r = await read_or_cancel(t, flag)
pending = not t.done(); t.cancel()
return r, pending
# a set cancel flag ends the wait at once and leaves the task running
test_eq(run_sync(_poll()), (False, True))Urai runs the Python code that a model writes through SafePyRun. SafePyRun up to version 0.2.6 runs each block of code with separate global and local namespaces. A function defined in the block cannot see a module imported in the same block. For example, import math followed by a function that calls math.sqrt fails with a NameError. rishi replaces the SafePyRun runner with one that uses a single namespace. The replacement can be removed when SafePyRun fixes this.
The host’s __name__ and __builtins__ survive a block that raises or fails to parse:
A Caps record lists the kinds of input and output a model takes. You can check it before you send a picture to a model. Urai reads the Caps record of a hosted model from the fastllm model table. Local models have no such table. Each local runtime supplies a function that inspects the model. litert_caps reports text, image and audio for every LiteRT-LM model. LiteRT-LM builds the vision and audio encoders whenever multimodal input is on. ollama_caps_ asks the Ollama daemon, which holds the model weights.
Ask the Ollama daemon what model accepts, or return None when the Ollama backend cannot be imported.
Report text, image and audio input for any LiteRT-LM model.
BACKENDS holds one Runtime record per backend. A record has the backend name, the class that implements it, a capabilities function, and the name patterns that identify its models. Urai imports the class when the backend is first used. When Chat gets a model name and no runtime, Urai tries the patterns in list order and takes the first match. Ollama comes before llama.cpp in the list. The id hf.co/unsloth/Qwen3-4B-GGUF contains gguf, but it is an Ollama id and not a file for llama.cpp. LiteRT-LM is the default when no model is named.
Claude Code and Copilot have no patterns, because their model names look like hosted model names. Choose them with a claude/ or copilot/ prefix, or with runtime='claude' or runtime='copilot'. The tests below show which names go to which backend. A name that matches no pattern raises an error.
test_eq(list(RUNTIMES), ['litert', 'ollama', 'llama', 'mlx', 'remote', 'claude', 'copilot'])
test_eq(infer_runtime('gemma-3n-E4B.litertlm'), 'litert')
test_eq(infer_runtime('hf.co/unsloth/Qwen3-4B-GGUF'), 'ollama') # asked before llama
test_eq(infer_runtime('qwen3-4b-Q4_K_M.gguf'), 'llama')
test_eq(infer_runtime('mlx-community/Qwen3-4B-4bit'), 'mlx')
test_eq(infer_runtime('gpt-5.1'), 'remote')test_eq(resolve_runtime('claude-sonnet-4.6'), ('remote', 'claude-sonnet-4.6'))
test_eq(resolve_runtime('claude/claude-sonnet-4.6'), ('claude', 'claude-sonnet-4.6'))
test_eq(resolve_runtime()[0], 'litert') # nothing named: the default runtime
test_fail(lambda: resolve_runtime('some-unknown-name'), contains="Can't tell which backend")A plain pip install rishi must load every runtime that is not optional. Each package that such a runtime imports must be in pyproject.toml, or must come with a package that is in it. Before 0.1.68, the remote and copilot backends imported fastspec, but rishi did not declare it. Most installs got fastspec from another package, so the error showed only in a project that had rishi alone.
The test reads the source of each runtime module and of the rishi modules it imports. It collects the names of the packages it imports. It ignores the standard library and the imports in a try block that catches ImportError, because rishi can run without them. Then it compares the packages with the declared dependencies and with what those dependencies always install.
def _norm(n): return re.sub(r'[-_.]+', '-', n).lower()
def _req_name(s): return _norm(re.match(r'[\w.\-]+', s)[0])
def _guarded(tree):
"Nodes inside a `try` that catches `ImportError`: imports rishi can do without."
tries = [t for t in ast.walk(tree) if isinstance(t, ast.Try)
and any(isinstance(h.type, ast.Name) and h.type.id in ('ImportError', 'ModuleNotFoundError') for h in t.handlers)]
return {id(n) for t in tries for b in t.body for n in ast.walk(b)}
def _mod_imports(mod, seen=None):
"Top-level names of the packages `mod` needs, following its imports of other rishi modules."
seen = set() if seen is None else seen
if mod in seen: return set()
seen.add(mod)
tree = ast.parse(Path(importlib.util.find_spec(mod).origin).read_text())
skip,res = _guarded(tree),set()
for n in ast.walk(tree):
if id(n) in skip: continue
if isinstance(n, ast.Import): names = [a.name for a in n.names]
elif isinstance(n, ast.ImportFrom): names = [f'rishi.{n.module}' if n.level else n.module]
else: continue
for o in names:
if o.startswith('rishi.'): res |= _mod_imports(o, seen)
elif o != 'rishi': res.add(o.split('.')[0])
return res - set(sys.stdlib_module_names)
def _dep_closure(reqs):
"Distributions that installing `reqs` always brings, leaving out extras."
todo,res = [_req_name(r) for r in reqs],set()
while todo:
if (d := todo.pop()) in res: continue
res.add(d)
try: todo += [_req_name(r) for r in im.requires(d) or [] if 'extra ==' not in r]
except im.PackageNotFoundError: pass
return res
proj = tomllib.loads(Path('../pyproject.toml').read_text())['project']
pkg2dist = im.packages_distributions()
def _undeclared(mods, deps): return sorted(m for m in mods if not {_norm(d) for d in pkg2dist.get(m, [m])} & deps)The remote backend needs fastspec, and through it copilot too. A runtime that is not optional must need nothing more than the core dependencies:
Of the optional runtimes, only llama and mlx need an extra. A plain install loads litert and ollama too:
Some functions moved from rishi to Urai and got new names. The old names remain as aliases. For example, mk_oai_msg is an alias of mk_msg, and browser_approval is an alias of http_approval. Use Urai’s names in new code, as the rishi backends do.
Deprecated alias for urai.use_system_certs.
The wheel includes a skill.md file that tells a coding agent how to use rishi. mv_skill_md copies it to .agents/skills/rishi/SKILL.md and .claude/skills/rishi/SKILL.md, where agents look for skills. The target root is the dir argument if you pass one. Otherwise it is the root of the current git repository, found by repo_root. Outside a repository, the target root is the current folder. repo_root returns None outside a repository. By default mv_skill_md prints the target paths and copies nothing. Pass dry_run=False to copy. If mv_skill_md finds no skill.md, it returns without output.
Copy the bundled skill.md into the repository’s .agents and .claude skill directories, or only print the targets while dry_run is True.
Root of the current git repository, or None if not in one.