Skip to main content

remote

Hosted models such as GPT, Claude and Gemini through fastllm, with the same Chat API as the local backends.
import threading
from fastcore.test import test_eq, test_fail, test_close
from fastllm.types import Usage

Messages

fastllm represents a message as Msg(role, content=[Part, ...]). Each part has a type: text, thinking, tool_use, tool_result, input_image or input_audio. An image or audio part holds a data URL in part.text. rishi’s history uses OpenAI-shaped dicts.

to_msg converts one history message to a Msg. to_hist converts a Msg back and returns a list, because one tool Msg can hold several results.

The conversion keeps images and audio as data URLs. It does not replace them with placeholders, so media survives a move between backends. Thinking also survives. rishi stores it in channels['thought'], and fastllm stores it as a thinking part.

When a message mixes text and media, to_hist joins all the text into one part and puts it first. The test below shows this.


source

to_hist

def to_hist(
    m
):

Convert a fastllm Msg to a list of rishi history messages, since a tool Msg can hold several results.


source

to_msg

def to_msg(
    m
):

Convert one rishi history message to a fastllm Msg.

# a round trip through fastllm's Msg keeps text, thinking, tool calls and tool results intact
h = [{'role': 'user', 'content': 'what is 2+2?'},
     {'role': 'assistant', 'content': 'let me add', 'channels': {'thought': 'hmm'},
      'tool_calls': [ToolCall('add', {'a': 2, 'b': 2}, id='c1')]},
     {'role': 'tool', 'tool_call_id': 'c1', 'name': 'add', 'content': '4'},
     {'role': 'assistant', 'content': 'it is 4'}]
msgs = [to_msg(m) for m in h]
test_eq([m.role for m in msgs], ['user', 'assistant', 'tool', 'assistant'])
back = [x for m in msgs for x in to_hist(m)]
test_eq(back[0], {'role': 'user', 'content': 'what is 2+2?'})
test_eq(back[1]['channels'], {'thought': 'hmm'})
test_eq(back[1]['tool_calls'][0].name, 'add')
test_eq(back[1]['tool_calls'][0].arguments, {'a': 2, 'b': 2})
test_eq(back[2], {'role': 'tool', 'tool_call_id': 'c1', 'name': 'add', 'content': '4'})
test_eq(back[3], {'role': 'assistant', 'content': 'it is 4'})

# reverse conversion groups text first, then images and audio
mixed = [{'type': 'text', 'text': 'before'},
         {'type': 'image_url', 'image_url': {'url': 'data:image/png;base64,iVBORw0KGgo='}},
         {'type': 'image_url', 'image_url': {}},
         {'type': 'unknown'},
         {'type': 'text', 'text': 'between'},
         {'type': 'input_audio', 'input_audio': {'data': 'UklGRg==', 'format': 'wav'}},
         {'type': 'input_audio', 'input_audio': {}},
         {'type': 'text', 'text': 'after'}]
m = to_msg({'role': 'user', 'content': mixed})
test_eq([p.type for p in m.content], ['text', 'input_image', 'input_image', 'text', 'input_audio', 'input_audio', 'text'])
rt = to_hist(m)[0]
test_eq([p['type'] for p in rt['content']], ['text', 'image_url', 'image_url', 'input_audio', 'input_audio'])
test_eq(rt['content'][0]['text'], 'beforebetweenafter')
test_eq(rt['content'][1]['image_url']['url'], m.content[1].text)
test_eq(rt['content'][2]['image_url']['url'], m.content[2].text)
test_eq(rt['content'][3]['input_audio']['format'], 'wav')

# a server-side tool call keeps its flag across the hop
sm = to_msg({'role': 'assistant', 'content': '', 'tool_calls': [ToolCall('web_search', {}, id='s1', server=True)]})
assert to_hist(sm)[0]['tool_calls'][0].server

Responses and usage

norm_completion converts a fastllm Completion to a rishi Resp. It reads tool calls that the model wrote into its text as <tool_call> tags. It sets truncated when the reply hit the token limit. It adds token usage from norm_usage.

cached_tokens is set when the provider reports prompt caching. reasoning_tokens and cache_creation_tokens appear only when the provider reports them. A local backend’s usage dict does not change.

Some models generate images. fastllm’s message parts describe inputs only. gen_media searches the provider’s raw response for generated images in the shapes that Gemini, the OpenAI Responses and Images APIs, and LiteLLM use. norm_completion stores what it finds in Resp['media'] as {mime, data} dicts. It does not change the text.


source

norm_completion

def norm_completion(
    comp
):

Convert a fastllm Completion to a rishi Resp, also reading tool calls written as <tool_call> tags in the text.


source

gen_media

def gen_media(
    raw
):

Collect the images a model generated from the provider’s raw response, Completion.raw, as {mime, data} dicts.


source

norm_usage

def norm_usage(
    u, model:NoneType=None
):

Convert fastllm Usage to a rishi usage dict, keeping reasoning and cache-write counts when the provider reports them.

from base64 import b64encode

png = b'\x89PNG\r\n\x1a\n' + b'fake'
b64 = b64encode(png).decode()

