Module contents
Lesson 25 of 31Core 105 min

Orchestration and workflows: patterns, state and reliability

Study workflow patterns, durable execution, retries, idempotency, cascades, observability, and LLM program optimization. Build a state-graph engine and evaluate a DSPy program against a manual prompt.

After this lesson you can

  • Choose a workflow pattern and reason about critical-path latency, cost, and quality.
  • Implement a state-graph workflow engine with parallel branches, persistent checkpoints, resumption, and human approvals.
  • Use idempotency keys for safe retries and record per-step cost in traces.
  • Design a local model cascade and evaluate its accuracy-cost trade-off.
  • Optimize an LLM program with DSPy against a manual prompt using held-out data.

Before you start

Choosing control

A workflow fixes the steps and transitions in code, even when a model solves a node. An agent can dynamically decide which tool to call and when to stop. This distinction alone determines neither quality nor cost: a well-specified task can benefit from a fixed flow, while another may require exploration. Building effective agents describes both approaches and their patterns.

The workflow patterns include a chain with validation gates, a router that chooses a branch, independent parallel steps, an orchestrator with workers, and an evaluator-optimizer loop. Parallelism reduces latency only when resources are available, and can increase the total number of calls. For a DAG with duration tvt_v per node, the critical path is the largest sum of durations along a path. Waiting, queues, and concurrency limits can increase actual latency.

InteractivePattern gallery

Question: I have 10 liters of orange drink that are two-thirds water and I wish to add it to 15 liters of pineapple drink that is three-fifths water. But as I pour it, I spill one liter of the orange drink. How much water is in the remaining 24 liters? Reference: 15.

The animation illustrates order and does not replay the measured times.

extract
solve
  1. extract: 9937 ms, 195 tokens; depends on start.
  2. solve: 11197 ms, 299 tokens; depends on extract.

