← Lesson
ReAct: Thought, Action, Observation
Joeven
Run
Reset
Python loads on first run
import json import re TOOLS = { "get_weather": lambda city: {"city": city, "sky": "rain", "temp_c": 12}, "finish": lambda answer: {"final": answer}, } def parse_react(text): thought = re.search(r"Thought:\s*(.*)", text) action = re.search(r"Action:\s*(\w+)", text) args = re.search(r"Action Input:\s*(\{.*\})", text) return { "thought": thought.group(1).strip() if thought else "", "action": action.group(1) if action else None, "args": json.loads(args.group(1)) if args else {}, } def fake_model(scratchpad): if not scratchpad: return chr(10).join([ "Thought: I should check the weather before advising.", "Action: get_weather", 'Action Input: {"city": "Paris"}', ]) obs = scratchpad[-1]["observation"] if obs.get("sky") == "rain": ans = "Take an umbrella in Paris (12C, rain)." else: ans = "No umbrella needed." return chr(10).join([ "Thought: Use the observation, not a guess.", "Action: finish", "Action Input: " + json.dumps({"answer": ans}), ]) scratchpad = [] for step in range(1, 6): parsed = parse_react(fake_model(scratchpad)) obs = TOOLS[parsed["action"]](**parsed["args"]) rec = { "thought": parsed["thought"], "action": parsed["action"], "args": parsed["args"], "observation": obs, } scratchpad.append(rec) print("step", step, rec["action"], rec["args"]) print(" obs", rec["observation"]) if parsed["action"] == "finish": break print("ANSWER", scratchpad[-1]["observation"]["final"])
Run to execute this in your browser. Nothing is sent to a server.