# Gemini native, camelCase and snake_case, however deep the candidate sits
test_eq(gen_media({'candidates': [{'content': {'parts': [
    {'text': 'here you go'}, {'inlineData': {'mimeType': 'image/png', 'data': b64}}]}}]}),
    [{'mime': 'image/png', 'data': png}])
test_eq(gen_media({'candidates': [{'content': {'parts': [
    {'inline_data': {'mime_type': 'image/webp', 'data': b64}}]}}]}),
    [{'mime': 'image/webp', 'data': png}])

# the OpenAI-shaped route litellm normalises Gemini's image output onto
test_eq(gen_media({'choices': [{'message': {'content': 'done',
    'images': [{'image_url': {'url': f'data:image/png;base64,{b64}'}}]}}]}),
    [{'mime': 'image/png', 'data': png}])

# the Responses API image tool, and the Images API
test_eq(gen_media({'output': [{'type': 'image_generation_call', 'result': b64}]}),
        [{'mime': 'image/png', 'data': png}])
test_eq(gen_media({'data': [{'b64_json': b64}]}), [{'mime': 'image/png', 'data': png}])

# a plain text reply carries nothing, and neither does a missing `raw`
test_eq(gen_media({'choices': [{'message': {'content': 'just words'}}]}), [])
test_eq(gen_media(None), [])

# the same image reached by two routes in one payload is still one image
test_eq(len(gen_media({'candidates': [{'content': {'parts': [{'inlineData': {'mimeType': 'image/png', 'data': b64}}]}}],
                       'choices': [{'message': {'images': [{'image_url': {'url': f'data:image/png;base64,{b64}'}}]}}]})), 1)

# and it rides on `Resp.media`, leaving `content` alone
r = norm_completion(Completion(model='m', usage=Usage(prompt_tokens=1, completion_tokens=2),
        message=Msg(role='assistant', content=[Text(text='here')]),
        raw={'candidates': [{'content': {'parts': [{'inlineData': {'mimeType': 'image/png', 'data': b64}}]}}]}))
test_eq(r['content'], 'here')
test_eq(r['media'], [{'mime': 'image/png', 'data': png}])

# a caller may hand in anything Completion-shaped; `raw` is newer than the function and
# must not become a requirement -- ramabana's routing test builds one without it
class _NoRaw:
    model, usage, finish_reason, tool_calls = 'm', None, 'stop', None
    message = Msg(role='assistant', content=[Text(text='hi')])
test_eq(norm_completion(_NoRaw())['content'], 'hi')
assert 'media' not in norm_completion(_NoRaw())

RemoteChat

RemoteChat runs fastllm’s async client from synchronous code. It uses Urai’s run_coro and sync_iter. With no model named, it uses dflt_remote, which is gpt-5.1.

max_output_tokens sets the output cap. Without it, the cap is the maximum that fastllm’s model table gives for the model. For a model that is not in the table, the cap is DFLT_MAX_TOKENS, 16,000. A reasoning model spends its thinking from the same cap. A small cap cut its tool calls short.

These options exist only on RemoteChat:

  • tool_choice forces one tool. The value 'required' forces any tool.
  • effort sets the provider’s reasoning effort. reasoning_effort is an accepted alias.
  • tool_mode='native' is the default. It sends tool schemas in the API’s tools field.
  • tool_mode='tags' writes the tool schemas into the system prompt and reads <tool_call> tags from the reply. Use it for a provider that has no tools field.
  • vendor_name and api_name override the vendor and the API that fastllm infers from the model id.

You can pass tool_mode for a single turn, streamed or not.

When the provider’s API lacks the effort level you set, the chat sends the level that EFFORT_MAP names. max becomes xhigh on OpenAI and Azure. xhigh and max become high on Gemini.

When a provider refuses the effort with a 400, the chat repeats the call once without it. dropped_effort then holds the reason, and the chat sends no effort. Set dropped_effort back to None to send effort again.

A one-shot call with think=False sends no effort, so the model runs at its default: NO_THINK_EFFORT is None. Some models refuse 'minimal', and a refusal costs one more call. A deployment whose provider takes a lowest effort can set NO_THINK_EFFORT to it; when the provider refuses it, the call goes again without.

You can name a Gemini model with or without models/, as in gemini-3.5-flash, gemini/gemini-3.5-flash or models/gemini-3.5-flash. Gemini’s API puts the model in the URL and answers 404 without that prefix. The chat adds the prefix to the request. model_id stays as you gave it.

Some providers run tools on their own side, such as web search. Those calls come back marked server=True. The chat records them in the history. rishi does not run them.

A vendor in STREAM_ONLY answers only streamed requests. At present the only such vendor is codex. For it, the chat streams every request and collects the result.

Azure OpenAI’s v1 API works through base_url. Set these values:

  • base_url: https://<resource>.openai.azure.com/openai/v1
  • model: the deployment name
  • api_key: the Azure key
  • api_name='openai' for the Responses API

The chat sends no api-version. The v1 API needs none.

