ReAct Agent: Reasoning + Acting
Implement the ReAct (Reasoning + Acting) pattern with Gemini 2.0 Flash and the Wikipedia API. The model generates Thought→Action→Observation chains to answer complex questions.
Implement a ReAct agent with two tools: Wikipedia and a safe calculator (restricted eval). Ask a question requiring both search and computation, e.g. 'How many years has the Eiffel Tower been standing as of 2025?'
Copy and adapt to your context. Text in angle brackets should be replaced.
import google.generativeai as genai
import wikipedia, re
genai.configure(api_key=GOOGLE_API_KEY)
model = genai.GenerativeModel("gemini-2.0-flash")
chat = model.start_chat(history=[])
def search(query):
try:
return wikipedia.summary(query, sentences=3)
except Exception as e:
return f"Error: {e}"
# ReAct loop
response = chat.send_message(REACT_PROMPT + "\nQuestion\n" + "How tall is Eiffel Tower?")
while "<finish>" not in response.text:
match = re.search(r"<search>(.*?)</search>", response.text)
if match:
obs = search(match.group(1))
response = chat.send_message(f"Observation {obs}")