|
#!/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") |