On the chat-completions route, api_name='openai_chat', an Azure reasoning deployment refuses max_tokens. For a host in MAX_COMPLETION_HOSTS, the chat sends the output cap as max_completion_tokens. Every Azure model accepts that field.


source

RemoteChat

def RemoteChat(
    model:NoneType=None, *, runtime:NoneType=None, model_path:NoneType=None, opts:NoneType=None,
    vendor_name:NoneType=None, # override the vendor fastllm infers from the model id
    api_name:NoneType=None, # override the api name fastllm infers
    tool_choice:NoneType=None, # force a particular tool, or 'required'
    retries:int=2, comp_kw:NoneType=None, # passed to `acomplete` verbatim
    **kw
):

A Chat that sends each turn to a hosted model API through fastllm.


source

effort_refused

def effort_refused(
    e
):

Whether e is a provider’s 400 that names the reasoning effort (effort, reasoning_effort, reasoning.effort).


source

cut_args

def cut_args(
    e
):

Whether the JSON in e ended early, as arguments cut off at the output cap do, rather than being malformed.


source

args_error

def args_error(
    e
):

Whether the JSONDecodeError e came from fastllm decoding a model’s tool-call arguments.

A one-shot prompt can be a list, as ramabana’s Agent.compose gives: the picture bytes, then the text. Both parts reach the model.

import io
from PIL import Image
_b = io.BytesIO(); Image.new('RGB', (8, 8), 'white').save(_b, 'PNG')
_m = to_msg(mk_msg([_b.getvalue(), 'Find its labels.']))   # what `_oneshot_args` builds now
test_eq([p.type.value for p in _m.content], ['input_image', 'text'])
test_eq([p.type.value for p in to_msg(mk_msg('hi')).content], ['text'])   # a plain text prompt is as before
def _add(a: int, b: int) -> int:
    'Add a and b.'
    return a + b

# native puts the schemas on the wire; tags puts them in the system prompt and leaves the field empty
kw = RemoteChat('gpt-5.1', tools=[_add], sp='Be terse.')._kw()
test_eq([t['function']['name'] for t in kw['tools']], ['_add'])
test_eq(kw['system'], 'Be terse.')

kw = RemoteChat('gpt-5.1', tools=[_add], sp='Be terse.', tool_mode='tags', tool_choice='required')._kw()
assert 'tools' not in kw and 'tool_choice' not in kw
assert kw['system'].startswith('Be terse.') and '"name": "_add"' in kw['system']

# Parse tagged calls without dropping surrounding text.
def _comp(text):
    return Completion(model='m', usage=Usage(prompt_tokens=1, completion_tokens=2),
                      message=Msg(role='assistant', content=[Text(text=text)]))
r = norm_completion(_comp('on it\n<tool_call>{"name": "_add", "arguments": {"a": 1, "b": 2}}</tool_call>'))
test_eq(resp_text(r), 'on it')
test_eq((r['tool_calls'][0].name, r['tool_calls'][0].arguments), ('_add', {'a': 1, 'b': 2}))
test_eq(norm_completion(_comp('just prose')).get('tool_calls'), None)

# provider-billed reasoning and cache-write token counts appear only when the provider reports them
u = Usage(prompt_tokens=10, completion_tokens=5, cached_tokens=4, reasoning_tokens=7, cache_creation_tokens=3)
test_eq(norm_usage(u, 'm'), {'prompt_tokens': 10, 'completion_tokens': 5, 'total_tokens': 15,
                             'cached_tokens': 4, 'model': 'm', 'reasoning_tokens': 7, 'cache_creation_tokens': 3})
test_eq(set(norm_usage(Usage(prompt_tokens=1, completion_tokens=1), 'm')),
        {'prompt_tokens', 'completion_tokens', 'total_tokens', 'cached_tokens', 'model'})

us = UsageStats(**norm_usage(u)) + UsageStats(**norm_usage(u))
test_eq((us.reasoning_tokens, us.cache_creation_tokens, us.cached_tokens), (14, 6, 8))
assert 'reasoning=14' in repr(us) and 'cache_write=6' in repr(us)
test_eq(sum_usage([norm_usage(u), norm_usage(u)])['reasoning_tokens'], 14)
assert 'reasoning_tokens' not in sum_usage([{'prompt_tokens': 1}])   # absent, not zero, when nothing was reported
# codex answers a streamed request and refuses every other one (400 "Stream must be set to true"),
# so the calls that are not already streams have to be gathered from one
class _Stop(Exception): pass
def _fake(msgs, model, **kw):
    async def go(): raise _Stop(kw.get('stream'))
    return go()

def _streamed(chat, fn):
    try: fn(chat)
    except _Stop as e: return e.args[0]

_real, acomplete = acomplete, _fake
try:
    codex, plain = RemoteChat('codex/gpt-5.5'), RemoteChat('gpt-5.1')
    test_eq((codex._stream_only, plain._stream_only), (True, False))
    test_eq(_streamed(codex, lambda c: c._model_step()), True)
    test_eq(_streamed(plain, lambda c: c._model_step()), False)
    test_eq(_streamed(codex, lambda c: c._oneshot('hi')), True)
    test_eq(_streamed(codex, lambda c: c._structured_call('hi', _add, '')), True)
    test_eq(_streamed(plain, lambda c: c._structured_call('hi', _add, '')), False)
