import numpy as np
rng = np.random.default_rng(0)
X = rng.normal(size=(200, 3)) # 200 samples, 3 features
y = X @ np.array([2.0, -1.0, 0.5]) + 0.3 + 0.1 * rng.normal(size=200)
w, b, lr = np.zeros(3), 0.0, 0.1
for step in range(500):
err = X @ w + b - y # prediction error
loss = (err ** 2).mean() # mean squared error
w -= lr * 2 * X.T @ err / len(y) # dL/dw, derived by hand
b -= lr * 2 * err.mean() # dL/db
if step % 100 == 0:
print(f"step {step:3d} loss {loss:.4f}")
# sanity check against the closed-form least-squares answer
A = np.c_[X, np.ones(len(y))]
print("gradient descent:", np.round(np.r_[w, b], 3))
print("least squares :", np.round(np.linalg.lstsq(A, y, rcond=None)[0], 3))
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset, random_split
torch.manual_seed(0)
X = torch.rand(2000, 2) * 4 - 2 # swap in your own measurements here
y = torch.sin(2 * X[:, :1]) + X[:, 1:] ** 2 + 0.05 * torch.randn(2000, 1)
train_ds, val_ds = random_split(TensorDataset(X, y), [1600, 400])
train_dl = DataLoader(train_ds, batch_size=64, shuffle=True)
val_dl = DataLoader(val_ds, batch_size=400)
model = nn.Sequential(nn.Linear(2, 64), nn.ReLU(), nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 1))
opt = torch.optim.AdamW(model.parameters(), lr=3e-3)
loss_fn = nn.MSELoss()
yv = torch.cat([yb for _, yb in val_dl])
print(f"baseline (always predict the mean): {((yv - yv.mean()) ** 2).mean():.4f}")
best = float("inf")
for epoch in range(30):
model.train()
for xb, yb in train_dl:
loss = loss_fn(model(xb), yb)
opt.zero_grad()
loss.backward() # autograd does the calculus
opt.step()
model.eval()
with torch.no_grad():
val = sum(loss_fn(model(xb), yb).item() * len(xb) for xb, yb in val_dl) / len(val_ds)
if val < best: # keep the best checkpoint, not the last
best = val
torch.save(model.state_dict(), "best.pt")
if epoch % 5 == 0:
print(f"epoch {epoch:2d} val_mse {val:.4f}")
print(f"best val_mse {best:.4f}")
import torch
import torch.nn.functional as F
torch.manual_seed(0)
B, T, C = 2, 8, 32 # batch, sequence length, embedding size
x = torch.randn(B, T, C)
Wq, Wk, Wv = (torch.nn.Linear(C, C, bias=False) for _ in range(3))
q, k, v = Wq(x), Wk(x), Wv(x)
scores = q @ k.transpose(-2, -1) / C ** 0.5 # (B, T, T): how much each token attends to each other
causal = torch.tril(torch.ones(T, T, dtype=torch.bool))
scores = scores.masked_fill(~causal, float("-inf")) # a token may not look at the future
out = F.softmax(scores, dim=-1) @ v # (B, T, C): weighted mix of values
ref = F.scaled_dot_product_attention(q, k, v, is_causal=True)
print("matches PyTorch's built-in attention:", torch.allclose(out, ref, atol=1e-5))
import json, os, pathlib, urllib.request
BASE = os.environ.get("LLM_BASE_URL", "https://api.deepseek.com") # any OpenAI-compatible endpoint
MODEL = os.environ.get("LLM_MODEL", "deepseek-chat")
KEY = os.environ.get("LLM_API_KEY", "")
ROOT = pathlib.Path("workspace").resolve() # the agent may only touch this folder
ROOT.mkdir(exist_ok=True)
def inside(path): # permission check #1: stay in the sandbox
p = (ROOT / path).resolve()
if not p.is_relative_to(ROOT):
raise PermissionError(f"{path} is outside the workspace")
return p
def list_files(path="."):
return "\n".join(sorted(f.name for f in inside(path).iterdir()))
def read_file(path):
return inside(path).read_text(encoding="utf-8")[:4000] # cap what flows back into context
def write_file(path, content):
if input(f"Allow writing {path}? [y/N] ").strip().lower() != "y": # permission check #2: ask a human
return "the user refused this write"
inside(path).write_text(content, encoding="utf-8")
return f"wrote {len(content)} characters to {path}"
TOOLS = {f.__name__: f for f in (list_files, read_file, write_file)}
SCHEMAS = [
{"type": "function", "function": {"name": "list_files", "description": "List files in a workspace folder",
"parameters": {"type": "object", "properties": {"path": {"type": "string"}}}}},
{"type": "function", "function": {"name": "read_file", "description": "Read a UTF-8 text file from the workspace",
"parameters": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}}},
{"type": "function", "function": {"name": "write_file", "description": "Create or overwrite a text file in the workspace",
"parameters": {"type": "object", "properties": {"path": {"type": "string"}, "content": {"type": "string"}},
"required": ["path", "content"]}}},
]
def chat(messages):
body = json.dumps({"model": MODEL, "messages": messages, "tools": SCHEMAS}).encode()
req = urllib.request.Request(BASE.rstrip("/") + "/chat/completions", data=body,
headers={"Content-Type": "application/json", "Authorization": f"Bearer {KEY}"})
with urllib.request.urlopen(req, timeout=120) as r:
return json.load(r)["choices"][0]["message"]
def run(task, max_steps=10):
messages = [{"role": "system", "content": "You work inside a sandboxed workspace. Use the tools; never guess file contents."},
{"role": "user", "content": task}]
for step in range(max_steps): # the loop is the agent
msg = chat(messages)
messages.append(msg)
if not msg.get("tool_calls"):
return msg.get("content")
for call in msg["tool_calls"]:
name, args = call["function"]["name"], json.loads(call["function"]["arguments"] or "{}")
try:
result = TOOLS[name](**args)
except Exception as e: # errors go back to the model, not up the stack
result = f"error: {e}"
print(f"[{step}] {name}({args}) -> {str(result)[:60]!r}") # the trace: your first eval tool
messages.append({"role": "tool", "tool_call_id": call["id"], "content": str(result)})
return "stopped: step limit reached"
if __name__ == "__main__":
print(run("Summarise every .txt file in the workspace into summary.md"))