スクリプト化、再生、ローカル、ホスト型のモデルに共通する一つのインターフェース
読了まで約39 分分、5 節 節の 4 例 例。
この章を読み終えると、スクリプト化したモデル、再生した実行、ローカルモデル、OpenAI 互換のエンドポイントのどれに対しても、ループを変更せずに同じループを実行できるようになる。また、各アダプタが応答から何を保持し、応答のテキストから何を読み取るのかを説明できるようになる。
第1章では、unitcraft の保守エージェントをスクリプト化したモデルで実行し、続いて保存済みの実行で実行した。ループはどちらも変更なしで受け付けた。次の問いは、それを成り立たせるためにモデルが何を返さなければならないか、である。T-01 は、format_quantity が末尾のゼロを落とすという問題である。そのため、3.5 kg は 3.5 kg と出力され、既定の小数点以下2桁であれば 3.50 kg となる。T-01 では、どのステップでも同じ三つの情報が返ってくる必要がある。モデルのテキスト、そのテキストからハーネスが読み取れるツール呼び出し、そしてリクエストと応答が使ったトークン数である。スクリプト化した文字列のリストは、この三つをすべて供給できる。ディスク上のファイル、メモリに読み込んだモデル、HTTP エンドポイントでも同様である。アダプタとは、これらの供給元をループから見て同じに見せるコードである。この章の残りでは、ループが出会う順に四つのアダプタを取り上げる。
この部分はまだ翻訳されていないため、英語で表示している。
Ask every model the same question
The loop needs one thing from a model: given the messages so far and the tool schemas from the schema chapter, return what the model said. A Python Protocol names that contract. Every adapter in this book has the same method, and every adapter returns the same kind of value.
class Model(Protocol):
def reply(self, messages: list[dict], tools: list[dict]) -> Reply: ...
The Reply is a small dataclass. It holds the model's raw text, the tool calls the adapter read from that text, any malformed blocks it could not read, the prompt and completion token counts, and the finish reason, which says whether the model stopped on its own or ran out of tokens. A token here is the unit that chapter 1 counts, from the pinned model's own tokenizer, so the counts belong to that model and mean nothing for another. The adapter never edits text. The loop acts on the calls, but the transcript keeps the text as the model wrote it, so a reader can see what the model actually said.
Keeping both the text and the calls matters because parsing can fail. A reply may hold a <tool_call> block whose JSON does not parse, or a block that is never closed. The adapter cannot quietly turn such a reply into a call, and it cannot throw the reply away, because the loop has to tell the model what went wrong. So the parse leaves the text as it is, records a short reason for each bad block beside it, and lets the loop decide what the model sees next. The local model section shows the parser at work.
A Protocol looks like an interface, but Python checks it by shape. Python's typing documentation says that a runtime_checkable protocol "will check only the presence of the required methods or attributes, not their type signatures or types." So isinstance can confirm that an object has a reply method, and nothing more: a class whose method is written reply(self, prompt) passes, and a class with no reply fails. The book's own Model is not decorated with runtime_checkable, and the same documentation says isinstance on such a protocol raises a TypeError. No example in this book calls isinstance on Model, so both claims are the documentation's and not run here.
Working rule: Test each adapter by calling reply() with the messages and tool schemas the loop sends, and check the fields of the Reply that come back. Use isinstance only to see that a method exists, never to show that its signature is right.
この部分はまだ翻訳されていないため、英語で表示している。
Script the replies, or replay a stored run
Two adapters need no model at all. Chapter 1's scripted run used a scripted model, and its replayed run used a stored one. Both work for the same reason: the loop is the thing under test, and a fixed list of replies keeps the model out of it. This section says what the adapters add to that.
ScriptedModel takes strings or Reply objects. A string is parsed into a Reply for you, and its tool calls are read from the <tool_call> blocks in the text. A Reply object is passed through unchanged. That second form lets a test set the token counts or a malformed entry directly, instead of writing JSON that must fail in exactly the right way. If the loop asks for more replies than the script holds, the model raises an IndexError, so a short script fails loudly rather than returning nothing. The script also keeps a test readable. The reply that causes a behaviour sits in the test beside the assertion about it, and the reader does not have to open a recording to find it.
ReplayModel reads one run's rows from the recording's replies.jsonl, in step order. Each row holds the request's hash as it was sent, the reply's text and the token counts. When the loop asks for a step, ReplayModel hashes the request it was given, the sha256 of its messages and tool schemas in canonical JSON, and compares that hash with the row's. A difference raises ReplayMismatch, which names the step. The counts come from the stored row, so a replay never tokenizes again.
The rows come from a logger, not from a script. LoggedModel wraps a live model and appends each reply to a JSON-lines file before the loop sees it. A run that stops partway leaves its rows on disk, and the recording script removes them before it resumes.
Chapter 1's T-01 run goes through the loop twice in the first example: once on a ScriptedModel that holds the stored reply texts, and once on the ReplayModel for the same run. The scripted replies are read from the stored file, so both runs start from the same source.
1"""Chapter-1-t01 runs through the loop twice: once with a ScriptedModel holding the stored reply texts, once with a2ReplayModel. The assert compares the two runs' step lines, and the lines printed below are the replayed run's."""3import json45from lib.case import load_tasks6from lib.loop import run_task7from lib.models import RECORDED, ReplayModel, ScriptedModel8from lib.tools import CH19from lib.trace import IdCounter1011task = load_tasks(only=["T-01"])[0]12rows = [json.loads(line) for line in (RECORDED / "chapter-1-t01" / "replies.jsonl").read_text(encoding="utf-8").splitlines()]131415def run_once(model):16 run = run_task(model, task, CH1, max_steps=CH1.step_cap, ids=IdCounter()) # counter-based IDs, never random (P-3)17 try:18 return list(run.trace.lines()), run.steps, run.ended19 finally:20 run.close()212223scripted = run_once(ScriptedModel([row["text"] for row in rows]))24replayed = run_once(ReplayModel("chapter-1-t01", "T-01"))25assert scripted == replayed, "the two adapters gave the loop different steps"26lines, steps, ended = replayed27for line in lines:28 print(line)29print(f"steps: {steps}")30print(f"ended: {ended}")
python same-loop-two-models.pystep 1: read_file: 23 lines
step 2: run_tests: 8 failed, 22 passed
step 3: malformed: error: malformed call
step 4: malformed: error: malformed call
step 5: malformed: error: malformed call
step 6: malformed: error: malformed call
step 7: malformed: error: malformed call
step 8: malformed: error: malformed call
steps: 8
ended: step_cap
The loop made the same calls both times, and the example stops if the two runs differ in any step line. The run is the one that hit the step cap in chapter 1: it ended as step_cap after 8 steps. The loop cannot tell the two adapters apart, so whatever the loop does with a reply, it does the same for either source.
The second example checks the recording itself, against its manifest, and then replays it.
1"""The stored chapter-1 run is the recording its manifest describes, and replaying it hands the loop each stored reply text2exactly. The prompt and the check hash to the manifest's values, the first request hashes to the reply row stored with it,3and the stored replies add up to the manifest's counts. The run is then replayed through the loop, which refuses any request4that differs from its recorded hash, and each replayed text is compared with its stored text. No model file is loaded."""5from contextlib import closing67from lib.case import load_tasks8from lib.loop import run_task9from lib.models import RECORDED_SAMPLING, ReplayModel, TextCapture, first_step, load_recording, request_hash, same_texts, stored_totals10from lib.prompts import prompt_sha25611from lib.tasks import check_sha25612from lib.tools import CH113from lib.trace import IdCounter1415task = load_tasks(only=["T-01"])[0]16manifest, rows = load_recording("chapter-1-t01")17messages, tools = first_step(task, CH1)18assert manifest["prompt_sha256"] == prompt_sha256(CH1.system, CH1.descriptions()), "the prompt changed since recording"19assert manifest["check_sha256"] == check_sha256(task), "the check changed since recording"20assert rows[0]["request_sha256"] == request_hash(messages, tools), "the first request differs from the stored reply row"21assert len(rows) == manifest["steps"], "the stored replies and the manifest disagree on the step count"22prompt_tokens, completion_tokens = stored_totals(manifest, rows)23assert manifest["sampling"] == RECORDED_SAMPLING, "the recording's sampling differs from the settings the adapters send"2425capture = TextCapture(ReplayModel("chapter-1-t01", "T-01"))26with closing(run_task(capture, task, CH1, max_steps=CH1.step_cap, ids=IdCounter())) as run:27 steps, ended = run.steps, run.ended28compared = same_texts(rows, capture.texts)29assert steps == manifest["steps"] and ended == manifest["ended"], "the replay did not end as the manifest records"30print(f"stored replies: {len(rows)}")31print(f"prompt tokens: {prompt_tokens}")32print(f"completion tokens: {completion_tokens}")33for key in ("temperature", "top_k", "seed"):34 print(f"{key}: {manifest['sampling'][key]}")35print(f"reply texts compared exactly: {compared}")36print(f"steps: {steps}")37print(f"ended: {ended}")
python replay-byte-for-byte.pystored replies: 8
prompt tokens: 13009
completion tokens: 2128
temperature: 0
top_k: 1
seed: 4217
reply texts compared exactly: 8
steps: 8
ended: step_cap
Here the manifest is the reference, and the example makes four checks. The prompt's hash and the check's hash are compared with the manifest's values, where the check is the hidden test, H-01, that chapter 1 grades T-01 with. The first request's hash is compared with the one stored in its reply row in replies.jsonl, because the manifest holds no request hash. The stored replies must match the manifest's step count and token totals, and the sampling settings are printed from the manifest and compared with RECORDED_SAMPLING in the library, the values loopback_model sends. The stored run has 8 replies, 13009 prompt tokens and 2128 completion tokens. The example prints its sampling settings on their own lines, so a reader sees the temperature, the top k and the seed the recording used.
Then the run goes through the loop. ReplayModel refuses any step whose request hash differs from its row, and the example compares each replayed text with its stored text, exactly. It prints the count it compared, 8, and the run ends as the manifest says. The manifest holds no hash for each reply, so the stored texts are not checked against an independent value. The check shows that replay hands the loop each stored text unchanged. The prompt hash covers the system message and the tool descriptions together, so a changed tool description changes the recording's identity as surely as a changed line of code does.
Working rule: Replay a recorded run only with the prompt and the check it was recorded with. When either changes, its hash in the manifest no longer matches, the example fails, and the run has to be recorded again. Changing a stored reply to make the example pass hides the change that caused the failure.
ローカルモデルと、その設定が固定されている理由
LlamaModel はローカルモデルを実行する。llama-cpp-python を通じて GGUF ファイル、すなわち llama.cpp が読み込む単一ファイル形式のファイルを読み込む。アダプタはモデルを構築するときにだけライブラリをインポートするので、各例がライブラリを読み込むことはない。どの例も GGUF ファイルを読み込まず、本書には LlamaModel のテストもない。記録はこれを使って行われ、各例はその記録が保存した応答を読む。reply() は、メッセージとツールを渡して create_chat_completion を呼び出し、返ってきた結果からテキストと使用量を読み取る。
ライブラリのデフォルト値は本書の設定とは異なる。固定したリリースでは、llama-cpp-python の create_chat_completion は temperature が 0.2、top k が 40 である。これらをそのままにしたアダプタは、本書のアダプタとは異なるサンプリングを行う。LlamaModel は、呼び出しのたびに temperature=0 と top_k=1 を渡す。そのため、サンプリングはライブラリから受け継ぐのではなく、コードに明記される。
返ってくるのはテキストである。記録に使ったサーバは、同じモデルファイルに対し、固定した版の llama-cpp-python を python -m llama_cpp.server として実行し、最初のステップのツール呼び出しをメッセージ本文の中に入れて返した。エンドポイントの記録に保存された本体には、その本文があり、tool_calls フィールドはまったくない。
<tool_call>
{"name": "read_file", "arguments": {"path": "unitcraft/format.py"}}
</tool_call>
このように、ライブラリの応答は呼び出しをテキストとして運ぶ。LlamaModel はそこから構造化されたフィールドを読むのではなく、テキストを構文解析する。
構文解析は parse_tool_calls という一つの関数で行う。この関数は <tool_call> ブロックをそれぞれ見つけ、name と arguments のオブジェクトを持つ JSON として読み、呼び出しを保持する。構文解析できないブロックは、短い理由を付けた不正な項目になる。ループはこの項目をツールエラーとしてモデルに示すので、不正な呼び出しは破棄されず、ステップとして記録される。第1章の T-01 の実行が、何がうまくいかないかでこれを示している。最初の二つのステップの後は、すべてのステップが error: malformed call になっている。
終了理由はループにとって重要である。stop はモデルが回答を終えたことを意味し、length は応答がアダプタの設定したトークン上限に達したことを意味する。length の応答は <tool_call> ブロックの途中で止まることがある。そのためパーサは、閉じられていないブロックを完全なものとして読まず、不正なものとして報告する。
カウントはライブラリ自身のものである。LlamaModel は、llama-cpp-python が報告するプロンプトと補完のトークン数を Reply にコピーし、記録はそれらを保存する。これらは固定したファイルのトークナイザに基づく数なので、ファイルが違えば同じメッセージでも数は異なる。あるモデルの数を別のモデルの数と比較することはできない。
コンストラクタが受け取るのは、ファイルのパス、コンテキストサイズ、スレッド数、シード、トークン上限だけであり、モデルに関するそれ以外のものは受け取らない。記録は recordings/local_model.py から値を読む。したがって、別のファイルを読み込みたい読者は、パスとこれらの設定をあわせて変更し、記録をやり直す。サンプリングは選択の問題であり、モデルカードは別の設定を推奨している。Qwen のモデルカードには「Temperature=0.7、TopP=0.8、TopK=20、MinP=0 の使用を勧める」とある。これらの設定は、実行ごとに変化する回答に向いている。本書は実行を一度記録し、後の実行を保存した応答と照合するので、マニフェストに記録されているとおり、temperature 0、top k 1、固定シード 4217 を使う。これらの設定により、再記録が一致する可能性は最も高くなるが、temperature 0 でも出力が繰り返される保証はない。そのため、本書は各例が示す以上のことは主張しない。エンドポイントの例は、一つの記録における二つのリクエストが同じテキストを返したことを確認する。リプレイは保存されたテキストを読むので、サンプリングにはまったく依存しない。
実践ルール: マニフェストが指定するサンプリングで記録し、モデルファイルのハッシュもマニフェストに並べて残す。設定を変更すると応答も変わるので、古い記録と比較せず、記録をやり直す。
ホスト型風のエンドポイントをループバックで試験する
OpenAI のチャット補完のリクエスト形式を受け付けるサーバーには、ベース URL と、ホストが要求する場合は鍵を与えれば、一つのアダプタで接続できる。OpenAICompatibleModel は、メッセージ、ツールのスキーマ、サンプリング設定を /chat/completions へ送信する。このアダプタは標準ライブラリの urllib を使い、SDK は使わない。SDK がなければ、リクエストを隠すものは何もない。request_body() はアダプタが直列化して送信する本体を返すので、テストでその本体を記録された内容と比較できる。top_k フィールドは、アダプタにその値が与えられた場合にのみ送信される。アダプタは、構築時、つまりリクエストを送る前に、次の二つを拒否する。http でも https でもない URL と、ループバック以外のホストに対して平文の http で鍵を送る設定である。また、リダイレクトには決して従わない。リダイレクトはエラーを発生させるので、鍵が二つ目の URL へ送られることはない。
レスポンスでは、ツール呼び出しは二つの場所のどちらかにある。OpenAI のリファレンスは、ツール呼び出しの function.arguments を、モデルが JSON として生成する文字列であると説明し、呼び出し側に「関数を呼び出す前に、コード内で引数を検証すること」を求めている。アダプタは、応答が構造化された tool_calls フィールドを持つ場合に、その文字列を解析する。このフィールドがない場合は、ローカルモデルと同様に <tool_call> テキストにフォールバックする。parse_chat_body は message.content をサーバーが送ったままに保ち、content がなければ空のテキストとして読み、使用量の数を Reply にコピーする。そのため、保存された本体は毎回同じ Reply に解析される。どちらの場合も、引数は辞書としてループに渡され、その辞書はまだ検証されていない。その検証は、スキーマの章のツールの引数モデルが行う。
この本のどの例も、構造化された tool_calls フィールドを返すリクエストを送らない。したがって、最初の分岐はコードとして存在するが、どの例からも実行されない。他のプロバイダがこのフィールドに何を返すかは、この本では示さない。この章でも、OpenAI のリファレンスが述べる以上のことは述べない。
記録には、ローカルモデルと同じファイルと同じサンプリングを使った。固定したバージョンの llama-cpp-python 自身のサーバーをループバックで動かし、T-01 の最初のステップをアダプタ経由で二回送信した。保存されたファイルには、送信されたとおりの各リクエストと、各生のレスポンス本体が入っている。ループバックの http.server がそれらの本体を順に返し、本体が記録と異なるリクエストには 409 で応答する。このスタブが比較するのは、リクエスト本体、すべてのメッセージ、すべての設定である。パス、メソッド、ヘッダーは比較しないので、エンドポイントのパスや Authorization ヘッダーを変更しても通ってしまう。アダプタの変更によって送信する本体が変わると、応答が読まれる前にリクエストが失敗する。保存された本体には、サーバー自身の id フィールドと created フィールドが残っている。これらを比較したり出力したりするものはない。モデルを読み込まないので、この本の例を検査するたびに、アダプタの HTTP コードと解析コードが実行される。
1"""The OpenAI-compatible adapter, run live against a loopback stub that serves the bodies recorded from llama.cpp's own2server. The line that matters is "raw text": the server put the call in the message content as text, with no tool_calls3field, so the adapter parses the text, and the tool's own model accepts the arguments. Needs4recordings/openai_compatible.py to have been run; until then this raises."""5import json67from lib.case import load_tasks8from lib.models import first_step, loopback_model, serve_recorded9from lib.tools import CH11011task = load_tasks(only=["T-01"])[0]12messages, tools = first_step(task, CH1)13bodies: list[str] = []14with serve_recorded("openai-compatible") as base_url:15 model = loopback_model(base_url, on_body=bodies.append)16 first = model.reply(messages, tools)17 second = model.reply(messages, tools)18assert first.text.lstrip().startswith("<tool_call>"), "the server should return the call as text"19assert "tool_calls" not in json.loads(bodies[0])["choices"][0]["message"], "the recorded body has a structured tool_calls field"20assert len(first.tool_calls) == 1 and first.tool_calls[0]["name"] == "read_file", "the first step is one read_file call"21assert not first.malformed, "the call should parse"22CH1.get("read_file").args.model_validate(first.tool_calls[0]["arguments"]) # raises if the arguments do not fit the tool23assert first.text == second.text, "the two recorded responses differ"24print(f"requests: {len(bodies)}")25print("raw text:", json.dumps(first.text))26print("structured tool_calls field: absent")27print(f"tool calls: {len(first.tool_calls)}")28print("call:", first.tool_calls[0]["name"], json.dumps(first.tool_calls[0]["arguments"], sort_keys=True))29print(f"malformed: {len(first.malformed)}")30print(f"prompt tokens: {first.prompt_tokens}")31print(f"completion tokens: {first.completion_tokens}")32print(f"finish reason: {first.finish_reason}")
python openai-compatible-loopback.pyrequests: 2
raw text: "<tool_call>\n{\"name\": \"read_file\", \"arguments\": {\"path\": \"unitcraft/format.py\"}}\n</tool_call>"
structured tool_calls field: absent
tool calls: 1
call: read_file {"path": "unitcraft/format.py"}
malformed: 0
prompt tokens: 501
completion tokens: 22
finish reason: stop
アダプタは read_file の呼び出しを一つ、テキストとして受け取る。その引数をツールのモデルと照合するのは呼び出し側の役目であり、この検証こそがこの節の要点なので、例ではそれを明示している。応答にはツール呼び出しが 1 個、不正な形式のブロックが 0 個含まれ、リクエストでは 501 個のプロンプトトークンが使われた。応答は stop で終わる。これは、モデルがトークンを使い果たしたのではなく、自ら回答を終えたことを意味する。
記録と例のためにアダプタを構築するヘルパー loopback_model は、サーバーの起動時に使ったモデルのエイリアス、各応答につき 1024 トークンの上限、温度 0、top_k 1 を固定する。別の設定を使いたい呼び出し側は OpenAICompatibleModel を直接構築する。その場合は送信されるリクエスト本体が変わり、スタブはそれを拒否する。
プロキシは、通常の urllib リクエストと同じように働く。ただし、ループバックのホストである 127.0.0.1、::1、localhost には直接接続する。リモートの http URL は、環境が指定するプロキシを経由する。拒否の例では、スタブがプロキシの代わりを務め、両方の面を示す。ループバックへのリクエストはプロキシに届かず、リモートへのリクエストは完全な URL を伴って届く。
1"""The OpenAI-compatible adapter refuses a redirect, a key over plain http to a remote host, and a non-http scheme. It sends2a remote URL through the environment's proxy and a loopback URL around it. Every request goes to a stub on 127.0.0.1, which3stands in for both the endpoint and the proxy, so no network is used. Each refusal prints one labelled line."""4from lib.models import OpenAICompatibleModel, proxy_env, refusal, stub_endpoint56REMOTE = "http://remote-host.invalid/v1"7MESSAGES = [{"role": "user", "content": "ping"}]89with stub_endpoint(200) as proxy, stub_endpoint(302) as target, proxy_env(proxy):10 loopback = f"{target.url}/v1"11 model = OpenAICompatibleModel(loopback, "model", max_tokens=8, api_key="DUMMY-KEY")12 reason = refusal(lambda: model.reply(MESSAGES, []))13 assert target.seen == ["/v1/chat/completions"], "a redirect was followed"14 print("redirect 302 on loopback:", reason)15 target.code = 30716 reason = refusal(lambda: model.reply(MESSAGES, []))17 print("redirect 307 on loopback:", reason)18 assert target.seen == ["/v1/chat/completions"] * 2, "a redirect was followed"19 print(f"requests to the redirect target: {target.seen.count('/collect')}")20 print(f"loopback requests through the proxy: {len(proxy.seen)}")2122 remote = OpenAICompatibleModel(REMOTE, "model", max_tokens=8)23 reply = remote.reply(MESSAGES, [])24 assert reply.text == "ok" and proxy.seen == ["http://remote-host.invalid/v1/chat/completions"]25 print("remote request through the proxy:", proxy.seen[0])26 print("remote reply text:", reply.text)2728 reason = refusal(lambda: OpenAICompatibleModel(REMOTE, "model", max_tokens=8, api_key="DUMMY-KEY"))29 print("key over plain http to a remote host:", reason)30 assert len(proxy.seen) == 1, "a request was made for the refused key"31 OpenAICompatibleModel("https://remote-host.invalid/v1", "model", max_tokens=8, api_key="DUMMY-KEY")32 print("key over https to a remote host: accepted, no request made")33 OpenAICompatibleModel(loopback, "model", max_tokens=8, api_key="DUMMY-KEY")34 print("key over http to loopback: accepted")35 reason = refusal(lambda: OpenAICompatibleModel("file:///v1", "model", max_tokens=8))36 print("file URL:", reason)
python adapter-refuses-unsafe-endpoints.pyredirect 302 on loopback: the endpoint answered 302 with a redirect, and the adapter does not follow redirects
redirect 307 on loopback: the endpoint answered 307 with a redirect, and the adapter does not follow redirects
requests to the redirect target: 0
loopback requests through the proxy: 0
remote request through the proxy: http://remote-host.invalid/v1/chat/completions
remote reply text: ok
key over plain http to a remote host: the adapter sends an API key over https, or over http to a loopback host only
key over https to a remote host: accepted, no request made
key over http to loopback: accepted
file URL: the scheme 'file' is not http or https
この例は、リダイレクト、リモートホストへの平文の http による鍵の送信、ファイルアドレスという各拒否も示す。リダイレクト先にはリクエストが届かず、残りの二つは接続が行われる前に拒否される。拒否のたびに、その原因となった規則が出力される。
この章は、ホスト型のプロバイダを呼び出さない。アダプタをそうしたプロバイダに向ける場合は、鍵にどのみち必要な https を使い、自分のアカウントと鍵を用意すること。この本はどちらも提供せず、この本の例がモデルやリモートホストを呼び出すこともない。
実践ルール: function.arguments を JSON として解析し、結果をツールの引数モデルと照合し、失敗はツールの結果としてモデルに返す。厳密なスキーマを強制するエンドポイントでは、こうした失敗は起こりにくくなるが、検証は引き続き実行する。
一つのループ、複数のモデル
ループはアダプタが変わっても変化しない。ループは reply() を呼び出し、Reply から呼び出しを読み取り、最初の呼び出しを実行して、その結果を次のステップに書き込む。アダプタ間で異なるのは、応答の取得元と、応答のテキストの扱い方である。ループが目にするのは、各アダプタが返す Reply だけである。
| アダプタ | 応答の取得元 | 呼び出しの読み取り元 | 示す例 |
|---|---|---|---|
ScriptedModel |
コード中に書かれた文字列 | テキスト | same-loop-two-models |
ReplayModel |
一回の実行で保存された応答 | テキスト | same-loop-two-models、replay-byte-for-byte |
LlamaModel |
llama-cpp-python 経由のローカルの GGUF ファイル | テキスト | なし。ローカルモデルを参照 |
OpenAICompatibleModel |
HTTP エンドポイント(本書ではループバック上) | 構造化フィールドがあればそれ、なければテキスト | openai-compatible-loopback、adapter-refuses-unsafe-endpoints |
各行はアダプタの動作を示し、最後の列はそれを実行する例の名前を挙げている。二つの例は ScriptedModel と ReplayModel をループ経由で動かし、別の二つの例は OpenAICompatibleModel の reply() を直接呼び出す。
本番環境でアダプタが壊れる箇所は三つある。読者は、いま見ているのがどれであるかを把握しておく必要がある。一つ目はトランスポートである。urllib はエラーステータスで例外を送出し、アダプタはそれを捕捉しない。アダプタは意図的にリダイレクトを拒否するので、リダイレクトでも例外が送出される。いずれの場合も、そのステップには Reply が存在せず、実行はエラーとともに停止する。二つ目は応答の形である。応答は構文解析に成功しても、ループが持たないツールを指していることがある。その場合は、第3章の名前の検査がツールエラーとして拒否する。三つ目は保存された実行である。プロンプトが変わると、replay-byte-for-byte はどのステップも実行される前の最初のアサーションで失敗する。ループの後のバージョンが、あるステップで異なる問いを発した場合、ReplayModel はそのステップで ReplayMismatch を送出し、メッセージにはそのステップが示される。稼働中のモデルが返す不正な形式のツール呼び出しは、これらとはまた別の扱いになる。それは想定される事象であり、ループはそれを数えてモデルに示す。
ループを安定させているのは、一つのパーサーと一つの Reply である。ライブか保存かを問わず、すべてのアダプタはループに同じフィールドを渡す。テキストはモデルが書いたままに保たれ、各応答とともに保存されるリクエストハッシュによって、問いが変わると、変わったステップで失敗する。ネットワークに触れるのはエンドポイントアダプタだけである。実在のホストを指す前に再確認すべきなのは、このアダプタの規則である。リダイレクトを行わないこと、平文の http でキーを送らないこと、プロキシはリモート URL に限ることである。
五つ目のアダプタを追加するには三つの手順を踏む。まず、ループのメッセージとツールを受け取る reply() メソッドを持つクラスを書く。次に、他のアダプタと同じパーサーを使って Reply を構築する。テキストには make_reply、レスポンスボディには parse_chat_body を用いる。これにより、すべてのアダプタが同じ方法でツール呼び出しを読み取る。最後に、プロトコルの節に記されたテストを与える。ループは変わらず、他のどのアダプタも変わらない。
実践ルール: アダプタは生のテキストと件数を保持し、ツール呼び出しを一箇所で読み取り、Reply を返す。SDK のオブジェクトをループに渡してはならない。各アダプタには、ループの引数で reply() を呼び出すテストを用意し、プロンプトやリクエストが変わった場合は、記録し直す理由として扱う。
この版における本章
第2026.11.2版2026年11月20日時点で例が通過この章の4 例件のうち4件が合格
英語版の書籍(版2026.11.2)から翻訳した。