finally: acomplete = _real
# Azure's chat-completions route refuses `max_tokens` from a reasoning deployment, so the cap goes out as
# `max_completion_tokens` there; its Responses route and every other host keep `max_tokens`
az = 'https://res.openai.azure.com/openai/v1'
kw = RemoteChat('gpt-5.4', base_url=az, api_key='k', api_name='openai_chat', max_output_tokens=900)._kw()
test_eq(('max_tokens' in kw, kw['xtra_body']), (False, {'max_completion_tokens': 900}))
kw = RemoteChat('gpt-5.4', base_url=az, api_key='k', api_name='openai_chat', comp_kw={'xtra_body': {'store': False}})._kw()
mx54 = get_model_info('gpt-5.4')['max_output_tokens']   # a model fastllm knows asks for its own maximum
test_eq(kw['xtra_body'], {'max_completion_tokens': mx54, 'store': False})
test_eq(RemoteChat('gpt-5.4', base_url=az, api_key='k', api_name='openai')._kw()['max_tokens'], mx54)
test_eq(RemoteChat('m', base_url='https://res.openai.azure.us/openai/v1', api_key='k', api_name='openai_chat')._max_completion, True)
test_eq(RemoteChat('m', base_url='https://api.example.com/v1', api_key='k', api_name='openai_chat')._kw()['max_tokens'], DFLT_MAX_TOKENS)

# the request itself: the deployment as the model, Bearer auth, `/openai/v1/responses`, no `api-version`
import fastllm.acomplete as fa
from fastllm.acomplete import mk_client
seen, _req = {}, fa.provider_req
async def _fake_req(cli, path, body, params=None, stream=False, **kw):   # newer fastllm passes `headers`
    seen.update(url=cli._url(path), params=params, body=body)
    return {'output': [{'type': 'message', 'role': 'assistant', 'content': [{'type': 'output_text', 'text': 'pong'}]}],
            'usage': {'input_tokens': 5, 'output_tokens': 1, 'total_tokens': 6}, 'status': 'completed'}
fa.provider_req = _fake_req
try: r = RemoteChat('gpt-5.4', base_url=az, api_key='k', api_name='openai')('ping')
finally: fa.provider_req = _req
test_eq((seen['url'], seen['params'], seen['body']['model'], seen['body']['max_output_tokens']), (f'{az}/responses', None, 'gpt-5.4', mx54))
test_eq((resp_text(r), r['usage']['prompt_tokens']), ('pong', 5))
test_eq(mk_client('gpt-5.4', api_name='openai', api_key='k', base_url=az)[0].transport.base_headers['Authorization'], 'Bearer k')

A tool call that does not decode

fastllm decodes a model’s tool-call arguments before rishi sees the reply. It raises JSONDecodeError when the arguments are not whole JSON. The usual cause is the output cap: the model ran out of tokens while it wrote the call.

args_error checks that the error came from one of the fastllm functions in ARG_SITES. rishi raises any other decode error unchanged. cut_args tells a cut-off call from a malformed one.

A cut-off call goes back to the model with urai’s cut_msg_. The next step runs at CUT_CAP_MULT times the cap, up to the most that fastllm says the model can write. A malformed call goes back with the decoder’s error message.

A reply cut off while the model was still thinking, with no text and no call, goes back the same way and uses the same single resend. A second failure in the turn raises ToolCallError with the reason.

# a tool call cut off at the output cap, or not JSON at all, goes back to the model rather than killing the turn
# with fastllm's bare `JSONDecodeError`; the step after a cut-off call gets `CUT_CAP_MULT` times the cap
import fastllm.acomplete as fa
from fastcore.xtras import dict2obj
from urai import cut_msg_
def _wf(path: str, content: str) -> str:
    'Write content to path.'
    return f'wrote {len(content)}'
_CUT, _BAD, _OK = '{"path": "a.txt", "content": "it stops', '{"path": "a.txt" "content": "x"}', '{"path": "a.txt", "content": "whole"}'
def _resp(args):    # a Responses reply, its call cut short when `args` is
    if args is None: return {'output': [{'type': 'message', 'role': 'assistant', 'content': [{'type': 'output_text', 'text': 'done'}]}], 'status': 'completed',
                             'usage': {'input_tokens': 5, 'output_tokens': 1, 'total_tokens': 6}}
    return {'output': [{'type': 'function_call', 'call_id': 'c1', 'id': 'fc1', 'name': '_wf', 'arguments': args}],
            'usage': {'input_tokens': 5, 'output_tokens': 9, 'total_tokens': 14}, 'status': 'incomplete' if args == _CUT else 'completed'}
