GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • All gists
  • Back to GitHub
  • Sign in
  • Sign up
  • Code
  • Revisions 1
  • Terms
  • Privacy
  • Security
  • Status
  • Community
  • Docs
  • Contact

This view

  • Original page
  • New address

GeezerVison is showing gist.github.com — Code Mode vs tool calling: same task, two token accounts (OpenCode)

Instantly share code, notes, and snippets.

@RicSchonfelder

RicSchonfelder/README.md

Created October 24, 2026 14:04
Show Gist options
  • Download ZIP
  • Star 0 (0) You must be signed in to star a gist
  • Fork 0 (0) You must be signed in to fork a gist
  • Clone this repository at <script src="https://gist.github.com/RicSchonfelder/268a51cb86395db36eaac0aa018686cd.js"></script>
  • Save RicSchonfelder/268a51cb86395db36eaac0aa018686cd to your computer and use it in GitHub Desktop.
Clone this repository at <script src="https://gist.github.com/RicSchonfelder/268a51cb86395db36eaac0aa018686cd.js"></script>
Save RicSchonfelder/268a51cb86395db36eaac0aa018686cd to your computer and use it in GitHub Desktop.
Download ZIP
Code Mode vs tool calling: same task, two token accounts (OpenCode)
Raw
README.md

Code Mode vs tool calling: same task, two accounts

Benchmark from OpenCode v2.1.4 on Linux, used in https://github.com/anomalyco/opencode/issues — "Code Mode needs a token budget and a per-tool breakdown".

Two measurements:

  1. Live A/B. The same task in two real OpenCode sessions (deepseek-flash), billing read from session_v2 in opencode.db. Task: fetch 8 URLs, report which ones fail or mention "token".
    • A: one tool call per URL, each body returned whole.
    • B: one execute program, filtered array returned.
A: one call per URL B: one program
tokens in 31,427 696
tokens out 1,566 505
reasoning 1,496 56
cache read 426,752 44,544
total tokens 34,489 1,257
context processed 458,179 45,240
cost $0.00783 $0.00057

27.4x fewer tokens, 13.6x cheaper. The dollar gap is smaller than the token gap because the repeated prefix hits prompt cache.

A also got 3 of 8 answers wrong: its bodies were truncated at 50k characters, which cut off the word "token" on three pages. B searched the full text inside the sandbox and got all 8 right.

  1. Schema cost of one real MCP server. rea (tools/list) exposes 207 tools. Serialized to JSON: 3,423,785 characters, 1,033,360 tokens with tiktoken o200k_base. One tool (address_name) is 2,721 tokens. Injected the traditional way, that server costs 1.03M tokens before the first user message.

  2. Synthetic run (bench.py, same 8 URLs, markup stripped, 50 KiB cap): 114,320 tokens with one call per URL against 2,436 with one program, 46.9x apart, 24.5x once the prefix is priced at a 10% cache rate. Cost grows with N² because every observation is resent in every later request: 20 URLs cost 578k tokens and 50 cost 3.5M.

Reproduce

uv run --with tiktoken python bench.py

The rea numbers come from the server's own tools/list, saved to rea-tools.json:

p = subprocess.Popen(["rea", "mcp"], stdin=PIPE, stdout=PIPE, text=True)
# initialize -> notifications/initialized -> tools/list

Any MCP server works, the point is the size of the payload a client injects.

