One interface for scripted, replayed, local and hosted models

읽는 데 약 33분분 걸린다, 5절에 4개 예제이(가) 있음.

2026.11.2판 예제 통과 2026년 11월 20 64개 예제 중 64개 통과 변경 사항

AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식

영어판 2026.11.2판을 번역한 것이다. 원문 읽기

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

By the end of this chapter you can run the same loop on a scripted model, a replayed run, a local model and an OpenAI-compatible endpoint, without changing the loop. You can also say what each adapter keeps from a reply, and what it reads out of the reply's text.

Chapter 1 ran the maintenance agent for unitcraft on a scripted model, then on a stored run, and the loop took both without a change. The next question is what a model has to hand over for that to work. For T-01, the issue that format_quantity drops trailing zeros, so 3.5 kg prints as 3.5 kg where the default of two places gives 3.50 kg, every step needs the same three things back: the model's text, the tool calls the harness can read from that text, and the counts of tokens the request and the reply used. A scripted list of strings can supply all three. So can a file on disk, a model loaded in memory, or an HTTP endpoint. The adapter is the code that makes each of those sources look the same to the loop, and the rest of this chapter takes the four adapters in the order the loop meets them.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

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.

same-loop-two-models.py Python 3.12.15 · pydantic 2.14.3 통과
"""Chapter-1-t01 runs through the loop twice: once with a ScriptedModel holding the stored reply texts, once with aReplayModel. The assert compares the two runs' step lines, and the lines printed below are the replayed run's."""import jsonfrom lib.case import load_tasksfrom lib.loop import run_taskfrom lib.models import RECORDED, ReplayModel, ScriptedModelfrom lib.tools import CH1from lib.trace import IdCountertask = load_tasks(only=["T-01"])[0]rows = [json.loads(line) for line in (RECORDED / "chapter-1-t01" / "replies.jsonl").read_text(encoding="utf-8").splitlines()]def run_once(model):    run = run_task(model, task, CH1, max_steps=CH1.step_cap, ids=IdCounter())  # counter-based IDs, never random (P-3)    try:        return list(run.trace.lines()), run.steps, run.ended    finally:        run.close()scripted = run_once(ScriptedModel([row["text"] for row in rows]))replayed = run_once(ReplayModel("chapter-1-t01", "T-01"))assert scripted == replayed, "the two adapters gave the loop different steps"lines, steps, ended = replayedfor line in lines:    print(line)print(f"steps: {steps}")print(f"ended: {ended}")
출력python same-loop-two-models.py
step 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.

replay-byte-for-byte.py Python 3.12.15 · pydantic 2.14.3 통과
"""The stored chapter-1 run is the recording its manifest describes, and replaying it hands the loop each stored reply textexactly. The prompt and the check hash to the manifest's values, the first request hashes to the reply row stored with it,and the stored replies add up to the manifest's counts. The run is then replayed through the loop, which refuses any requestthat differs from its recorded hash, and each replayed text is compared with its stored text. No model file is loaded."""from contextlib import closingfrom lib.case import load_tasksfrom lib.loop import run_taskfrom lib.models import RECORDED_SAMPLING, ReplayModel, TextCapture, first_step, load_recording, request_hash, same_texts, stored_totalsfrom lib.prompts import prompt_sha256from lib.tasks import check_sha256from lib.tools import CH1from lib.trace import IdCountertask = load_tasks(only=["T-01"])[0]manifest, rows = load_recording("chapter-1-t01")messages, tools = first_step(task, CH1)assert manifest["prompt_sha256"] == prompt_sha256(CH1.system, CH1.descriptions()), "the prompt changed since recording"assert manifest["check_sha256"] == check_sha256(task), "the check changed since recording"assert rows[0]["request_sha256"] == request_hash(messages, tools), "the first request differs from the stored reply row"assert len(rows) == manifest["steps"], "the stored replies and the manifest disagree on the step count"prompt_tokens, completion_tokens = stored_totals(manifest, rows)assert manifest["sampling"] == RECORDED_SAMPLING, "the recording's sampling differs from the settings the adapters send"capture = TextCapture(ReplayModel("chapter-1-t01", "T-01"))with closing(run_task(capture, task, CH1, max_steps=CH1.step_cap, ids=IdCounter())) as run:    steps, ended = run.steps, run.endedcompared = same_texts(rows, capture.texts)assert steps == manifest["steps"] and ended == manifest["ended"], "the replay did not end as the manifest records"print(f"stored replies: {len(rows)}")print(f"prompt tokens: {prompt_tokens}")print(f"completion tokens: {completion_tokens}")for key in ("temperature", "top_k", "seed"):    print(f"{key}: {manifest['sampling'][key]}")print(f"reply texts compared exactly: {compared}")print(f"steps: {steps}")print(f"ended: {ended}")
출력python replay-byte-for-byte.py
stored 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 파일을 불러오는데, 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의 chat-completions 요청 형식을 받는 서버라면 어댑터 하나로 접근할 수 있다. 이때 기본 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 코드와 파싱 코드가 실행된다.