def _cc(args):      # a chat-completions reply
    m = {'role': 'assistant', 'content': 'done'} if args is None else {'role': 'assistant', 'content': None, 'tool_calls': [{'id': 'c1', 'type': 'function', 'function': {'name': '_wf', 'arguments': args}}]}
    return {'choices': [{'index': 0, 'message': m, 'finish_reason': 'stop' if args is None else 'length' if args == _CUT else 'tool_calls'}],
            'usage': {'prompt_tokens': 5, 'completion_tokens': 9, 'total_tokens': 14}}
def _chunks(args):  # a chat-completions stream: some prose, then the call in pieces, then `length` when it was cut
    yield {'choices': [{'index': 0, 'delta': {'role': 'assistant', 'content': 'Writing it.'}}]}
    if args is None: yield {'choices': [{'index': 0, 'delta': {}, 'finish_reason': 'stop'}]}; return
    for i in range(0, len(args), 8):
        f = {'arguments': args[i:i+8]} | ({'name': '_wf'} if not i else {})
        yield {'choices': [{'index': 0, 'delta': {'tool_calls': [{'index': 0, 'id': 'c1' if not i else None, 'type': 'function', 'function': f}]}}]}
    yield {'choices': [{'index': 0, 'delta': {}, 'finish_reason': 'length' if args == _CUT else 'tool_calls'}]}
def _wire(*script):
    "A fake `provider_req` answering with `script` in order, and the request bodies it saw."
    bodies, it = [], iter(script)
    async def req(cli, path, body, params=None, stream=False, **kw):
        bodies.append(body); a = next(it)
        if isinstance(a, Exception): raise a
        if not stream: return dict2obj((_cc if 'chat' in path else _resp)(a))
        async def ev():
            for c in _chunks(a): yield dict2obj(c)
        return ev()
    return req, bodies
def _run(chat, *script, stream=False):
    req, bodies = _wire(*script)
    _req, fa.provider_req = fa.provider_req, req
    try: r = chat('go', stream=stream); r = ''.join(r) if stream else r
    finally: fa.provider_req = _req
    return r, bodies
_resps = lambda **kw: RemoteChat('gpt-5.4', api_key='k', tools=[_wf], max_output_tokens=1000, **kw)
_chats = lambda **kw: RemoteChat('gpt-5.4', base_url='https://x.example.com/v1', api_key='k', api_name='openai_chat', tools=[_wf], max_output_tokens=1000, **kw)
caps = lambda bodies: [b.get('max_output_tokens') or b.get('max_tokens') or b.get('max_completion_tokens') for b in bodies]

# cut off, then asked again at four times the cap, then whole: the call runs, on both wires and both ways of sending
for mk, stream in ((_resps, False), (_resps, True), (_chats, False), (_chats, True)):
    if mk is _resps and stream: continue           # the Responses stream is fastllm's, covered by its own event parser
    c = mk()
    r, bodies = _run(c, _CUT, _OK, None, stream=stream)
    test_eq([m['role'] for m in c.hist], ['user', 'assistant', 'user', 'assistant', 'tool', 'assistant'])
    test_eq((c.hist[2]['content'], c.hist[4]['content']), (cut_msg_, 'wrote 5'))
    test_eq(caps(bodies), [1000, 4000, 1000])        # the raise lasts one step
    assert ('Writing it.' if stream else 'cut off at its 1000-token output limit') in c.hist[1]['content'] and 'lost' not in c.hist[1]   # what streamed, else why

# cut off twice: `ToolCallError` says what happened, not a decoder message
for mk, stream in ((_resps, False), (_chats, True)):
    test_fail(lambda: _run(mk(), _CUT, _CUT, stream=stream), contains="gpt-5.4's tool call was cut off at its 4000-token output limit")

# arguments that are not JSON go back naming the problem, at the same cap
c = _chats()
r, bodies = _run(c, _BAD, _OK, None, stream=True)
assert "not valid JSON (Expecting ',' delimiter at char 17)" in c.hist[2]['content']
test_eq((c.hist[4]['content'], caps(bodies)), ('wrote 5', [1000, 1000, 1000]))

# a `JSONDecodeError` that is not the model's, such as a proxy's HTML page, is raised as it was
test_fail(lambda: _run(_chats(), json.JSONDecodeError('Expecting value', '<html>', 0)), contains='Expecting value')

# the raise stays within what fastllm says the model can write; past that, the advice is smaller steps
c = RemoteChat('gpt-5.4', max_output_tokens=100_000)
assert 'ask for smaller steps' in c._cut(100_000) and c._boost == get_model_info('gpt-5.4')['max_output_tokens']
c = RemoteChat('gpt-5.4', max_output_tokens=128_000)
assert 'raise max_output_tokens' not in c._cut(128_000) and c._boost is None
c = RemoteChat('no-such-model', base_url='https://x.example.com/v1', api_key='k', max_output_tokens=500); c._cut(500); test_eq(c._boost, 2000)

# a reply that is all thinking when the cap cuts it goes back once at the raised cap, then raises
_THINK = 'think'
_r0, _c0 = _resp, _chunks
def _resp(args):
    if args != _THINK: return _r0(args)
    return {'output': [{'type': 'reasoning', 'id': 'r1', 'summary': []}], 'status': 'incomplete', 'incomplete_details': {'reason': 'max_output_tokens'},
            'usage': {'input_tokens': 5, 'output_tokens': 1000, 'total_tokens': 1005}}