Raw
bench.py
#!/usr/bin/env python3
"""Reprodução: tool calling tradicional vs Code Mode.
Mede tokens REAIS (tiktoken o200k_base) para a mesma tarefa:
"verifique N URLs, devolva só as que falharam ou que contêm X"
Tradicional: 1 chamada de tool por URL. Cada resultado volta INTEIRO para o
contexto e é reenviado em todas as chamadas seguintes.
Code Mode: 1 programa roda no sandbox, faz os N fetches e devolve só o filtro.
Uso: uv run --with tiktoken python bench.py
"""
import json
import re
import sys
import urllib.request
import tiktoken
ENC = tiktoken.get_encoding("o200k_base")
def tok(s: str) -> int:
return len(ENC.encode(s))
URLS = [
"https://example.com",
"https://opencode.ai/v2/llms.txt",
"https://blog.cloudflare.com/code-mode/",
"https://www.anthropic.com/news/advanced-tool-use",
"https://api.github.com/repos/anomalyco/opencode",
"https://opencode.ai/v2/docs/compaction/",
"https://opencode.ai/v2/docs/tools/",
"https://github.com/anomalyco/opencode/issues/8625",
]
NEEDLE = "token"
def fetch(url: str) -> str:
req = urllib.request.Request(url, headers={"User-Agent": "bench/1.0"})
try:
with urllib.request.urlopen(req, timeout=30) as r:
return r.read().decode("utf-8", "replace")
except Exception as e: # o "status 200 + corpo de erro" também conta como resultado
return f"ERROR {type(e).__name__}: {e}"
def to_text(body: str) -> str:
body = re.sub(r"<script[\s\S]*?</script>", " ", body)
body = re.sub(r"<style[\s\S]*?</style>", " ", body)
body = re.sub(r"<[^>]+>", " ", body)
return re.sub(r"\s+", " ", body).strip()
# ---- schemas de tools (o que o modo tradicional injeta em toda request) ----
TOOL_SCHEMA_8 = [
{
"name": f"fetch_page_{i}",
"description": "Fetch a URL and return the full response body as text. Use this "
"when you need to read a web page, an API response or a file over HTTP. "
"Returns the complete body, truncated at 50 KiB.",
"input_schema": {
"type": "object",
"properties": {
"url": {"type": "string", "description": "Absolute http(s) URL to fetch"},
"format": {"type": "string", "enum": ["text", "markdown", "html"]},
"timeout": {"type": "integer", "minimum": 1, "maximum": 120},
},
"required": ["url"],
},
}
for i in range(8)
]
SCHEMA_TOKENS = tok(json.dumps(TOOL_SCHEMA_8))
QUESTION = (
"Fetch these 8 URLs and tell me which ones fail and which ones mention "
"'token' in the body. Reply with a short list only.\n\n"
+ "\n".join(f"- {u}" for u in URLS)
)
QUESTION_TOKENS = tok(QUESTION)
SYSTEM_TOKENS = 900 # system prompt + instructions típicas
# ---- coleta real ----
observations = []
for u in URLS:
raw = fetch(u)
text = to_text(raw)[: 50 * 1024] # tools reais truncam em ~50 KiB
observations.append(text)
obs_tokens = [tok(o) for o in observations]
# ================= ESTRATÉGIA A: tool calling tradicional =================
# passo 0: request com pergunta + todos os schemas
# passo i: request com pergunta + schemas + todas as observações anteriores
steps_a = []
cum = 0
for i in range(len(URLS) + 1):
context = SYSTEM_TOKENS + SCHEMA_TOKENS + QUESTION_TOKENS + cum
steps_a.append(context)
if i < len(URLS):
# o modelo escreve o JSON da chamada (saída), depois entra a observação
call_out = tok(json.dumps({"name": f"fetch_page_{i}", "arguments": {"url": URLS[i]}}))
cum += call_out + obs_tokens[i]
total_a = sum(steps_a)
peak_a = max(steps_a)
out_a = sum(tok(json.dumps({"name": f"fetch_page_{i}"})) for i in range(len(URLS))) + 60
# ================= ESTRATÉGIA B: Code Mode =================
CODE = """const urls = [...]; // as 8 URLs
const out = [];
for (const u of urls) {
const r = await fetch(u);
const body = await r.text();
if (!r.ok || body.includes("token")) out.push({u, status: r.status});
}
return out;"""
SEARCH_TOOL_TOKENS = tok(
json.dumps(
{
"name": "execute",
"description": "Run JavaScript in a sandbox. Tools are available as "
"typed functions under `tools`. Only the returned value enters context.",
"input_schema": {"type": "object", "properties": {"code": {"type": "string"}}},
}
)
)
code_tokens = tok(CODE)
# o sandbox devolve só o filtro (status das que casaram)
result_payload = json.dumps(
[{"u": u, "status": 200} for u, o in zip(URLS, observations) if NEEDLE in o.lower()]
)
result_tokens = tok(result_payload)
# 2 turnos: (1) escreve o código (2) lê o resultado
b1 = SYSTEM_TOKENS + SEARCH_TOOL_TOKENS + QUESTION_TOKENS
b2 = b1 + code_tokens + result_tokens
total_b = b1 + b2
peak_b = max(b1, b2)
out_b = code_tokens + 40
# ================= SAÍDA =================
print(f"tiktoken o200k_base | {len(URLS)} URLs | needle={NEEDLE!r}\n")
print(f"{'URL':<52} {'tok corpo':>10}")
for u, t in zip(URLS, obs_tokens):
print(f"{u[:52]:<52} {t:>10,}")
print(f"\n{'schema 8 tools':<52} {SCHEMA_TOKENS:>10,}")
print(f"{'observações totais (o que volta ao contexto)':<52} {sum(obs_tokens):>10,}")
print("\n--- A) tool calling tradicional ---")
for i, s in enumerate(steps_a):
print(f" passo {i}: request = {s:>10,} tok")
print(f" total enviado: {total_a:>12,} tok")
print(f" pico de contexto: {peak_a:>9,} tok")
print(f" saída do modelo: {out_a:>10,} tok")
print(f" CUSTO TOTAL: {total_a + out_a:>14,} tok")
print("\n--- B) Code Mode ---")
print(f" passo 0: request = {b1:>10,} tok")
print(f" passo 1: request = {b2:>10,} tok")
print(f" total enviado: {total_b:>12,} tok")
print(f" pico de contexto: {peak_b:>9,} tok")
print(f" CUSTO TOTAL: {total_b + out_b:>14,} tok")
a, b = total_a + out_a, total_b + out_b
print(f"\nrazão A/B: {a / b:.1f}x (economia {100 * (1 - b / a):.1f}%)")
print(f"pico de contexto: {peak_a / peak_b:.1f}x menor em Code Mode")
# ---- com prompt cache (prefixo repetido cobrado a 10%) ----
def billed(steps, discount=0.1):
total = steps[0]
for prev, cur in zip(steps, steps[1:]):
total += prev * discount + max(0, cur - prev)
return total
ca, cb = billed(steps_a), billed([b1, b2])
print(f"com prompt cache a 10%: A={ca:,.0f} B={cb:,.0f} → diferença {ca / cb:.1f}x")
# ---- o schema de um MCP grande (o caso que não cabe na janela) ----
import os
rea = os.path.join(os.path.dirname(__file__), "rea-tools.json")
if os.path.exists(rea):
with open(rea, encoding="utf-8") as f:
schema = f.read()
rea_tokens = tok(schema)
print(
f"\nMCP 'rea' deste usuário: 207 tools = {rea_tokens:,} tokens de schema "
f"(1 tool sozinha = 2,721 tok)"
)
print(f" tradicional: 1ª request = {SYSTEM_TOKENS + rea_tokens + QUESTION_TOKENS:,} tok (não cabe)")
print(f" code mode: search + 2 tools ≈ {SYSTEM_TOKENS + 300 + 2 * 2721:,} tok")
# ---- crescimento: N URLs de T tokens custa ~N²T/2 ----
print("\ncrescimento do modo tradicional (obs média = %d tok):" % (sum(obs_tokens) // len(URLS)))
avg = sum(obs_tokens) // len(URLS)
for n in (8, 20, 50, 100):
print(f" {n:>3} URLs → {int(n * (n + 1) / 2 * avg):>10,} tok enviados")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You are visitor 01402809 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.