Original run answer: To determine the amount of water in the remaining 24 liters of the mixture, we need to calculate the amount of water in the orange drink and the pineapple drink before and after the spill, and then sum these amounts. 1. **Calculate the amount of water in the 10 liters of orange drink:** - The orange drink is two-thirds water. - Amount of water in the orange drink = \( \frac{2}{3} \times 1

Illustrative cost is one unit per million tokens, not a price. The prior router combines separately measured traces. That composition was not run and its quality is unknown. Independent nodes were measured serially; the critical path assumes they could overlap without waiting.

Prior router
Estimated critical path (ms)21134
Tokens494
Hypothetical cost0.000494
Exact matchno
Explore five measured traces on the same question and add a prior router.

The figure uses five CPU runs of Qwen2.5-7B-Instruct GGUF Q4_K_M on the same GSM8K question. Their responses reached the 96-token limit before producing the FINAL marker, so the parser records 0/5 exact matches. This describes this question and protocol, not a general quality comparison. Tokens are counted per node, and cost assigns one hypothetical unit per million tokens. Timings were measured serially under shared load. The critical path assumes independent nodes can overlap, and does not measure real parallel latency. Adding the router combines separate traces and does not measure the quality of that composition.

You can inspect the five traces. To reproduce them on CPU, prepare the GSM8K file from the later cascade cell and download the GGUF adapter and the pattern runner into the same directory. With llama-cpp-python 0.3.36 and transformers installed, run python patterns-cpu.py. The weights are pinned to revision bb5d59e06d9551d752d08b292a50eb208b07ab1f; both shards are downloaded if absent from the cache.

State and resumption

A state graph declares the data each node reads and writes, which dependencies must finish, and which condition enables a branch. Parallel branches must merge their results in a defined way: incompatible writes to the same key should not be resolved by accidental ordering. A graph can have cycles if it has a stopping condition; the simple engine in the lab only supports DAGs.

Durable execution saves state and progress at checkpoints. After a failure, it resumes from the last committed state. An interruption for human review must record what was approved, who decided, and which data were used, as appropriate to the context. Rerunning a node does not undo its external effects.

Retries with backoff and timeouts help with transient errors, but a timeout can mean the operation succeeded and its response was lost. An idempotency key prevents duplicates only if the system performing the effect records the key atomically with that effect and checks that the key is not reused with different content. A local cache written after an external call cannot provide that atomicity on its own.

InteractiveRetries with side effects

One thousand independent requests. For each attempt, the simulation assigns 10% to failure before creation, 15% to creation with a late response, and 75% to creation with a timely response. Enabling retries permits up to three attempts. Policies consume different numbers of random draws, so their results are not paired trials.

The key prevents duplicates only when the service records the key and effect atomically. A timeout can hide a success, and retrying without that guarantee can create another order.

Retries
Timeout
Idempotency key
Duplicates0
No order2
Unconfirmed20
Attempts1324
Change retries, timeout, and key across one thousand fixed-seed simulated requests.

Cascades and evaluation

A model cascade first queries a cheap model and escalates uncertain cases to a larger one. A signal such as agreement among samples can guide the decision, but is not a calibrated probability of correctness. Choose thresholds on calibration data, evaluate them on held-out questions, and also count sampling and router tokens. FrugalGPT studies cascades and RouteLLM studies learned routers; their results depend on the models and tasks.

InteractiveCascade threshold
  • Exploratory frontier
  • Current thresholds
  • Always 7B

0.5B agreement across three samples: correct / incorrect.

  • Correct
  • Incorrect
0.000 / 11
0.330 / 8
0.670 / 1
1.000 / 0

The weights are 1, 3, and 12 per token for 0.5B, 1.5B, and 7B. If no sample is recognized, the request is escalated. The frontier uses test data and is exploratory: choose thresholds on calibration data. The initial thresholds 0.34 and 0.67 were selected on the 20 calibration questions.

0.34
0.67
Escalated to 1.5B / 7B0.95 / 0.95
Accuracy0.30
Mean relative cost2646.1
Always 7B: accuracy / cost0.30 / 1204.8
Explore agreement, tokens, and accuracy observed on twenty held-out questions.

The figure’s three stages are Qwen2.5-0.5B and 1.5B in GPU FP16, with three samples each, and 7B NF4 with one sample, on the same 20 GSM8K questions. Outputs with no recognizable final number count as failures; strict accuracy can penalize equivalent answers. The sample is small, and exploring it is not equivalent to setting thresholds on calibration data. The cost weights are hypothetical: 1, 3, and 12 per token, not prices.

Maximizing accuracy on 20 calibration questions and breaking ties by cost selected thresholds 0.34 and 0.67. On the 20 held-out questions the cascade escalated 95% to each subsequent stage and achieved accuracy 0.30, the same as always using 7B. The paired difference was 0 with bootstrap interval [0, 0] because the correct decisions coincided in this sample. Mean hypothetical cost was 2646.1 units versus 1204.8 for always using 7B. The cascade did not save cost here, partly because it paid for three samples at each small stage. The degenerate interval and strict parser do not support generalization.

LLM program optimization treats instructions and demonstrations as parameters of a composition of modules. DSPy separates signatures, modules, and optimizers; MIPRO searches for instructions and demonstrations for multistep programs. A development improvement can overfit. Hold out test data and record seeds, model version, search budget, and paired differences.

Observability connects each execution to a hierarchical trace: input, version, start and finish, tokens, cost, branch decision, and error. Redact sensitive data before retaining a trace. A failed case can be added to a future evaluation without turning the test set into tuning data.

Local lab: durable graph

The engine uses asynchronous nodes, atomically stores each batch of independent nodes in SQLite, rejects simultaneous writes to the same key, and logs events. A node can return StepResult with input tokens, output tokens, and cost measured or calculated under an explicit tariff; the event retains those numbers per node. A simulated failure interrupts after merging. The next execution stops at an approval, which the example grants in code to demonstrate resumption. In a real application approval must arrive through the authorized channel. The order tool uses the same database for key and effect; it cannot guarantee idempotency for an external service that does not implement the contract.

We also used this engine to run a draft, critique, and revision with 7B GGUF on CPU. Their events recorded 193, 296, and 396 tokens respectively, at a total hypothetical cost of 0.000885 units. The revision was truncated before the final answer, so it is not reported as correct. The result and JSONL trace are available. To repeat the run, use the same adapter and download the engine and the runner; the GSM8K file must be in workflow-lab.

The next cell’s demonstration replays rag-lab/pipeline.json and rag-lab/generation.json from the previous lesson. Its lists and answer are historical and it records zero new tokens. Simulated branch times are not inference latencies. Each execution uses a distinct identifier and writes its log in workflow-lab.

We also ran the RAG from lesson 22 as a real graph: BM25 and E5/HNSW retrieve candidates, RRF merges them, a cross-encoder reranks them, and 7B GGUF answers with citations. On the first question in the SQuAD corpus, the annotated source appeared among the five retrieved and the answer was Denver Broncos [1], matching the reference and carrying a valid identifier; the answer appeared in the cited source. This is a single case, and lexical checking does not establish entailment. Generation consumed 786 input tokens and 6 output tokens, equivalent to 0.000792 units at the hypothetical tariff; embedding and reranking computation is not included. See the result and trace. To reproduce it, prepare rag-lab/squad.json with the first cell of lesson 22 and download the earlier adapter and engine along with the RAG runner.

[ ]Checkpoints, pause, and idempotencyLocal GPU
import asyncio,json,math,sqlite3,time,uuid
from dataclasses import dataclass,asdict
from typing import Callable,Awaitable,Any

@dataclass(frozen=True)
class StepResult:
    patch:dict
    input_tokens:int=0
    output_tokens:int=0
    cost:float=0.0

@dataclass(frozen=True)
class Node:
    name:str
    deps:tuple[str,...]
    run:Callable[[dict],Awaitable[dict|StepResult]]
    when:Callable[[dict],bool]=lambda s:True

@dataclass
class WorkflowState:
    question:str
    approved:bool=False
    lex:list[int]|None=None
    dense:list[int]|None=None
    fused:list[int]|None=None
    reviewed:bool=False
    answer:str=''
    historical_prompt_tokens:int=0
    answer_has_citation:bool=False
    diagnostic:str=''

class NeedsApproval(Exception):pass

class Store:
    def __init__(self,path):
        self.db=sqlite3.connect(path)
        self.db.execute('CREATE TABLE IF NOT EXISTS runs (id TEXT PRIMARY KEY,state TEXT NOT NULL,done TEXT NOT NULL)')
        self.db.execute('CREATE TABLE IF NOT EXISTS events (seq INTEGER PRIMARY KEY AUTOINCREMENT,run_id TEXT,node TEXT,event TEXT,data TEXT)')
        self.db.execute('CREATE TABLE IF NOT EXISTS orders (idempotency_key TEXT PRIMARY KEY,payload TEXT NOT NULL,result TEXT NOT NULL)')
        self.db.commit()
    def initialize(self,run_id,state):
        with self.db:self.db.execute('INSERT OR IGNORE INTO runs VALUES (?,?,?)',(run_id,json.dumps(state),json.dumps([])))
    def load(self,run_id):
        row=self.db.execute('SELECT state,done FROM runs WHERE id=?',(run_id,)).fetchone()
        if row is None:raise KeyError(run_id)
        return json.loads(row[0]),set(json.loads(row[1]))
    def checkpoint(self,run_id,state,done,events):
        with self.db:
            self.db.execute('UPDATE runs SET state=?,done=? WHERE id=?',(json.dumps(state,ensure_ascii=False),json.dumps(sorted(done)),run_id))
            self.db.executemany('INSERT INTO events(run_id,node,event,data) VALUES (?,?,?,?)',[(run_id,n,e,json.dumps(d,ensure_ascii=False)) for n,e,d in events])
    def approve(self,run_id):
        state,done=self.load(run_id);state['approved']=True;self.checkpoint(run_id,state,done,[('human','approval',{})])
    def create_order(self,key,payload,fail_after_commit=False):
        # El efecto y la clave comparten una transacción SQLite.
        encoded=json.dumps(payload,sort_keys=True,ensure_ascii=False)
        with self.db:
            row=self.db.execute('SELECT payload,result FROM orders WHERE idempotency_key=?',(key,)).fetchone()
            if row:
                if row[0]!=encoded:raise ValueError('clave reutilizada con otro contenido')
                return json.loads(row[1])
            result={'order_id':key,'status':'created'}
            self.db.execute('INSERT INTO orders VALUES (?,?,?)',(key,encoded,json.dumps(result)))
        if fail_after_commit:raise TimeoutError('respuesta perdida después del commit')
        return result
    def export_jsonl(self,run_id,path):
        rows=self.db.execute('SELECT seq,node,event,data FROM events WHERE run_id=? ORDER BY seq',(run_id,)).fetchall()
        with open(path,'w',encoding='utf8') as f:
            for seq,node,event,data in rows:f.write(json.dumps({'seq':seq,'node':node,'event':event,'data':json.loads(data)},ensure_ascii=False)+'\n')

async def run_graph(nodes,run_id,store,initial,crash_after=None):
    names={n.name for n in nodes}
    if len(names)!=len(nodes) or any(set(n.deps)-names for n in nodes):raise ValueError('grafo inválido')
    store.initialize(run_id,initial);state,done=store.load(run_id)
    while done!=names:
        ready=[n for n in nodes if n.name not in done and set(n.deps)<=done]
        if not ready:raise ValueError('ciclo o dependencia imposible')
        flags={n.name:n.when(state) for n in ready}
        active=[n for n in ready if flags[n.name]];skipped=[n for n in ready if not flags[n.name]]
        snapshot=json.loads(json.dumps(state));start=time.perf_counter()
        try:outputs=await asyncio.gather(*(n.run(json.loads(json.dumps(snapshot))) for n in active))
        except NeedsApproval:
            store.checkpoint(run_id,state,done,[('approval','interrupt',{})]);return {'status':'paused','state':state}
        results=[out if isinstance(out,StepResult) else StepResult(out) for out in outputs]
        if any(not isinstance(r.patch,dict) or type(r.input_tokens) is not int or type(r.output_tokens) is not int or r.input_tokens<0 or r.output_tokens<0 or type(r.cost) not in (int,float) or not math.isfinite(r.cost) or r.cost<0 for r in results):
            raise ValueError('resultado o coste de nodo inválido')
        patches=[r.patch for r in results]
        keys=[k for patch in patches for k in patch]
        if len(set(keys))!=len(keys):raise ValueError('ramas escriben la misma clave')
        for patch in patches:state.update(patch)
        done.update(n.name for n in ready)
        elapsed=time.perf_counter()-start
        events=[(n.name,'completed',{'batch_seconds':elapsed,'patch_keys':list(r.patch),'input_tokens':r.input_tokens,'output_tokens':r.output_tokens,'cost':r.cost}) for n,r in zip(active,results)]
        events += [(n.name,'skipped',{}) for n in skipped]
        store.checkpoint(run_id,state,done,events)
        if crash_after and crash_after in done:raise RuntimeError('fallo inyectado tras checkpoint')
    return {'status':'complete','state':state}

async def demo():
    from pathlib import Path
    root=Path('workflow-lab');root.mkdir(parents=True,exist_ok=True)
    source=json.load(open('rag-lab/pipeline.json',encoding='utf8'))['cases'][0]
    generation=json.load(open('rag-lab/generation.json',encoding='utf8'))[0]
    async def lexical(s):await asyncio.sleep(.02);return {'lex':source['lex']}
    async def dense(s):await asyncio.sleep(.02);return {'dense':source['dense']}
    async def fuse(s):
        scores={}
        for ranking in (s['lex'],s['dense']):
            for rank,i in enumerate(ranking,1):scores[i]=scores.get(i,0)+1/(60+rank)
        order=sorted(scores,key=lambda i:(-scores[i],i))[:20]
        return {'fused':order}
    async def approval(s):
        if not s.get('approved'):raise NeedsApproval()
        return {'reviewed':True}
    async def answer(s):return {'answer':generation['answer'],'historical_prompt_tokens':generation['usage']['prompt_tokens']}
    async def critic(s):return {'answer_has_citation':'[1]' in s['answer']}
    async def optimize(s):return {'diagnostic':'falta cita, solicitar otra generación'}
    nodes=[Node('lex',(),lexical),Node('dense',(),dense),Node('fuse',('lex','dense'),fuse),Node('approval',('fuse',),approval),
           Node('answer',('approval',),answer),Node('critic',('answer',),critic),Node('optimize',('critic',),optimize,lambda s:not s['answer_has_citation'])]
    db=root/'workflow.sqlite';store=Store(str(db));run='m23-l25-'+uuid.uuid4().hex
    print('run_id',run,flush=True)
    initial=asdict(WorkflowState(question=source['question']['question']))
    try:await run_graph(nodes,run,store,initial,crash_after='fuse')
    except RuntimeError:print('Fallo tras fusionar: checkpoint conservado',flush=True)
    paused=await run_graph(nodes,run,store,{});print('estado',paused['status'],flush=True)
    store.approve(run);final=await run_graph(nodes,run,store,{})
    assert final['state']['fused']==source['fused'] and final['state']['answer']==generation['answer']
    try:store.create_order('demo-1',{'sku':'libro'},fail_after_commit=True)
    except TimeoutError:pass
    result=store.create_order('demo-1',{'sku':'libro'});count=store.db.execute('SELECT COUNT(*) FROM orders WHERE idempotency_key=?',('demo-1',)).fetchone()[0]
    assert count==1;store.export_jsonl(run,str(root/'trace.jsonl'))
    print('estado',final['status'],'respuesta histórica',final['state']['answer'],'pedidos',count,result,flush=True)
    store.db.close()

if __name__=='__main__':asyncio.run(demo())
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Local lab: agreement signals

The cell downloads the official GSM8K dataset and uses the first 20 questions for calibration and the next 20 for testing. It runs three samples per small or intermediate model; 7B NF4 uses one response. Change which and run each stage separately. Results are saved by model and device and can be resumed. The 7B model requires CUDA, bitsandbytes, and accelerate; the others use CUDA FP16 when available and CPU FP32 otherwise. The parser accepts only a complete number or an explicit final marker and retains the original text for inspection.

[ ]Generate cascade samplesLocal GPU
import hashlib,requests
from pathlib import Path
Path('workflow-lab').mkdir(exist_ok=True)
p=Path('workflow-lab/gsm8k-test.jsonl')
if not p.exists():
    r=requests.get('https://raw.githubusercontent.com/openai/grade-school-math/3101c7d5072418e28b9008a6636bde82a006892c/grade_school_math/data/test.jsonl',timeout=120);r.raise_for_status();p.write_bytes(r.content)
if hashlib.sha256(p.read_bytes()).hexdigest()!='3730d312f6e3440559ace48831e51066acaca737f6eabec99bccb9e4b3c39d14':raise ValueError('hash incorrecto')

import json,re,sys,time,collections,decimal,os,torch
from transformers import AutoTokenizer,AutoModelForCausalLM,BitsAndBytesConfig
torch.set_num_threads(6)
root='workflow-lab/'
rows=[json.loads(s) for s in open(root+'gsm8k-test.jsonl',encoding='utf8')][:40]
which='small'  # repetir con 'mid' y 'large'
configs={'small':('Qwen/Qwen2.5-0.5B-Instruct','7ae557604adf67be50417f59c2c2f167def9a775'),
         'mid':('Qwen/Qwen2.5-1.5B-Instruct','989aa7980e4cf806f80c7fef2b1adb7bc71aa306'),
         'large':('Qwen/Qwen2.5-7B-Instruct','a09a35458c702b33eeacc393d103063234e8bc28')}
name,rev=configs[which];tok=AutoTokenizer.from_pretrained(name,revision=rev)
if which=='large':
    quant=BitsAndBytesConfig(load_in_4bit=True,bnb_4bit_quant_type='nf4',bnb_4bit_compute_dtype=torch.float16)
    model=AutoModelForCausalLM.from_pretrained(name,revision=rev,quantization_config=quant,device_map={'':0},dtype=torch.float16).eval();device='cuda'
else:
    device='cuda' if torch.cuda.is_available() else 'cpu'
    model=AutoModelForCausalLM.from_pretrained(name,revision=rev,dtype=torch.float16 if device=='cuda' else torch.float32).to(device).eval()
def extract(s):
    matches=re.findall(r'[-+]?\d+(?:\.\d+)?',s.replace(',',''))
    if not matches:return None
    try:return str(decimal.Decimal(matches[-1]).normalize())
    except decimal.InvalidOperation:return None
def parse_response(s):
    s=s.replace(',','').strip()
    m=re.fullmatch(r'\$?\s*([-+]?\d+(?:\.\d+)?)\s*[.!]?',s)
    if not m:m=re.search(r'(?:####|final answer(?:\s+is|\s*:))\s*\$?\s*([-+]?\d+(?:\.\d+)?)',s,re.I)
    return str(decimal.Decimal(m.group(1)).normalize()) if m else None
path=root+'cascade-'+which+'-'+device+'.json';results=json.load(open(path,encoding='utf8')) if os.path.exists(path) else []
for i in range(len(results),len(rows)):
    item=rows[i];ground=extract(item['answer'].split('####')[-1]);n=1 if which=='large' else 3
    prompt='Solve the problem. Return only the final numeric answer.\nProblem: '+item['question']+'\nAnswer:'
    chat=tok.apply_chat_template([{'role':'user','content':prompt}],tokenize=False,add_generation_prompt=True)
    batch=tok(chat,return_tensors='pt').to(device);torch.manual_seed(25000+i);start=time.perf_counter()
    kwargs={'max_new_tokens':48,'pad_token_id':tok.eos_token_id,'num_return_sequences':n,'do_sample':n>1}
    if n>1:kwargs.update(temperature=.7,top_p=.95)
    with torch.no_grad():out=model.generate(**batch,**kwargs)
    generated=out[:,batch['input_ids'].shape[1]:];texts=tok.batch_decode(generated,skip_special_tokens=True);values=[parse_response(t) for t in texts]
    lengths=[]
    for seq in generated.tolist():
        lengths.append(seq.index(tok.eos_token_id)+1 if tok.eos_token_id in seq else len(seq))
    counts=collections.Counter(v for v in values if v is not None)
    winner=max(counts,key=lambda v:(counts[v],-values.index(v))) if counts else None
    record={'index':i,'split':'calibracion' if i<20 else 'prueba','question':item['question'],'gold':ground,'raw':texts,
            'values':values,'winner':winner,'confidence':counts[winner]/n if winner is not None else 0,
            'correct':winner==ground if winner is not None else False,'prompt_tokens':batch['input_ids'].shape[1]*n,
            'output_tokens':sum(lengths),'seconds':time.perf_counter()-start}
    results.append(record)
    with open(path,'w',encoding='utf8') as f:json.dump(results,f,ensure_ascii=False,indent=2)
    print(which,i,record['confidence'],record['correct'],repr(texts),flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

With both smaller stages run on CUDA, this cell selects a threshold using only calibration and compares held-out accuracy with always using 1.5B. Relative cost is an illustrative weighting, not a price. If you ran both on CPU, change the filename suffix. The figure and later variant also include 7B, with two thresholds selected on calibration.

[ ]Calibrate and compare on test dataLocal GPU
import json,random
root='workflow-lab/'
a=json.load(open(root+'cascade-small-cuda.json',encoding='utf8'));b=json.load(open(root+'cascade-mid-cuda.json',encoding='utf8'))
assert len(a)==len(b)==40 and all(x['index']==y['index'] for x,y in zip(a,b))
thresholds=[0,.01,.34,.67,1]
def evaluate(indices,t):
    correct=[];cost=[];escalated=[]
    for i in indices:
        x,y=a[i],b[i];up=x['winner'] is None or x['confidence']<t
        correct.append(int(y['correct'] if up else x['correct']));escalated.append(int(up))
        cost.append(x['prompt_tokens']+x['output_tokens']+(3*(y['prompt_tokens']+y['output_tokens']) if up else 0))
    return {'accuracy':sum(correct)/len(correct),'cost_units':sum(cost)/len(cost),'escalated':sum(escalated)/len(escalated),'correct':correct}
dev=[(t,evaluate(range(20),t)) for t in thresholds]
chosen=max(dev,key=lambda x:(x[1]['accuracy'],-x[1]['cost_units']))[0]
test=evaluate(range(20,40),chosen)
always=[int(x['correct']) for x in b[20:]];delta=[u-v for u,v in zip(test['correct'],always)]
rng=random.Random(25);boot=sorted(sum(rng.choice(delta) for _ in delta)/len(delta) for _ in range(2000))
summary={'chosen':chosen,'calibration':dev,'test':test,'always_mid_accuracy':sum(always)/len(always),
         'paired_difference':sum(delta)/len(delta),'bootstrap_ci':[boot[49],boot[1949]]}
with open(root+'cascade-analysis.json','w',encoding='utf8') as f:json.dump(summary,f,indent=2)
print(summary,flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Local lab: optimizing demonstrations

If you do not have a compatible endpoint, save this minimal adapter as servidor_local.py and run it in a separate terminal with python servidor_local.py 18973. It listens only on loopback, supports non-streaming chat, and requires PyTorch, transformers, and CUDA. Stop that process when finished. The adapter pins the Qwen revision used in the measurement and does not implement a production server’s full API.

import json,sys,time,uuid,torch
from http.server import BaseHTTPRequestHandler,HTTPServer
from transformers import AutoTokenizer,AutoModelForCausalLM
name='Qwen/Qwen2.5-0.5B-Instruct';rev='7ae557604adf67be50417f59c2c2f167def9a775'
tok=AutoTokenizer.from_pretrained(name,revision=rev)
model=AutoModelForCausalLM.from_pretrained(name,revision=rev,dtype=torch.float16).to('cuda').eval()
class Handler(BaseHTTPRequestHandler):
    def respond(self,code,payload):
        data=json.dumps(payload,ensure_ascii=False).encode('utf8');self.send_response(code)
        self.send_header('Content-Type','application/json');self.send_header('Content-Length',str(len(data)));self.end_headers();self.wfile.write(data)
    def do_GET(self):
        if self.path=='/v1/models':self.respond(200,{'object':'list','data':[{'id':'local','object':'model','owned_by':'local'}]})
        else:self.respond(404,{'error':'not found'})
    def do_POST(self):
        if self.path!='/v1/chat/completions':return self.respond(404,{'error':'not found'})
        try:
            body=json.loads(self.rfile.read(int(self.headers.get('Content-Length','0'))))
            if body.get('stream') or body.get('n',1)!=1:raise ValueError('solo n=1 y sin streaming')
            text=tok.apply_chat_template(body['messages'],tokenize=False,add_generation_prompt=True)
            batch=tok(text,return_tensors='pt').to('cuda');temperature=body.get('temperature',0) or 0
            kwargs={'max_new_tokens':body.get('max_tokens',body.get('max_completion_tokens',96)),'do_sample':temperature>0,'pad_token_id':tok.eos_token_id}
            if temperature>0:kwargs['temperature']=temperature
            with torch.no_grad():out=model.generate(**batch,**kwargs)
            generated=out[0,batch['input_ids'].shape[1]:];content=tok.decode(generated,skip_special_tokens=True)
            prompt=int(batch['input_ids'].shape[1]);completion=int(generated.shape[0]);finish='length' if completion>=kwargs['max_new_tokens'] else 'stop'
            self.respond(200,{'id':'chatcmpl-'+uuid.uuid4().hex,'object':'chat.completion','created':int(time.time()),'model':'local',
                              'choices':[{'index':0,'message':{'role':'assistant','content':content},'finish_reason':finish}],
                              'usage':{'prompt_tokens':prompt,'completion_tokens':completion,'total_tokens':prompt+completion}})
        except Exception as e:self.respond(400,{'error':{'message':str(e),'type':'invalid_request_error'}})
    def log_message(self,fmt,*args):pass
if __name__=='__main__':
    port=int(sys.argv[1]);print('HTTP loopback',port,'Qwen 0.5B FP16 GPU',flush=True)
    HTTPServer(('127.0.0.1',port),Handler).serve_forever()

The following program uses DSPy 3.5.0 and LiteLLM 1.109.1 with a compatible local chat server at http://127.0.0.1:18973/v1, model local. Start the endpoint separately and point it to a real model. The measurement used Qwen2.5-0.5B-Instruct FP16 on GPU. The program extracts an integer and classifies its parity with two modules, optimizes demonstrations with BootstrapFewShot on four examples, and compares a manual prompt with four other held-out examples. The local endpoint needs no remote-service credentials.

In the recorded run, the manual prompt answered 4/4 correctly and the optimized program 2/4, for paired difference -0.5 and bootstrap interval [-1.0, 0.0]. This tiny synthetic task does not show that optimizing programs generally makes them worse. The parser accepts a single even or odd label in the response and may misread a negation; inspect the saved answers. Searching for demonstrations also consumes calls and time, which must be counted alongside the result.

[ ]DSPy: demonstrations and held-out testLocal GPU
import json,random,re,time,dspy
from pathlib import Path
root='workflow-lab/'
Path(root).mkdir(parents=True,exist_ok=True)
lm=dspy.LM('openai/local',model_type='chat',api_base='http://127.0.0.1:18973/v1',api_key='local',engine='litellm',cache=False,max_tokens=32,temperature=0)
dspy.configure(lm=lm)
class Extract(dspy.Signature):
    """Extract the integer from the text; return only the integer."""
    text:str=dspy.InputField()
    number:str=dspy.OutputField()
class Classify(dspy.Signature):
    """Classify the integer as even or odd; return only even or odd."""
    number:str=dspy.InputField()
    parity:str=dspy.OutputField()
class Program(dspy.Module):
    def __init__(self):
        super().__init__();self.extract=dspy.Predict(Extract);self.classify=dspy.Predict(Classify)
    def forward(self,text):
        number=self.extract(text=text).number
        parity=self.classify(number=number).parity
        return dspy.Prediction(parity=parity)
def gold(i):return 'even' if i%2==0 else 'odd'
def label(text):
    found=set(re.findall(r'\b(?:even|odd)\b',str(text).lower()))
    return next(iter(found)) if len(found)==1 else None
def metric(example,prediction,trace=None):return label(prediction.parity)==example.parity
train=[dspy.Example(text=f'Please classify the number {i}.',parity=gold(i)).with_inputs('text') for i in (3,4,5,6)]
test=[dspy.Example(text=f'Please classify the number {i}.',parity=gold(i)).with_inputs('text') for i in (7,8,9,10)]
opt=dspy.BootstrapFewShot(metric=metric,max_bootstrapped_demos=1,max_labeled_demos=2,max_rounds=1,max_errors=10)
start=time.perf_counter();program=opt.compile(Program(),trainset=train);compile_seconds=time.perf_counter()-start
results=[]
for ex in test:
    start=time.perf_counter();baseline=lm('Return only even or odd. '+ex.text)[0].strip();baseline_time=time.perf_counter()-start
    start=time.perf_counter();prediction=program(text=ex.text).parity.strip();program_time=time.perf_counter()-start
    row={'text':ex.text,'gold':ex.parity,'baseline':baseline,'optimized':prediction,
         'baseline_correct':label(baseline)==ex.parity,'optimized_correct':label(prediction)==ex.parity,
         'baseline_seconds':baseline_time,'optimized_seconds':program_time}
    results.append(row)
    with open(root+'dspy-progress.json','w',encoding='utf8') as f:json.dump(results,f,ensure_ascii=False,indent=2)
    print(ex.text,'baseline',repr(baseline),'optimized',repr(prediction),flush=True)
diff=[int(x['optimized_correct'])-int(x['baseline_correct']) for x in results];rng=random.Random(25)
boot=sorted(sum(rng.choice(diff) for _ in diff)/len(diff) for _ in range(2000))
summary={'n':len(results),'baseline':sum(x['baseline_correct'] for x in results)/len(results),
         'optimized':sum(x['optimized_correct'] for x in results)/len(results),'paired_difference':sum(diff)/len(diff),
         'ci':[boot[49],boot[1949]],'compile_seconds':compile_seconds,'rows':results}
with open(root+'dspy-results.json','w',encoding='utf8') as f:json.dump(summary,f,ensure_ascii=False,indent=2)
print({k:v for k,v in summary.items() if k!='rows'},flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Once you have also generated the 7B responses, this variant selects two thresholds on calibration and compares the three-stage cascade against always using the largest model on test data. It requires the three CUDA files and records a paired interval. The weights 1, 3, and 12 are hypothetical units per token. The measured results appear in the earlier figure.

[ ]Calibrate three stagesLocal GPU
import json,random,itertools
root='workflow-lab/'
a=json.load(open(root+'cascade-small-cuda.json',encoding='utf8'))
b=json.load(open(root+'cascade-mid-cuda.json',encoding='utf8'))
c=json.load(open(root+'cascade-large-cuda.json',encoding='utf8'))
assert len(a)==len(b)==len(c)==40 and all(x['index']==y['index']==z['index'] for x,y,z in zip(a,b,c))
thresholds=[0,.01,.34,.67,1]
def evaluate(indices,t1,t2):
    correct=[];cost=[];up1s=[];up2s=[]
    for i in indices:
        x,y,z=a[i],b[i],c[i];up1=x['winner'] is None or x['confidence']<t1
        up2=up1 and (y['winner'] is None or y['confidence']<t2)
        correct.append(int(z['correct'] if up2 else y['correct'] if up1 else x['correct']))
        cost.append(x['prompt_tokens']+x['output_tokens']+(3*(y['prompt_tokens']+y['output_tokens']) if up1 else 0)+(12*(z['prompt_tokens']+z['output_tokens']) if up2 else 0))
        up1s.append(int(up1));up2s.append(int(up2))
    return {'accuracy':sum(correct)/len(correct),'cost_units':sum(cost)/len(cost),'to_mid':sum(up1s)/len(up1s),
            'to_large':sum(up2s)/len(up2s),'correct':correct}
cal=[(t1,t2,evaluate(range(20),t1,t2)) for t1,t2 in itertools.product(thresholds,repeat=2)]
chosen=max(cal,key=lambda x:(x[2]['accuracy'],-x[2]['cost_units']));test=evaluate(range(20,40),chosen[0],chosen[1])
always=[int(x['correct']) for x in c[20:]];delta=[x-y for x,y in zip(test['correct'],always)];rng=random.Random(25)
boot=sorted(sum(rng.choice(delta) for _ in delta)/len(delta) for _ in range(2000))
summary={'chosen_thresholds':chosen[:2],'calibration':cal,'test':test,'always_large_accuracy':sum(always)/len(always),
         'paired_difference':sum(delta)/len(delta),'bootstrap_ci':[boot[49],boot[1949]]}
with open(root+'cascade3-analysis.json','w',encoding='utf8') as f:json.dump(summary,f,indent=2)
print(summary,flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

CodeRetry with a key
Implement idempotent(key_fn, store): return a decorator that calculates a key for each call, returns an already stored result or calls the tool with idempotency_key and stores its result upon completion. The tool service must also apply the key atomically with its effect: the local decorator alone cannot recover a result lost after a timeout.
def idempotent(key_fn, store):
  pass
Shift+Enter to run
CodeBranch checkpoint
Implement async run_graph(graph, state, checkpoint_store). graph maps each name to deps and an async fn that receives a copy of the state and returns a patch. Run ready nodes in parallel. Save each completed patch in checkpoint_store. If a branch fails, propagate the error and do not repeat finished branches when resuming. Branches in the same batch must receive the same snapshot even on resumption. Detect cycles and incompatible parallel writes. The exercise store is a dictionary; real durability requires atomic persistence.
async def run_graph(graph, state, checkpoint_store):
  pass
Shift+Enter to run
NumericExpected cost
The small model costs 1 per request and escalates 30% to the large model, which costs an additional 12. What is the expected cost per request?
Quiz
You need to summarize four independent sections and combine them. Which pattern should you try first?
Quiz
A request must go to billing or technical support depending on its content. Which pattern is appropriate?
Quiz
You must extract fields, validate them, and produce a report only if they meet a schema. Which pattern fits?
Quiz
The number of subtasks varies by document and each can be processed separately. Which pattern is worth investigating?
Quiz
A draft must satisfy a verifiable rubric before delivery. Which pattern is appropriate?
Quiz
An optimizer improves by 12 points on development and 2 on test. Which explanation and check are reasonable?
Key idea
A reliable workflow makes state, dependencies, effects, and evaluation explicit. Additional complexity must be justified by measurements.