def _chunks(args):
    if args != _THINK: yield from _c0(args); return
    yield {'choices': [{'index': 0, 'delta': {'role': 'assistant', 'content': ''}}]}
    yield {'choices': [{'index': 0, 'delta': {}, 'finish_reason': 'length'}]}
for mk, stream in ((_resps, False), (_chats, True)):
    c = mk()
    r, bodies = _run(c, _THINK, None, stream=stream)
    test_eq((c.hist[-1]['content'], caps(bodies)), ('Writing it.' if stream else 'done', [1000, 4000]))
    assert 'still thinking' in c.hist[1]['content'] and 'channels' not in c.hist[1] and 'thinking less' in c.hist[2]['content']
    test_fail(lambda: _run(mk(), _THINK, _THINK, stream=stream), contains='gpt-5.4 was still thinking when its reply was cut off at its 4000-token output limit')

# the default cap: the model's own maximum, `DFLT_MAX_TOKENS` for a model fastllm does not know, and `max_output_tokens` over both
test_eq(RemoteChat('gpt-5.4').max_output_tokens, get_model_info('gpt-5.4')['max_output_tokens'])
test_eq(RemoteChat('no-such-model', base_url='https://x.example.com/v1', api_key='k').max_output_tokens, DFLT_MAX_TOKENS)
test_eq(RemoteChat('gpt-5.4', max_output_tokens=900).max_output_tokens, 900)
assert DFLT_MAX_TOKENS >= 16_000

# tags mode: a `<tool_call>` cut off at the cap keeps `unread`, so it is asked for again, not run with no arguments
r = norm_completion(Completion(model='m', finish_reason='length', message=Msg(role='assistant', content=[Text(text='<tool_call>{"name": "_wf", "arguments": {"path": "a')])))
test_eq((r['truncated'], r['tool_calls'][0].get('unread')), (True, True))

# `ask(schema=)`: once more at the raised cap, then `ToolCallError`
c = _resps()
req, bodies = _wire(_CUT, _OK); _req, fa.provider_req = fa.provider_req, req
try: test_eq(c._structured_call('go', _wf, ''), {'path': 'a.txt', 'content': 'whole'})
finally: fa.provider_req = _req
test_eq(caps(bodies), [1000, 4000])
req, bodies = _wire(_CUT, _CUT); _req, fa.provider_req = fa.provider_req, req
try: test_fail(lambda: c._structured_call('go', _wf, ''), contains='cut off at its 1000-token output limit')
finally: fa.provider_req = _req
# a Gemini model reaches `v1beta/models/<id>`, however it was named: without `models/` Gemini answers 404
import fastllm.acomplete as fa
seen, _req = [], fa.provider_req
async def _gem_req(cli, path, body, params=None, stream=False, **kw):
    seen.append(cli._url(path))
    return {'candidates': [{'content': {'role': 'model', 'parts': [{'text': 'pong'}]}, 'finishReason': 'STOP'}],
            'usageMetadata': {'promptTokenCount': 5, 'candidatesTokenCount': 1, 'totalTokenCount': 6}}
gem = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-3.5-flash:generateContent'
fa.provider_req = _gem_req
try:
    for m in ('gemini-3.5-flash', 'gemini/gemini-3.5-flash', 'models/gemini-3.5-flash', 'gemini/models/gemini-3.5-flash'):
        seen.clear(); c = RemoteChat(m, api_key='k')
        r = c('ping')
        test_eq((seen, resp_text(r), c.model_id), ([gem], 'pong', m))
        assert r['usage']['prompt_tokens'] == 5, r['usage']
    for kw in (dict(vendor_name='gemini'), dict(vendor_name='gemini', base_url='https://generativelanguage.googleapis.com/')):   # a named route: `acomplete` keeps the vendor prefix, so it goes here
        seen.clear(); RemoteChat('gemini/gemini-3.5-flash', api_key='k', **kw)('ping'); test_eq(seen, [gem])
    seen.clear(); RemoteChat('gemini-3.5-flash', api_key='k', api_name='gemini', base_url='https://gw.example.com/')('ping')
    test_eq(seen, ['https://gw.example.com/v1beta/models/gemini-3.5-flash:generateContent'])
    seen.clear(); RemoteChat('tunedModels/mine', api_key='k', vendor_name='gemini')('ping')
    test_eq(seen, ['https://generativelanguage.googleapis.com/v1beta/tunedModels/mine:generateContent'])
