shenmali commited on
Commit
53d41ca
·
verified ·
1 Parent(s): f13a831

Upload folder using huggingface_hub

Browse files
Files changed (10) hide show
  1. README.md +11 -7
  2. _core/__init__.py +1 -0
  3. _core/llm.py +42 -0
  4. _core/models.py +41 -0
  5. _core/tools.py +112 -0
  6. _core/tracer.py +27 -0
  7. _core/ui.py +116 -0
  8. agent.py +81 -0
  9. app.py +28 -0
  10. requirements.txt +4 -0
README.md CHANGED
@@ -1,13 +1,17 @@
1
  ---
2
- title: Agentic React From Scratch
3
- emoji: 🚀
4
- colorFrom: pink
5
- colorTo: red
6
  sdk: gradio
7
- sdk_version: 6.15.2
8
- python_version: '3.13'
9
  app_file: app.py
10
  pinned: false
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
1
  ---
2
+ title: ReAct From Scratch
3
+ emoji: 🧠
4
+ colorFrom: blue
5
+ colorTo: indigo
6
  sdk: gradio
7
+ sdk_version: 4.44.0
 
8
  app_file: app.py
9
  pinned: false
10
  ---
11
 
12
+ # ReAct from scratch
13
+
14
+ A Reasoning + Acting agent built from first principles, with a transparent
15
+ step-by-step trace. Bring your own [OpenRouter](https://openrouter.ai/keys) key.
16
+
17
+ Source & write-up: https://github.com/shenmali/agentic-ai-first/tree/main/demos/01-react-from-scratch
_core/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ __version__ = "0.1.0"
_core/llm.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass, field
2
+ from typing import Any
3
+
4
+ from openai import OpenAI
5
+
6
+
7
+ @dataclass
8
+ class LLMResponse:
9
+ content: str | None
10
+ tool_calls: list[dict] = field(default_factory=list)
11
+ prompt_tokens: int = 0
12
+ completion_tokens: int = 0
13
+
14
+
15
+ class LLMClient:
16
+ BASE_URL = "https://openrouter.ai/api/v1"
17
+
18
+ def __init__(self, api_key: str, model: str):
19
+ if not api_key:
20
+ raise ValueError("An OpenRouter API key is required.")
21
+ self.model = model
22
+ self._client = OpenAI(api_key=api_key, base_url=self.BASE_URL)
23
+
24
+ def chat(self, messages: list[dict], tools: list[dict] | None = None) -> LLMResponse:
25
+ kwargs: dict[str, Any] = {"model": self.model, "messages": messages}
26
+ if tools:
27
+ kwargs["tools"] = tools
28
+ resp = self._client.chat.completions.create(**kwargs)
29
+ msg = resp.choices[0].message
30
+ tool_calls = []
31
+ if getattr(msg, "tool_calls", None):
32
+ for tc in msg.tool_calls:
33
+ tool_calls.append(
34
+ {"id": tc.id, "name": tc.function.name, "arguments": tc.function.arguments}
35
+ )
36
+ usage = resp.usage
37
+ return LLMResponse(
38
+ content=msg.content,
39
+ tool_calls=tool_calls,
40
+ prompt_tokens=getattr(usage, "prompt_tokens", 0) if usage else 0,
41
+ completion_tokens=getattr(usage, "completion_tokens", 0) if usage else 0,
42
+ )
_core/models.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+
3
+ # NOTE: model ids and prices reflect OpenRouter's catalog. Verify/refresh against
4
+ # https://openrouter.ai/models before launch — ids change as providers release models.
5
+
6
+
7
+ @dataclass(frozen=True)
8
+ class ModelInfo:
9
+ id: str
10
+ label: str
11
+ prompt_cost: float # USD per 1M prompt tokens
12
+ completion_cost: float # USD per 1M completion tokens
13
+
14
+
15
+ MODELS: list[ModelInfo] = [
16
+ ModelInfo("openai/gpt-4o-mini", "GPT-4o mini (cheap)", 0.15, 0.60),
17
+ ModelInfo("anthropic/claude-3.5-haiku", "Claude 3.5 Haiku (cheap)", 0.80, 4.00),
18
+ ModelInfo("google/gemini-flash-1.5", "Gemini 1.5 Flash (cheap)", 0.075, 0.30),
19
+ ModelInfo("deepseek/deepseek-chat", "DeepSeek Chat (cheap)", 0.14, 0.28),
20
+ ModelInfo("anthropic/claude-3.5-sonnet", "Claude 3.5 Sonnet (strong)", 3.00, 15.00),
21
+ ModelInfo("openai/gpt-4o", "GPT-4o (strong)", 2.50, 10.00),
22
+ ]
23
+
24
+ DEFAULT_MODEL = "openai/gpt-4o-mini"
25
+
26
+
27
+ def model_ids() -> list[str]:
28
+ return [m.id for m in MODELS]
29
+
30
+
31
+ def get_model(model_id: str) -> ModelInfo | None:
32
+ return next((m for m in MODELS if m.id == model_id), None)
33
+
34
+
35
+ def estimate_cost(model_id: str, prompt_tokens: int, completion_tokens: int) -> float:
36
+ m = get_model(model_id)
37
+ if m is None:
38
+ return 0.0
39
+ return (prompt_tokens / 1_000_000) * m.prompt_cost + (
40
+ completion_tokens / 1_000_000
41
+ ) * m.completion_cost
_core/tools.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ast
2
+ import operator
3
+ from collections.abc import Callable
4
+ from dataclasses import dataclass
5
+
6
+
7
+ @dataclass
8
+ class Tool:
9
+ name: str
10
+ description: str
11
+ parameters: dict
12
+ fn: Callable[..., str]
13
+
14
+
15
+ class ToolRegistry:
16
+ def __init__(self) -> None:
17
+ self._tools: dict[str, Tool] = {}
18
+
19
+ def register(self, tool: Tool) -> None:
20
+ self._tools[tool.name] = tool
21
+
22
+ def to_openai_schema(self) -> list[dict]:
23
+ return [
24
+ {
25
+ "type": "function",
26
+ "function": {
27
+ "name": t.name,
28
+ "description": t.description,
29
+ "parameters": t.parameters,
30
+ },
31
+ }
32
+ for t in self._tools.values()
33
+ ]
34
+
35
+ def execute(self, name: str, args: dict) -> str:
36
+ if name not in self._tools:
37
+ return f"Error: unknown tool '{name}'"
38
+ try:
39
+ return self._tools[name].fn(**args)
40
+ except Exception as e: # tool failures must not crash the agent loop
41
+ return f"Error executing {name}: {e}"
42
+
43
+
44
+ _SAFE_OPS = {
45
+ ast.Add: operator.add,
46
+ ast.Sub: operator.sub,
47
+ ast.Mult: operator.mul,
48
+ ast.Div: operator.truediv,
49
+ ast.Pow: operator.pow,
50
+ ast.Mod: operator.mod,
51
+ ast.USub: operator.neg,
52
+ }
53
+
54
+
55
+ def _safe_eval(node: ast.AST) -> int | float:
56
+ if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
57
+ return node.value
58
+ if isinstance(node, ast.BinOp) and type(node.op) in _SAFE_OPS:
59
+ left = _safe_eval(node.left)
60
+ right = _safe_eval(node.right)
61
+ if isinstance(node.op, ast.Pow) and abs(right) > 100:
62
+ raise ValueError("exponent too large")
63
+ return _SAFE_OPS[type(node.op)](left, right)
64
+ if isinstance(node, ast.UnaryOp) and type(node.op) in _SAFE_OPS:
65
+ return _SAFE_OPS[type(node.op)](_safe_eval(node.operand))
66
+ raise ValueError("unsupported expression")
67
+
68
+
69
+ def calculate(expression: str) -> str:
70
+ try:
71
+ tree = ast.parse(expression, mode="eval")
72
+ return str(_safe_eval(tree.body))
73
+ except Exception as e:
74
+ return f"Error: {e}"
75
+
76
+
77
+ def make_calculator() -> Tool:
78
+ return Tool(
79
+ name="calculator",
80
+ description="Evaluate a basic arithmetic expression, e.g. '2 * (3 + 4)'.",
81
+ parameters={
82
+ "type": "object",
83
+ "properties": {"expression": {"type": "string"}},
84
+ "required": ["expression"],
85
+ },
86
+ fn=lambda expression: calculate(expression),
87
+ )
88
+
89
+
90
+ def web_search(query: str, max_results: int = 3) -> str:
91
+ try:
92
+ from ddgs import DDGS
93
+ except ImportError: # package was renamed; support both
94
+ from duckduckgo_search import DDGS # type: ignore
95
+ results = []
96
+ with DDGS() as ddgs:
97
+ for r in ddgs.text(query, max_results=max_results):
98
+ results.append(f"- {r.get('title', '')}: {r.get('body', '')}")
99
+ return "\n".join(results) if results else "No results found."
100
+
101
+
102
+ def make_web_search() -> Tool:
103
+ return Tool(
104
+ name="web_search",
105
+ description="Search the web for current information. Returns the top results.",
106
+ parameters={
107
+ "type": "object",
108
+ "properties": {"query": {"type": "string"}},
109
+ "required": ["query"],
110
+ },
111
+ fn=lambda query: web_search(query),
112
+ )
_core/tracer.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass, field
2
+ from typing import Literal
3
+
4
+ StepKind = Literal["thought", "action", "observation", "final"]
5
+
6
+
7
+ @dataclass
8
+ class Step:
9
+ kind: StepKind
10
+ content: str
11
+ tokens: int = 0
12
+ cost_usd: float = 0.0
13
+ latency_ms: int = 0
14
+
15
+
16
+ @dataclass
17
+ class Trace:
18
+ steps: list[Step] = field(default_factory=list)
19
+
20
+ def add(self, step: Step) -> None:
21
+ self.steps.append(step)
22
+
23
+ def total_tokens(self) -> int:
24
+ return sum(s.tokens for s in self.steps)
25
+
26
+ def total_cost(self) -> float:
27
+ return sum(s.cost_usd for s in self.steps)
_core/ui.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Callable, Iterator
2
+
3
+ import gradio as gr
4
+
5
+ from _core.llm import LLMClient
6
+ from _core.models import DEFAULT_MODEL, model_ids
7
+ from _core.tracer import Step, Trace
8
+
9
+ _KIND_ICON = {"thought": "💭", "action": "🔧", "observation": "👁️", "final": "✅"}
10
+
11
+
12
+ def api_key_input() -> gr.Textbox:
13
+ return gr.Textbox(
14
+ label="OpenRouter API key",
15
+ type="password",
16
+ placeholder="sk-or-...",
17
+ info=(
18
+ "Get a key at https://openrouter.ai/keys — it stays in your browser"
19
+ " session and is never stored."
20
+ ),
21
+ )
22
+
23
+
24
+ def model_selector() -> gr.Dropdown:
25
+ return gr.Dropdown(choices=model_ids(), value=DEFAULT_MODEL, label="Model")
26
+
27
+
28
+ def render_step_markdown(step: Step) -> str:
29
+ icon = _KIND_ICON.get(step.kind, "•")
30
+ meta = ""
31
+ if step.tokens or step.cost_usd or step.latency_ms:
32
+ meta = f" \n<sub>{step.tokens} tok · ${step.cost_usd:.4f} · {step.latency_ms} ms</sub>"
33
+ return f"**{icon} {step.kind.title()}** \n{step.content}{meta}"
34
+
35
+
36
+ def render_trace_markdown(trace: Trace) -> str:
37
+ return "\n\n---\n\n".join(render_step_markdown(s) for s in trace.steps)
38
+
39
+
40
+ def metrics_summary(trace: Trace) -> str:
41
+ return (
42
+ f"**Total:** {trace.total_tokens()} tokens · "
43
+ f"${trace.total_cost():.4f} · {len(trace.steps)} steps"
44
+ )
45
+
46
+
47
+ def build_agent_app(
48
+ *,
49
+ title: str,
50
+ description: str,
51
+ input_label: str,
52
+ input_placeholder: str,
53
+ run_fn: Callable[[LLMClient, str], Iterator[Step]],
54
+ example: str = "",
55
+ ) -> gr.Blocks:
56
+ """Build a standard single-input agent demo.
57
+
58
+ run_fn(llm, user_input) yields Steps. Key validation, LLM construction,
59
+ trace accumulation, rendering and error handling are handled here.
60
+ """
61
+
62
+ def _handler(api_key: str, model_id: str, user_input: str):
63
+ if not api_key:
64
+ yield "⚠️ Please enter your OpenRouter API key.", ""
65
+ return
66
+ try:
67
+ llm = LLMClient(api_key=api_key, model=model_id)
68
+ except Exception as e:
69
+ yield f"⚠️ {e}", ""
70
+ return
71
+ trace = Trace()
72
+ try:
73
+ for step in run_fn(llm, user_input):
74
+ trace.add(step)
75
+ yield render_trace_markdown(trace), metrics_summary(trace)
76
+ except Exception as e:
77
+ yield render_trace_markdown(trace) + f"\n\n⚠️ **Error:** {e}", metrics_summary(trace)
78
+
79
+ with gr.Blocks(title=title) as demo:
80
+ gr.Markdown(f"# {title}\n\n{description}")
81
+ with gr.Row():
82
+ key = api_key_input()
83
+ model = model_selector()
84
+ inp = gr.Textbox(label=input_label, placeholder=input_placeholder, value=example)
85
+ btn = gr.Button("Run agent", variant="primary")
86
+ trace_out = gr.Markdown()
87
+ metrics_out = gr.Markdown()
88
+ btn.click(_handler, inputs=[key, model, inp], outputs=[trace_out, metrics_out])
89
+ return demo
90
+
91
+
92
+ def _truncate(text: str, limit: int = 60) -> str:
93
+ text = text.replace("\n", " ")
94
+ return text if len(text) <= limit else text[: limit - 1] + "…"
95
+
96
+
97
+ def render_trace_table(trace: Trace) -> str:
98
+ header = (
99
+ "| # | Step | Tokens | Cost | Latency | Content |\n"
100
+ "|---|------|-------|------|---------|---------|"
101
+ )
102
+ rows = [
103
+ f"| {i + 1} | {s.kind} | {s.tokens} | ${s.cost_usd:.4f}"
104
+ f" | {s.latency_ms} ms | {_truncate(s.content)} |"
105
+ for i, s in enumerate(trace.steps)
106
+ ]
107
+ return "\n".join([header, *rows])
108
+
109
+
110
+ def cost_breakdown(trace: Trace) -> str:
111
+ by_kind: dict[str, float] = {}
112
+ for s in trace.steps:
113
+ by_kind[s.kind] = by_kind.get(s.kind, 0.0) + s.cost_usd
114
+ lines = [f"- **{kind}**: ${cost:.4f}" for kind, cost in by_kind.items()]
115
+ lines.append(f"- **total**: ${trace.total_cost():.4f}")
116
+ return "\n".join(lines)
agent.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import time
3
+ from collections.abc import Iterator
4
+
5
+ from _core.llm import LLMClient
6
+ from _core.models import estimate_cost
7
+ from _core.tools import ToolRegistry
8
+ from _core.tracer import Step
9
+
10
+ SYSTEM_PROMPT = (
11
+ "You are a ReAct agent. Reason step by step about the user's question. "
12
+ "Use a tool when you need external information or computation. "
13
+ "When you can answer directly, respond with the final answer and do NOT call a tool."
14
+ )
15
+
16
+
17
+ class ReActAgent:
18
+ def __init__(self, llm: LLMClient, tools: ToolRegistry, max_steps: int = 6):
19
+ self.llm = llm
20
+ self.tools = tools
21
+ self.max_steps = max_steps
22
+
23
+ def run(self, question: str) -> Iterator[Step]:
24
+ messages: list[dict] = [
25
+ {"role": "system", "content": SYSTEM_PROMPT},
26
+ {"role": "user", "content": question},
27
+ ]
28
+ for _ in range(self.max_steps):
29
+ start = time.monotonic()
30
+ resp = self.llm.chat(messages, tools=self.tools.to_openai_schema())
31
+ latency = int((time.monotonic() - start) * 1000)
32
+ cost = estimate_cost(self.llm.model, resp.prompt_tokens, resp.completion_tokens)
33
+ step_tokens = resp.prompt_tokens + resp.completion_tokens
34
+
35
+ if resp.tool_calls:
36
+ messages.append(
37
+ {
38
+ "role": "assistant",
39
+ "content": resp.content or "",
40
+ "tool_calls": [
41
+ {
42
+ "id": tc["id"],
43
+ "type": "function",
44
+ "function": {"name": tc["name"], "arguments": tc["arguments"]},
45
+ }
46
+ for tc in resp.tool_calls
47
+ ],
48
+ }
49
+ )
50
+ if resp.content:
51
+ yield Step(
52
+ kind="thought",
53
+ content=resp.content,
54
+ tokens=step_tokens,
55
+ cost_usd=cost,
56
+ latency_ms=latency,
57
+ )
58
+ for tc in resp.tool_calls:
59
+ yield Step(kind="action", content=f"{tc['name']}({tc['arguments']})")
60
+ try:
61
+ args = json.loads(tc["arguments"]) if tc["arguments"] else {}
62
+ except json.JSONDecodeError as e:
63
+ # Thread the error back as an observation so the model can
64
+ # recover, rather than aborting the whole run.
65
+ result = f"Error: invalid tool arguments (not valid JSON): {e}"
66
+ else:
67
+ result = self.tools.execute(tc["name"], args)
68
+ yield Step(kind="observation", content=result)
69
+ messages.append({"role": "tool", "tool_call_id": tc["id"], "content": result})
70
+ continue
71
+
72
+ yield Step(
73
+ kind="final",
74
+ content=resp.content or "",
75
+ tokens=step_tokens,
76
+ cost_usd=cost,
77
+ latency_ms=latency,
78
+ )
79
+ return
80
+
81
+ yield Step(kind="final", content="Reached max steps without a final answer.")
app.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from _core.llm import LLMClient
2
+ from _core.tools import ToolRegistry, make_calculator, make_web_search
3
+ from _core.ui import build_agent_app
4
+ from agent import ReActAgent
5
+
6
+
7
+ def run_fn(llm: LLMClient, user_input: str):
8
+ tools = ToolRegistry()
9
+ tools.register(make_calculator())
10
+ tools.register(make_web_search())
11
+ return ReActAgent(llm=llm, tools=tools).run(user_input)
12
+
13
+
14
+ demo = build_agent_app(
15
+ title="ReAct from scratch",
16
+ description=(
17
+ "The Reasoning + Acting loop, built from first principles. The agent "
18
+ "interleaves thinking, tool calls, and observations. Bring your own "
19
+ "OpenRouter key — it stays in your browser session."
20
+ ),
21
+ input_label="Question",
22
+ input_placeholder="What is 24 * 17? And who won the 2022 FIFA World Cup?",
23
+ run_fn=run_fn,
24
+ example="What is 24 * 17?",
25
+ )
26
+
27
+ if __name__ == "__main__":
28
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ gradio>=4.44,<5
2
+ huggingface_hub>=0.25,<1.0
3
+ openai>=1.40
4
+ ddgs>=6.0