openai-compatible-loopback.py Python 3.12.15 · pydantic 2.14.3 통과
"""The OpenAI-compatible adapter, run live against a loopback stub that serves the bodies recorded from llama.cpp's ownserver. The line that matters is "raw text": the server put the call in the message content as text, with no tool_callsfield, so the adapter parses the text, and the tool's own model accepts the arguments. Needsrecordings/openai_compatible.py to have been run; until then this raises."""import jsonfrom lib.case import load_tasksfrom lib.models import first_step, loopback_model, serve_recordedfrom lib.tools import CH1task = load_tasks(only=["T-01"])[0]messages, tools = first_step(task, CH1)bodies: list[str] = []with serve_recorded("openai-compatible") as base_url:    model = loopback_model(base_url, on_body=bodies.append)    first = model.reply(messages, tools)    second = model.reply(messages, tools)assert first.text.lstrip().startswith("<tool_call>"), "the server should return the call as text"assert "tool_calls" not in json.loads(bodies[0])["choices"][0]["message"], "the recorded body has a structured tool_calls field"assert len(first.tool_calls) == 1 and first.tool_calls[0]["name"] == "read_file", "the first step is one read_file call"assert not first.malformed, "the call should parse"CH1.get("read_file").args.model_validate(first.tool_calls[0]["arguments"])  # raises if the arguments do not fit the toolassert first.text == second.text, "the two recorded responses differ"print(f"requests: {len(bodies)}")print("raw text:", json.dumps(first.text))print("structured tool_calls field: absent")print(f"tool calls: {len(first.tool_calls)}")print("call:", first.tool_calls[0]["name"], json.dumps(first.tool_calls[0]["arguments"], sort_keys=True))print(f"malformed: {len(first.malformed)}")print(f"prompt tokens: {first.prompt_tokens}")print(f"completion tokens: {first.completion_tokens}")print(f"finish reason: {first.finish_reason}")
출력python openai-compatible-loopback.py
requests: 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과 함께 도착한다.

adapter-refuses-unsafe-endpoints.py Python 3.12.15 통과
"""The OpenAI-compatible adapter refuses a redirect, a key over plain http to a remote host, and a non-http scheme. It sendsa remote URL through the environment's proxy and a loopback URL around it. Every request goes to a stub on 127.0.0.1, whichstands in for both the endpoint and the proxy, so no network is used. Each refusal prints one labelled line."""from lib.models import OpenAICompatibleModel, proxy_env, refusal, stub_endpointREMOTE = "http://remote-host.invalid/v1"MESSAGES = [{"role": "user", "content": "ping"}]with stub_endpoint(200) as proxy, stub_endpoint(302) as target, proxy_env(proxy):    loopback = f"{target.url}/v1"    model = OpenAICompatibleModel(loopback, "model", max_tokens=8, api_key="DUMMY-KEY")    reason = refusal(lambda: model.reply(MESSAGES, []))    assert target.seen == ["/v1/chat/completions"], "a redirect was followed"    print("redirect 302 on loopback:", reason)    target.code = 307    reason = refusal(lambda: model.reply(MESSAGES, []))    print("redirect 307 on loopback:", reason)    assert target.seen == ["/v1/chat/completions"] * 2, "a redirect was followed"    print(f"requests to the redirect target: {target.seen.count('/collect')}")    print(f"loopback requests through the proxy: {len(proxy.seen)}")    remote = OpenAICompatibleModel(REMOTE, "model", max_tokens=8)    reply = remote.reply(MESSAGES, [])    assert reply.text == "ok" and proxy.seen == ["http://remote-host.invalid/v1/chat/completions"]    print("remote request through the proxy:", proxy.seen[0])    print("remote reply text:", reply.text)    reason = refusal(lambda: OpenAICompatibleModel(REMOTE, "model", max_tokens=8, api_key="DUMMY-KEY"))    print("key over plain http to a remote host:", reason)    assert len(proxy.seen) == 1, "a request was made for the refused key"    OpenAICompatibleModel("https://remote-host.invalid/v1", "model", max_tokens=8, api_key="DUMMY-KEY")    print("key over https to a remote host: accepted, no request made")    OpenAICompatibleModel(loopback, "model", max_tokens=8, api_key="DUMMY-KEY")    print("key over http to loopback: accepted")    reason = refusal(lambda: OpenAICompatibleModel("file:///v1", "model", max_tokens=8))    print("file URL:", reason)
출력python adapter-refuses-unsafe-endpoints.py
redirect 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판을 번역한 것이다.

이 절 인용

형식

각 형식은 이 번역이 따르는 영문 원서를 출처로 표기한다.

모든 형식은 이 판을 명시한다. 링크는 현재 판을 열며, 여기서 절의 제목은 본문이 마지막으로 바뀐 시점을 알려 준다. 접근 날짜와 검색 날짜는 이 자료를 여는 날짜다.

이 페이지의 내용

12장 중 4장: One interface for scripted, replayed, local and hosted models

  1. Ask every model the same question
  2. Script the replies, or replay a stored run
  3. 로컬 모델과 그 설정이 고정된 이유
  4. 호스티드 방식 엔드포인트, 루프백에서 테스트하기
  5. 하나의 루프, 여러 모델

맨 위로 돌아가기전체 장