finally: fa.provider_req = _req
test_eq(RemoteChat('gemini-3.5-flash', base_url='https://gw.example.com/v1', api_key='k')._wire_model, 'gemini-3.5-flash')   # an OpenAI-shaped route takes the bare id
test_eq(RemoteChat('gpt-5.4')._wire_model, 'gpt-5.4')
test_eq(RemoteChat('gemini-3.5-flash')._kw(stream=True)['stream'], True)
# an effort level the provider's API lacks goes out as the nearest one it takes
test_eq(RemoteChat('gpt-5.4-mini', effort='max')._kw()['reasoning_effort'], 'xhigh')
test_eq(RemoteChat('gpt-5.4', base_url=az, api_key='k', api_name='openai_chat', effort='max')._kw()['reasoning_effort'], 'xhigh')
test_eq(RemoteChat('gpt-5.4-mini')._kw(effort='max')['reasoning_effort'], 'xhigh')    # per turn too
test_eq(RemoteChat('gpt-5.4-mini', effort='xhigh')._kw()['reasoning_effort'], 'xhigh')
test_eq(RemoteChat('anthropic/claude-sonnet-4-5', effort='max')._kw()['reasoning_effort'], 'max')
test_eq(RemoteChat('models/gemini-3.5-flash', effort='max')._kw()['reasoning_effort'], 'high')
test_eq('reasoning_effort' in RemoteChat('gpt-5.4-mini')._kw(), False)

# a 400 that names the effort: the call goes once more without it, and `dropped_effort` says why
class _E400(Exception): status_code = 400
def _fake(msgs, model, **kw):
    sent.append(kw.get('reasoning_effort'))
    async def go():
        if kw.get('reasoning_effort'): raise _E400("Unsupported value: 'reasoning_effort' does not support 'xhigh' with this model.")
        return _comp('pong')
    async def gen():
        if kw.get('reasoning_effort'): raise _E400('400 Bad Request: reasoning.effort is not supported')
        yield Text(text='po'); yield Text(text='ng'); yield _comp('pong')
    if not kw.get('stream'): return go()
    async def wrap(): return gen()
    return wrap()

_real, acomplete = acomplete, _fake
try:
    sent, c = [], RemoteChat('gpt-5.4-mini', effort='max')
    test_eq((resp_text(c('ping')), sent), ('pong', ['xhigh', None]))
    assert 'refused reasoning effort' in c.dropped_effort and 'xhigh' in c.dropped_effort, c.dropped_effort
    sent.clear(); c('again')
    test_eq(sent, [None])                         # while it is set, no effort goes out
    sent, s = [], RemoteChat('gpt-5.4-mini', effort='high')
    test_eq((''.join(s('ping', stream=True)), sent, bool(s.dropped_effort)), ('pong', ['high', None], True))
    def _other(msgs, model, **kw):
        async def go(): raise _E400('400 Bad Request: messages is empty')
        return go()
    acomplete = _other
    test_fail(lambda: RemoteChat('gpt-5.4-mini', effort='high')('ping'), contains='messages is empty')   # any other 400 is the caller's
    def _rs(msgs, model, **kw):
        async def go(): raise _E400("Item 'rs_0a1b' of type 'reasoning' was provided without its required following item.")
        return go()
    acomplete, c = _rs, RemoteChat('gpt-5.4-mini', effort='high')
    test_fail(lambda: c('ping'), contains="type 'reasoning'")     # a reasoning item, not the effort
    test_eq(c.dropped_effort, None)
    class _E500(Exception): status_code = 500
    def _down(msgs, model, **kw):
        async def go(): raise _E500('upstream said 400 times: reasoning_effort timed out')
        return go()
    acomplete, c = _down, RemoteChat('gpt-5.4-mini', effort='high')
    test_fail(lambda: c('ping'), contains='upstream')               # only a 400 status counts, not "400" in the text
    test_eq(c.dropped_effort, None)
finally: acomplete = _real

# a turn's own `tool_mode` decides whether the stream is split on tags, as it decides where the schemas go
call = 'on it\n<' + 'tool_call>{"name": "_add", "arguments": {"a": 1, "b": 2}}</' + 'tool_call>'
def _tagged(msgs, model, **kw):
    async def gen():
        yield Text(text=call); yield _comp(call)
    async def wrap(): return gen()
    return wrap()
_real, acomplete = acomplete, _tagged
try:
    out = list(RemoteChat('gpt-5.1', tools=[_add])._stream_step(tool_mode='tags'))
    assert not any('tool_call>' in str(o) for o in out if 'content' in o and o['content'][0].get('type') == 'text'), out
    out = list(RemoteChat('gpt-5.1', tools=[_add], tool_mode='tags')._stream_step(tool_mode='native'))
    test_eq(out, [{'content': [{'type': 'text', 'text': call}]}])
finally: acomplete = _real

A one-shot with think=False sends no effort. When a deployment sets NO_THINK_EFFORT, the call is sent again without it only when the provider’s 400 names it. Any other failure, such as a bad key, is raised after one request.

class _HTTPErr(Exception):
    def __init__(self, code, msg): super().__init__(msg); self.status_code = code

def _failing(code, msg, sent):
    async def collect(msgs, **kw): sent.append(kw.get('reasoning_effort')); raise _HTTPErr(code, msg)
    return collect

