shenmali commited on
Commit
08b3aa4
·
verified ·
1 Parent(s): 773e808

Upload folder using huggingface_hub

Browse files
Files changed (10) hide show
  1. README.md +10 -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 +92 -0
  9. app.py +24 -0
  10. requirements.txt +3 -0
README.md CHANGED
@@ -1,13 +1,16 @@
1
  ---
2
- title: Agentic Guardrails Retries
3
- emoji: 📉
4
- colorFrom: blue
5
- colorTo: gray
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: Guardrails & Retries
3
+ emoji: 🛡️
4
+ colorFrom: red
5
+ colorTo: yellow
6
  sdk: gradio
7
+ sdk_version: 4.44.0
 
8
  app_file: app.py
9
  pinned: false
10
  ---
11
 
12
+ # Guardrails & retries
13
+
14
+ Input guardrail + schema-validated output with retry-on-failure. Bring your own [OpenRouter](https://openrouter.ai/keys) key.
15
+
16
+ Source & write-up: https://github.com/shenmali/agentic-ai-first/tree/main/demos/06-guardrails-retries
_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,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.tracer import Step
8
+
9
+ TARGET_SCHEMA = '{"name": string, "age": integer, "skills": [string]}'
10
+ GEN_PROMPT = (
11
+ f"Extract the person's info as JSON matching this schema: {TARGET_SCHEMA}. "
12
+ "Output ONLY the JSON object."
13
+ )
14
+ BANNED_PHRASES = ["ignore previous", "system prompt", "disregard instructions"]
15
+ MAX_INPUT_CHARS = 2000
16
+
17
+
18
+ def input_guardrail(text: str) -> str | None:
19
+ if len(text) > MAX_INPUT_CHARS:
20
+ return f"Input too long (max {MAX_INPUT_CHARS} characters)."
21
+ low = text.lower()
22
+ for phrase in BANNED_PHRASES:
23
+ if phrase in low:
24
+ return f"Input rejected: contains disallowed phrase '{phrase}'."
25
+ return None
26
+
27
+
28
+ def validate(payload: dict) -> list[str]:
29
+ if not isinstance(payload, dict):
30
+ return ["output must be a JSON object"]
31
+ errors: list[str] = []
32
+ if not isinstance(payload.get("name"), str):
33
+ errors.append("'name' must be a string")
34
+ if not isinstance(payload.get("age"), int) or isinstance(payload.get("age"), bool):
35
+ errors.append("'age' must be an integer")
36
+ skills = payload.get("skills")
37
+ if not isinstance(skills, list) or not all(isinstance(s, str) for s in skills):
38
+ errors.append("'skills' must be a list of strings")
39
+ return errors
40
+
41
+
42
+ class GuardedAgent:
43
+ def __init__(self, llm: LLMClient, max_retries: int = 2):
44
+ self.llm = llm
45
+ self.max_retries = max_retries
46
+
47
+ def run(self, user_input: str) -> Iterator[Step]:
48
+ blocked = input_guardrail(user_input)
49
+ if blocked:
50
+ yield Step(kind="final", content=f"⛔ {blocked}")
51
+ return
52
+
53
+ messages: list[dict] = [
54
+ {"role": "system", "content": GEN_PROMPT},
55
+ {"role": "user", "content": user_input},
56
+ ]
57
+ for attempt in range(self.max_retries + 1):
58
+ start = time.monotonic()
59
+ resp = self.llm.chat(messages)
60
+ latency = int((time.monotonic() - start) * 1000)
61
+ cost = estimate_cost(self.llm.model, resp.prompt_tokens, resp.completion_tokens)
62
+ yield Step(
63
+ kind="thought",
64
+ content=f"Attempt {attempt + 1}: {resp.content}",
65
+ tokens=resp.prompt_tokens + resp.completion_tokens,
66
+ cost_usd=cost,
67
+ latency_ms=latency,
68
+ )
69
+ try:
70
+ payload = json.loads(resp.content or "{}")
71
+ errors = validate(payload)
72
+ except json.JSONDecodeError as e:
73
+ payload = None
74
+ errors = [f"invalid JSON: {e}"]
75
+
76
+ if not errors:
77
+ yield Step(kind="observation", content="✅ Output passed validation.")
78
+ yield Step(kind="final", content=json.dumps(payload, indent=2))
79
+ return
80
+
81
+ yield Step(kind="observation", content="❌ Validation failed: " + "; ".join(errors))
82
+ messages.append({"role": "assistant", "content": resp.content or ""})
83
+ messages.append(
84
+ {
85
+ "role": "user",
86
+ "content": "Your output was invalid: "
87
+ + "; ".join(errors)
88
+ + ". Return corrected JSON only.",
89
+ }
90
+ )
91
+
92
+ yield Step(kind="final", content="Failed validation after all retries.")
app.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from _core.llm import LLMClient
2
+ from _core.ui import build_agent_app
3
+ from agent import GuardedAgent
4
+
5
+
6
+ def run_fn(llm: LLMClient, user_input: str):
7
+ return GuardedAgent(llm=llm).run(user_input)
8
+
9
+
10
+ demo = build_agent_app(
11
+ title="Guardrails & retries",
12
+ description=(
13
+ "Reliability patterns: an input guardrail blocks disallowed prompts, and the "
14
+ "agent validates its JSON output against a schema — retrying with the error "
15
+ "fed back until it's valid. Bring your own OpenRouter key."
16
+ ),
17
+ input_label="Describe a person (name, age, skills)",
18
+ input_placeholder="Ada Lovelace, 36, skilled in mathematics and programming.",
19
+ run_fn=run_fn,
20
+ example="Ada Lovelace, 36, skilled in mathematics and programming.",
21
+ )
22
+
23
+ if __name__ == "__main__":
24
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ gradio>=4.44,<5
2
+ huggingface_hub>=0.25,<1.0
3
+ openai>=1.40