rc, sent = RemoteChat('gpt-4o', key='k'), []
rc._collect = _failing(401, 'bad key', sent)
test_fail(lambda: rc._oneshot('hi', think=False), contains='bad key')
test_eq(len(sent), 1)
test_eq(sent, [None])   # think=False sends no effort, so the model runs at its default
NO_THINK_EFFORT = 'minimal'   # a deployment that asks for a lowest effort: a refusal sends once more without it
rc._collect = _failing(400, 'Unsupported reasoning_effort', sent := [])
test_fail(lambda: rc._oneshot('hi', think=False), contains='reasoning_effort')
test_eq(sent, ['minimal', None])
NO_THINK_EFFORT = None

Against a real API

Chat('gpt-5.1'), Chat('anthropic/claude-sonnet-4-5') and Chat(model, runtime='remote') all use this backend. These cells call paid APIs and need a provider key. The test run skips them, and the output shown was saved earlier. The last cell starts a conversation on a local Qwen3 through llama.cpp and continues it on GPT-5.1.

chat = Chat('gpt-4.1', sp='You are concise.')
test_eq(chat.runtime, 'remote')
r = chat('Reply with exactly: pong')
assert 'pong' in resp_text(r).lower()
print(chat.use)
chat.oneshot('what do you say to ping in one word')
total=22|in=20|out=2|turns=1|model=gpt-4.1
'The phrase "**say to ping**" can be interpreted in different contexts, but commonly, when someone says they want to "ping" someone (or something), it usually refers to one of the following:\n\n### 1. **In Networking or IT:**\nTo **ping** is to send a small data packet to a server or device to check if it\'s reachable/alive (like `ping google.com` in the command line).\n- **What you say:**  \n  You typically "say" or type the command:  \n  ```\n  ping [IP address or domain]\n  ```\n  For example: `ping google.com`\n\n### 2. **In Chat/Business Communication:**\nTo "ping" someone means to send them a quick message, usually to get their attention or check in.\n- **What you say:**  \n  You might say:  \n  - "I\'ll ping you later."\n  - "Can you ping John to see if he\'s available?"\n  - "Just pinging you to follow up on this."\n\n  Or, if you’re the person "pinging," you might send a message like:\n  - "Hi, just pinging to check in."\n  - "Ping!"\n\n### 3. **If Someone Says “What do you say to ping?”**\n- They might be asking **if you\'re okay with sending a quick message** or **checking the status** of a device/person.\n- **Possible replies:**  \n  - "Sure, I can ping them."\n  - "Go ahead and ping."\n  - "I already pinged them."\n\n---\n\n## **In summary:**\n- **To ping** = to reach out or check the status (either electronically or in conversation).\n- **What you say:**  \n  In IT: Use the command (e.g., `ping example.com`).  \n  In chat: Send a quick message ("Just pinging you...").\n\n**Let me know which context you meant if you want a more specific answer!**'
display_stream(Chat('gpt-5.1')('Write two sentences about the monsoon.', stream=True))

The monsoon is a seasonal wind system that brings heavy rainfall to regions such as South Asia, Southeast Asia, and parts of Africa. It is crucial for agriculture and water resources but can also cause severe flooding and landslides.

'The monsoon is a seasonal wind system that brings heavy rainfall to regions such as South Asia, Southeast Asia, and parts of Africa. It is crucial for agriculture and water resources but can also cause severe flooding and landslides.'
th = Chat('gpt-5.1', reasoning_effort='high', max_output_tokens=2048)
r = th('A bat and ball cost $1.10, the bat is $1 more than the ball. How much is the ball?')
print(thought(r)[:400]); print('---'); print(resp_text(r))

---
Let the price of the ball be \(x\) dollars.  
Then the bat costs \(x + 1\) dollars.

Total cost:
\[
x + (x + 1) = 1.10
\]
\[
2x + 1 = 1.10
\]
\[
2x = 0.10
\]
\[
x = 0.05
\]

The ball costs **5 cents**.
img = Path('images.jpeg').read_bytes()
print(resp_text(Chat('gpt-5.1')([img, 'What is in this image? One sentence.'])))
A German Shepherd dog is standing on an outdoor path with its tongue out.
# the whole point: start local, finish hosted, with one history
from rishi.llama import LlamaChat, qwen3_17b

local = LlamaChat(qwen3_17b, n_ctx=4096)
local('My name is Karthik and my favourite number is 17. Remember both.')
hist = local.hist
local.close()

remote = Chat('gpt-5.1', messages=hist)
r = remote('What is my name and my favourite number?')
assert 'karthik' in resp_text(r).lower() and '17' in resp_text(r)
resp_text(r)
/Users/71293/code/personal/orgs/ramabana/.venv/lib/python3.13/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html
  from .autonotebook import tqdm as notebook_tqdm
llama_context: n_ctx_seq (4096) < n_ctx_train (40960) -- the full capacity of the model will not be utilized
'Your name is Karthik, and your favourite number is 17.'
empty_parts = _parts([{'type': 'text', 'text': ''}])
test_eq(empty_parts, [])

mixed_parts = _parts([{'type': 'text', 'text': ''}, {'type': 'text', 'text': 'keep'}])
test_eq([p.text for p in mixed_parts], ['keep'])
test_eq(to_msg({'role': 'user', 'content': [{'type': 'text', 'text': ''}]}).content, [])