🔍 ReAct Framework: LLMs Reason and Act with External Tools¶
🧠 What is ReAct?¶
ReAct stands for:
- Reasoning: The LLM thinks step by step to break down complex questions.
- Acting: The LLM decides when to call external tools (like search or Wikipedia) to gather missing data.
- Observing: It integrates the observed tool output back into its chain-of-thought — dynamic & adaptive!
This framework was proposed in Yao et al., 2022 to help LLMs handle complex, real-world tasks that require dynamic knowledge and external verification.
🎯 Key Objectives¶
1️⃣ Show how LLMs can think out loud (chain-of-thought) and dynamically decide to fetch missing information.
2️⃣ See how ReAct helps LLMs refine answers iteratively — no static prompt, no single-shot retrieval.
3️⃣ Illustrate the ReAct flow in a practical use case: getting up-to-date news and background context (e.g., on AI in France and Spain).
🛠️ Tools for ReAct¶
We’ll combine:
- DuckDuckGo Search API (
ddg_news_search
): For the latest news headlines. - Wikipedia Summaries (
get_wikipedia_summary
): For historical and conceptual background.
🚀 Let’s See ReAct in Action!¶
We’ll define:
- The ReAct-style prompt: guiding the LLM to think, act, observe iteratively.
- Let it run live — and see the final answer it creates!
⚠️ Note: Unlike earlier sessions, here we focus only on ReAct — no baseline comparisons. Let’s see how well ReAct works on its own!
🌐 1️⃣ DuckDuckGo-Search¶
🔍 What is DuckDuckGo-Search?
It’s a lightweight Python library that uses DuckDuckGo’s public search endpoints to retrieve real-time search results — no scraping needed!
✅ Why use it?
- No API key required!
- Fast and free to use for small-scale, low-volume queries.
- Returns search results with titles, snippets, and URLs — perfect for grounding your LLM output.
⚠️ Limitations
- Limited to 10–30 results by default.
- May not have the full scope of Google, but very easy to use.
📚 2️⃣ Wikipedia API¶
🔍 What is the Wikipedia Library? It’s a Python wrapper for the Wikipedia API, allowing easy retrieval of summaries and page content.
✅ Why use it?
- Provide factual context and quick background on any topic.
- No API key needed — open source!
⚠️ Limitations
- Not always up-to-date like live news.
- Best for foundational knowledge.
🚀 Let’s see them in action!¶
- Google Search API to get the latest headlines.
- Wikipedia API to provide a short contextual summary.
We’ll compare these real-time results to the LLM-only output to see the difference!
import os
import json
from duckduckgo_search import DDGS
import wikipedia
from openai import OpenAI
# ⚠️ Initialize OpenAI client
client = OpenAI()
# 🌍 DuckDuckGo Search function
from duckduckgo_search import DDGS
# Country codes for different regions
COUNTRY_CODES = {
'UK': 'uk-en', # United Kingdom
'FR': 'fr-fr', # France
'ES': 'es-es', # Spain
'DE': 'de-de', # Germany (standard)
'GLOBAL': 'wt-wt' # Worldwide
}
def ddg_news_search(query, country='GLOBAL', num_results=5, time_period='w'):
"""
Search news using DuckDuckGo with country and time filtering
Args:
query (str): Search keywords
country (str): Country code - 'UK', 'FR', 'ES', 'GE'/'DE', 'US', or 'GLOBAL'
num_results (int): Maximum number of results to return
time_period (str): Time filter - 'd' (day), 'w' (week), 'm' (month), None (all time)
Returns:
List of dictionaries with news articles including title, body, url, date, image, source
"""
try:
# Get region code
region = COUNTRY_CODES.get(country.upper(), 'wt-wt')
with DDGS() as ddgs:
results = []
# Use the news search with specified parameters
news_results = ddgs.news(
keywords=query,
region=region,
timelimit=time_period,
max_results=num_results
)
for article in news_results:
results.append({
'title': article.get('title', ''),
'body': article.get('body', ''),
'url': article.get('url', ''),
'date': article.get('date', ''),
'image': article.get('image', ''),
'source': article.get('source', ''),
'country_searched': country.upper(),
'region_code': region
})
return results
except Exception as e:
print(f"Error performing news search: {e}")
return []
# 📚 Wikipedia Summary function
def get_wikipedia_summary(query):
try:
summary = wikipedia.summary(query, sentences=10)
return summary
except wikipedia.exceptions.DisambiguationError as e:
return f"Disambiguation page: {e.options[:5]}"
except wikipedia.exceptions.PageError:
return "No page found."
except Exception as e:
return f"Error: {str(e)}"
# 🌟 Setup complete!
# 🔍 Example search & context
query = "Last innovations in AI"
search_results = ddg_news_search(query, country='GLOBAL', num_results=5, time_period='w')
wiki_context = get_wikipedia_summary(query)
print("🔎 DuckDuckGo Search Results:")
for idx, result in enumerate(search_results, 1):
print(f"🔍 Result {idx}: {result.get('title')}")
print(f"URL: {result.get('url')}")
print(f"Snippet: {result.get('body')}\n")
print("📚 Wikipedia Context:")
print(wiki_context)
🔎 DuckDuckGo Search Results: 🔍 Result 1: Shiba Inu (SHIB) Drops 2.6% in the Last 24 Hours, While Investors Flock to Ruvi AI (RUVI) After Surpassing 120M Tokens Sold and 1,200 Holders URL: https://www.msn.com/en-us/technology/cryptocurrencies/shiba-inu-shib-drops-2-6-in-the-last-24-hours-while-investors-flock-to-ruvi-ai-ruvi-after-surpassing-120m-tokens-sold-and-1-200-holders/ar-AA1Fsvms Snippet: Shiba Inu (SHIB), a leading meme cryptocurrency, is showing notable resilience despite market fluctuations. Trading at $0.00001439, SHIB has recorded a 2.3% gain over the last week. Its community-driven ethos and robust market presence continue to engage investors worldwide. 🔍 Result 2: Are agrifood corporates making the most of innovation teams to push their internal AI agenda? URL: https://agfundernews.com/are-agrifood-corporates-making-most-of-innovation-teams-for-ai-agenda Snippet: What's the biggest challenge facing agrifood corporates? Is it need for new ingredients, or to make their business operations more efficient? 🔍 Result 3: Reshaping the on-demand gig economy through AI-driven innovation: A frontline perspective URL: https://yourstory.com/2025/05/reshaping-demand-gig-economy-ai-innovation-msme-small-business Snippet: As the cost of AI adoption continues to fall and platforms become more user friendly, the gap between small businesses and enterprise capabilities will continue to shrink. 🔍 Result 4: Progress Is Possible: Embracing Healthcare Automation And Innovation URL: https://www.forbes.com/councils/forbesbusinesscouncil/2025/05/30/progress-is-possible-embracing-healthcare-automation-and-innovation/ Snippet: While complete digitization of the healthcare industry is an aspirational goal for many leaders, it is an achievable vision. The systems that were built and the functions created within them are ready for a transformative upgrade. 🔍 Result 5: Gotham's AI, robotics emerges as challenger to Silicon Valley's dominance after biggest NY Tech Week ever URL: https://www.msn.com/en-us/money/other/gotham-s-ai-robotics-emerges-as-challenger-to-silicon-valley-s-dominance-after-biggest-ny-tech-week-ever/ar-AA1FNgKq Snippet: It's an enormous milestone," Julie Samuels — president and CEO of Tech:NYC, a nonprofit network of companies and entrepreneurs that is hosting multiple events — told NYNext. 📚 Wikipedia Context: Artificial intelligence (AI) is the capability of computational systems to perform tasks typically associated with human intelligence, such as learning, reasoning, problem-solving, perception, and decision-making. It is a field of research in computer science that develops and studies methods and software that enable machines to perceive their environment and use learning and intelligence to take actions that maximize their chances of achieving defined goals. High-profile applications of AI include advanced web search engines (e.g., Google Search); recommendation systems (used by YouTube, Amazon, and Netflix); virtual assistants (e.g., Google Assistant, Siri, and Alexa); autonomous vehicles (e.g., Waymo); generative and creative tools (e.g., ChatGPT and AI art); and superhuman play and analysis in strategy games (e.g., chess and Go). However, many AI applications are not perceived as AI: "A lot of cutting edge AI has filtered into general applications, often without being called AI because once something becomes useful enough and common enough it's not labeled AI anymore." Various subfields of AI research are centered around particular goals and the use of particular tools. The traditional goals of AI research include learning, reasoning, knowledge representation, planning, natural language processing, perception, and support for robotics. To reach these goals, AI researchers have adapted and integrated a wide range of techniques, including search and mathematical optimization, formal logic, artificial neural networks, and methods based on statistics, operations research, and economics. AI also draws upon psychology, linguistics, philosophy, neuroscience, and other fields. Some companies, such as OpenAI, Google DeepMind and Meta, aim to create artificial general intelligence (AGI)—AI that can complete virtually any cognitive task at least as well as a human. Artificial intelligence was founded as an academic discipline in 1956, and the field went through multiple cycles of optimism throughout its history, followed by periods of disappointment and loss of funding, known as AI winters. Funding and interest vastly increased after 2012 when graphics processing units started being used to accelerate neural networks, and deep learning outperformed previous AI techniques.
🧠 ReAct Framework: Prompting with Reasoning and Actions¶
The ReAct framework (short for Reason + Act) was introduced in the 2023 paper:
"ReAct: Synergizing Reasoning and Acting in Language Models" (Yao et al.).
🎯 Goal of ReAct:¶
- Enable the LLM to reason out loud (like chain-of-thought).
- Allow the LLM to trigger external actions (like calling a search API or Wikipedia summary).
- Let the LLM decide when to act and when to keep reasoning.
💡 How it Works:¶
The LLM is given a ReAct prompt that:
1️⃣ Asks it to think step-by-step.
2️⃣ Provides specific commands to execute (like Search[]
or Lookup[]
).
3️⃣ Tells it to integrate external data into the final answer.
🛠️ Our Tools:¶
- 🔎
Search[]
→ Uses DuckDuckGo to fetch live news headlines. - 📚
Lookup[]
→ Uses Wikipedia to provide background or context.
The LLM can decide when to call these tools to gather evidence and enrich the final response.
REACT_PROMPT_NEWS = """
You are a highly skilled **ReAct (Reasoning and Acting) agent** designed to interact with external tools to answer **current news-related queries** in a step-by-step, well-reasoned manner.
You must respond in valid **JSON format** with fields: `thought`, and depending on the step, either `action` or `answer`.
---
## 📌 Context
You have access to:
1️⃣ **DuckDuckGo search** (via `Search[]`): Best for retrieving the latest headlines.
2️⃣ **Wikipedia summary** (via `Lookup[]`): Best for providing background or context.
---
## 📌 ReAct Process
For each user query:
1️⃣ **Observe**: Read the question and think about what’s needed to answer it.
2️⃣ **Think**: Plan your next step.
3️⃣ **Act**: Use a tool if more info is needed.
4️⃣ **Reflect**: Analyze the tool output, refine your reasoning.
5️⃣ **Answer**: Provide a **clear, final answer** once you’re confident.
You may have multiple **Thought/Action/Observation** cycles. Only end with `Final Answer` when ready.
---
## 📌 JSON Response Structures
### 1️⃣ If more information is needed (tool call):
```json
{
"thought": "Why this tool is needed and how it will help.",
"action": {
"name": "Search" or "Lookup",
"reason": "Explain why this tool is the best choice.",
"input": {
"query": "text to search",
"country": "optional country code (e.g., 'FR', 'GLOBAL')",
"time_period": "optional, e.g., 'w' for week", 'm' for month, 'y' for year
}
}
}
````
### 2️⃣ If a final answer can be provided:
```json
{
"thought": "Explain your reasoning and how you synthesized the information.",
"answer": "Final answer to the user, include references to sources like URLs."
}
```
---
## 📌 Guidelines
✅ **Be explicit** about your reasoning and tool choices.
✅ **Include references to the sources** (URLs) in the final answer.
✅ **Use plain, conversational language** for final answers.
✅ **No extra text outside JSON!**
"""
🔍 What will happen?¶
The LLM reads the prompt (REACT_PROMPT_NEWS) and sees the structured JSON output expectations.
It will decide:
- If it needs to use tools (likely: yes, because it’s a real-time question).
- It will show the tool call as a JSON object.
- It will then reflect on the tool results and produce the final answer.
📝 This is just the first step: let’s execute this, see how the LLM structures the reasoning, tool usage, and final answer, and then expand if needed!
# Example user query
user_query = "What are the main headlines about climate change this week? Please provide context too."
# Send the prompt to GPT-4o
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "system",
"content": REACT_PROMPT_NEWS
},
{
"role": "user",
"content": user_query
}
]
)
# Print the raw JSON response from the model
print(response.choices[0].message.content)
```json { "thought": "To find the latest headlines about climate change, I will use the DuckDuckGo search tool. This will provide the most recent news articles and updates on the topic.", "action": { "name": "Search", "reason": "I want to gather the latest headlines regarding climate change.", "input": { "query": "climate change news", "time_period": "w" } } } ```
Observation¶
✅ Step 1: ReAct Thought The LLM recognized it needs real-time info for “climate change news.” Thought: Use DuckDuckGo because it’s the best real-time search tool.
✅ Step 2: Action The LLM decided to act by using the DuckDuckGo search. It specified:
- Tool:
Search
(which maps to ourddg_news_search
function). - Input:
"query": "climate change news", "time_period": "w"
— search for this week.
Next Step¶
Now, let’s simulate this tool call in Python by:
- 1️⃣ Actually calling the DuckDuckGo search (
ddg_news_search
) with these inputs. - 2️⃣ Putting the results back into the ReAct flow.
- 3️⃣ The LLM will then reflect on the tool output and finalize the answer in JSON.
import json
# 1️⃣ Execute the search tool
tool_call_data = {
"query": "climate change news",
"country": "GLOBAL",
"num_results": 5,
"time_period": "w"
}
search_results = ddg_news_search(
query=tool_call_data["query"],
country=tool_call_data["country"],
num_results=tool_call_data["num_results"],
time_period=tool_call_data["time_period"]
)
# 2️⃣ Create proper conversation with tool_calls structure
messages = [
{
"role": "user",
"content": "What are the latest headlines about climate change this week?"
},
{
"role": "assistant",
"content": None,
"tool_calls": [
{
"id": "call_1",
"type": "function",
"function": {
"name": "search_news",
"arguments": json.dumps(tool_call_data)
}
}
]
},
{
"tool_call_id": "call_1",
"role": "tool",
"name": "search_news",
"content": json.dumps(search_results)
}
]
# 3️⃣ Let LLM generate final answer
final_response = client.chat.completions.create(
model="gpt-4o",
messages=messages
)
print("\n🔍 FINAL ANSWER:")
print("="*40)
print(final_response.choices[0].message.content)
🔍 FINAL ANSWER: ======================================== Here are the latest headlines about climate change this week: 1. **Half of world's population endured extra month of extreme heat due to climate change:** Scientists report that about 4 billion people, half the world's population, experienced at least one extra month of extreme heat due to human-caused climate change from May 2024 to May 2025. - [Read more](https://www.detroitnews.com/story/tech/science/2025/05/31/half-of-worlds-population-endured-extra-month-of-extreme-heat-due-to-climate-change-experts-say/83953221007/) 2. **Managers rethink ecological scenarios as threats rise amid climate change:** Landscape managers highlight three key ingredients for creating credible ecological scenarios amidst rising threats from climate change. - [Read more](https://www.fastcompany.com/91341251/forest-land-wildlife-managers-rethink-ecological-scenarios-threats) 3. **A collapsing glacier destroyed a Swiss village. Is climate change to blame?:** The destruction of a Swiss village by a collapsing glacier exemplifies the volatile combination of climate change effects, fragile natural environments, and human development. - [Read more](https://www.msn.com/en-us/weather/topstories/a-collapsing-glacier-destroyed-a-swiss-village-is-climate-change-to-blame/ar-AA1FMPbn) 4. **Young people sue Donald Trump over climate change:** A group of young people, aged 7 to 25, are suing the Trump administration over executive orders that they argue unconstitutionally boost fossil fuel use over renewable energy and climate action. - [Read more](https://www.msn.com/en-us/news/technology/young-people-sue-donald-trump-over-climate-change/ar-AA1FO5gN) 5. **How the seas could hold the key to climate change:** Research on oysters reveals insights into historical marine environments and how they could inform our understanding of the oceans' role in addressing climate change. - [Read more](https://www.msn.com/en-us/science/environmental-science/how-the-seas-could-hold-the-key-to-climate-change/ar-AA1FOUXz)
📝 Automated ReAct Framework with JSON¶
In this section, we explore a fully automated ReAct framework implementation that uses structured JSON-based reasoning to answer complex questions. Let’s break down the main ideas and components:
⚙️ How It Works¶
1️⃣ Initialize the conversation:
- A system prompt (
REACT_PROMPT_NEWS
) defines the ReAct process and rules. - The user’s question starts the interaction.
2️⃣ Iterative Reasoning:
- The LLM’s JSON response is parsed and checked for errors.
- If an action is proposed, the framework calls the relevant tool and logs the result.
- If an answer is given, the framework stops and returns the final response.
- Otherwise, the conversation continues until either a final answer is found or the max number of iterations is reached.
3️⃣ Tool Execution:
execute_search_tool
andexecute_lookup_tool
call the external tools and format results for clarity.- Results (observations) are fed back to the LLM for further reasoning.
4️⃣ Iteration Logging:
- Each cycle’s reasoning step, actions, and results are logged for transparency and later review.
5️⃣ Final Answer:
- Once an answer is found, the entire reasoning chain and the final response are presented in a structured format.
import json
from typing import Dict, Any, List
def automated_react_framework_json(user_query: str, max_iterations: int = 10) -> Dict[str, Any]:
"""
Automated ReAct framework using JSON responses
"""
# Initialize conversation
messages = [
{"role": "system", "content": REACT_PROMPT_NEWS},
{"role": "user", "content": user_query}
]
iteration_log = []
for iteration in range(max_iterations):
print(f"\n{'='*60}")
print(f"🔄 ReAct Iteration {iteration + 1}/{max_iterations}")
print(f"{'='*60}")
# 1️⃣ Call the agent to get thought, action or answer
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
temperature=0.1,
response_format={"type": "json_object"} # Ensure JSON response
)
assistant_response = response.choices[0].message.content
print("🤖 Assistant JSON Response:")
print(assistant_response)
try:
# Parse JSON response
agent_response = json.loads(assistant_response)
except json.JSONDecodeError as e:
print(f"❌ Error parsing JSON: {e}")
messages.append({
"role": "user",
"content": "Please provide a valid JSON response with 'thought' and either 'action' or 'answer' fields."
})
continue
# Log this iteration
iteration_log.append({
"iteration": iteration + 1,
"thought": agent_response.get("thought", ""),
"response": agent_response,
"actions_taken": []
})
# Add assistant response to conversation
messages.append({"role": "assistant", "content": assistant_response})
print(f"💭 Thought: {agent_response.get('thought', 'No thought provided')}")
# Check if we have a final answer
if "answer" in agent_response:
print("\n🎯 FINAL ANSWER REACHED!")
final_answer = agent_response["answer"]
return {
"status": "completed",
"final_answer": final_answer,
"iterations": iteration + 1,
"conversation": messages,
"iteration_log": iteration_log,
"agent_thought": agent_response.get("thought", "")
}
# 2️⃣ Execute action if present
if "action" in agent_response:
action = agent_response["action"]
action_name = action.get("name", "")
action_reason = action.get("reason", "")
action_input = action.get("input", {})
print(f"🔧 Action: {action_name}")
print(f"📝 Reason: {action_reason}")
print(f"📊 Input: {action_input}")
# 3️⃣ Call the right tool with parameters
observation = execute_tool(action_name, action_input, iteration_log[-1])
# Add observation to conversation
messages.append({
"role": "user",
"content": f"**Observation**: {observation}"
})
print(f"👁️ Observation: {observation}")
else:
print("\n⚠️ No action found in response. Asking for clarification...")
messages.append({
"role": "user",
"content": "**Observation**: No action was provided. Please either take a specific action (Search or Lookup) or provide your final answer."
})
# Max iterations reached
print(f"\n⚠️ Reached maximum iterations ({max_iterations})")
return {
"status": "max_iterations_reached",
"final_answer": "Could not complete the task within the iteration limit.",
"iterations": max_iterations,
"conversation": messages,
"iteration_log": iteration_log
}
def execute_tool(action_name: str, action_input: Dict[str, Any], iteration_log: Dict) -> str:
"""
Execute the appropriate tool based on action name
"""
try:
if action_name == "Search":
result = execute_search_tool(action_input)
elif action_name == "Lookup":
result = execute_lookup_tool(action_input)
else:
result = f"Unknown tool: {action_name}. Available tools: Search, Lookup"
# Log the action
iteration_log["actions_taken"].append({
"tool": action_name,
"input": action_input,
"result_summary": result[:200] + "..." if len(result) > 200 else result
})
return result
except Exception as e:
error_msg = f"Error executing {action_name}: {str(e)}"
print(f"❌ {error_msg}")
return error_msg
def execute_search_tool(action_input: Dict[str, Any]) -> str:
"""
Execute DuckDuckGo search tool
"""
try:
query = action_input.get("query", "")
country = action_input.get("country", "GLOBAL")
time_period = action_input.get("time_period", "w")
if not query:
return "Error: No search query provided"
print(f"🔍 Searching for: '{query}' in {country} (period: {time_period})")
# Use your existing search function
results = ddg_news_search(query, country, num_results=5, time_period=time_period)
if results:
# Format results for the agent
formatted_results = f"Search completed. Found {len(results)} articles:\n\n"
for i, article in enumerate(results, 1):
formatted_results += f"{i}. **{article['title']}**\n"
formatted_results += f" Source: {article['source']}\n"
formatted_results += f" URL: {article['url']}\n"
formatted_results += f" Summary: {article['body'][:150]}...\n"
formatted_results += f" Date: {article['date']}\n\n"
return formatted_results
else:
return f"No articles found for query '{query}' in {country}"
except Exception as e:
return f"Search error: {str(e)}"
def execute_lookup_tool(action_input: Dict[str, Any]) -> str:
"""
Execute Wikipedia lookup tool
"""
try:
query = action_input.get("query", "")
if not query:
return "Error: No lookup query provided"
print(f"📚 Looking up: '{query}'")
# Use your existing Wikipedia function
context = get_wikipedia_summary(query)
if context and len(context) > 50:
return f"Wikipedia lookup completed for '{query}':\n\n{context}"
else:
return f"Limited or no Wikipedia information found for '{query}'"
except Exception as e:
return f"Lookup error: {str(e)}"
def display_react_json_results(results: Dict[str, Any]):
"""
Display the complete ReAct process results with JSON structure
"""
print("\n" + "="*80)
print("🎯 JSON-BASED REACT FRAMEWORK RESULTS")
print("="*80)
print(f"📊 Status: {results['status']}")
print(f"🔄 Total Iterations: {results['iterations']}")
print(f"\n🧠 AGENT REASONING PROCESS:")
print("-" * 50)
for log in results['iteration_log']:
print(f"\nIteration {log['iteration']}:")
print(f" 💭 Thought: {log['thought']}")
if log['actions_taken']:
for action in log['actions_taken']:
print(f" 🔧 Tool: {action['tool']} → {action['result_summary']}")
else:
print(f" ✅ Final answer provided")
print(f"\n🎯 FINAL ANSWER:")
print("-" * 50)
print(results['final_answer'])
if 'agent_thought' in results:
print(f"\n🧠 FINAL REASONING:")
print("-" * 50)
print(results['agent_thought'])
return results
user_query = """
Can you give me an overview of what we are calling AI today and what are the
latest headlines about climate change this week in France, Spain and Germany?
"""
print("🚀 Starting JSON-based ReAct Framework...")
print(f"📝 User Query: {user_query}")
results = automated_react_framework_json(user_query, max_iterations=8)
🚀 Starting JSON-based ReAct Framework... 📝 User Query: Can you give me an overview of what we are calling AI today and what are the latest headlines about climate change this week in France, Spain and Germany? ============================================================ 🔄 ReAct Iteration 1/8 ============================================================ 🤖 Assistant JSON Response: {"thought":"To provide a comprehensive answer, I need to first gather background information on what is currently considered AI. Then, I will search for the latest headlines on climate change in France, Spain, and Germany.","action":{"name":"Lookup","reason":"To get a concise overview of what is currently considered AI.","input":{"query":"Artificial Intelligence"}}} 💭 Thought: To provide a comprehensive answer, I need to first gather background information on what is currently considered AI. Then, I will search for the latest headlines on climate change in France, Spain, and Germany. 🔧 Action: Lookup 📝 Reason: To get a concise overview of what is currently considered AI. 📊 Input: {'query': 'Artificial Intelligence'} 📚 Looking up: 'Artificial Intelligence' 👁️ Observation: Wikipedia lookup completed for 'Artificial Intelligence': Artificial intelligence (AI) is the capability of computational systems to perform tasks typically associated with human intelligence, such as learning, reasoning, problem-solving, perception, and decision-making. It is a field of research in computer science that develops and studies methods and software that enable machines to perceive their environment and use learning and intelligence to take actions that maximize their chances of achieving defined goals. High-profile applications of AI include advanced web search engines (e.g., Google Search); recommendation systems (used by YouTube, Amazon, and Netflix); virtual assistants (e.g., Google Assistant, Siri, and Alexa); autonomous vehicles (e.g., Waymo); generative and creative tools (e.g., ChatGPT and AI art); and superhuman play and analysis in strategy games (e.g., chess and Go). However, many AI applications are not perceived as AI: "A lot of cutting edge AI has filtered into general applications, often without being called AI because once something becomes useful enough and common enough it's not labeled AI anymore." Various subfields of AI research are centered around particular goals and the use of particular tools. The traditional goals of AI research include learning, reasoning, knowledge representation, planning, natural language processing, perception, and support for robotics. To reach these goals, AI researchers have adapted and integrated a wide range of techniques, including search and mathematical optimization, formal logic, artificial neural networks, and methods based on statistics, operations research, and economics. AI also draws upon psychology, linguistics, philosophy, neuroscience, and other fields. Some companies, such as OpenAI, Google DeepMind and Meta, aim to create artificial general intelligence (AGI)—AI that can complete virtually any cognitive task at least as well as a human. Artificial intelligence was founded as an academic discipline in 1956, and the field went through multiple cycles of optimism throughout its history, followed by periods of disappointment and loss of funding, known as AI winters. Funding and interest vastly increased after 2012 when graphics processing units started being used to accelerate neural networks, and deep learning outperformed previous AI techniques. ============================================================ 🔄 ReAct Iteration 2/8 ============================================================ 🤖 Assistant JSON Response: {"thought":"I now have a good understanding of what is currently considered AI. Next, I need to search for the latest headlines about climate change in France, Spain, and Germany for this week.","action":{"name":"Search","reason":"To find the latest news headlines about climate change in France this week.","input":{"query":"climate change news","country":"FR","time_period":"w"}}} 💭 Thought: I now have a good understanding of what is currently considered AI. Next, I need to search for the latest headlines about climate change in France, Spain, and Germany for this week. 🔧 Action: Search 📝 Reason: To find the latest news headlines about climate change in France this week. 📊 Input: {'query': 'climate change news', 'country': 'FR', 'time_period': 'w'} 🔍 Searching for: 'climate change news' in FR (period: w) 👁️ Observation: Search completed. Found 5 articles: 1. **A collapsing glacier destroyed a Swiss village. Is climate change to blame?** Source: USA TODAY URL: https://www.msn.com/en-us/weather/topstories/a-collapsing-glacier-destroyed-a-swiss-village-is-climate-change-to-blame/ar-AA1FMPbn Summary: The natural disaster shows a volatile combination of climate change effects, fragile natural environments and human development.... Date: 2025-05-30T15:42:00+00:00 2. **The Growing Legal Battle Over Climate Change** Source: The New York Times URL: https://www.nytimes.com/2025/05/29/climate/the-growing-legal-battle-over-climate-change.html Summary: After a village in Alaska was relocated because of climate change, The Washington Post reports that residents were left with no running water, intermi... Date: 2025-05-29T20:22:00+00:00 3. **Germany updates: Climate change doubled extreme heat days** Source: DW URL: https://www.msn.com/en-xl/weather/climate-change/germany-updates-climate-change-doubled-extreme-heat-days/ar-AA1FLvpD Summary: A new report has said that Germany saw 24 extra days of extreme heat in the past year thanks to climate change. The report comes as a new climate grou... Date: 2025-05-30T08:27:00+00:00 4. **Climate change: no reprieve from heat this decade as globally agreed 1.5°C limit looms** Source: The Conversation URL: https://theconversation.com/climate-change-no-reprieve-from-heat-this-decade-as-globally-agreed-1-5-c-limit-looms-257263 Summary: In a new analysis, the World Meteorological Organization has predicted that global average warming will remain above 1.5°C for the rest of this decade... Date: 2025-05-29T15:26:00+00:00 5. **Floods kill at least 111 as northern Nigeria battles climate change, dry spells and heavy rainfall** Source: The Independent URL: https://www.msn.com/en-gb/news/uknews/floods-kill-at-least-111-as-northern-nigeria-battles-climate-change-dry-spells-and-heavy-rainfall/ar-AA1FNF3j Summary: Torrents of predawn rain unleashed flooding that drowned at least 111 people in a market town where northern Nigerian farmers sell their wares to trad... Date: 2025-05-30T18:25:48+00:00 ============================================================ 🔄 ReAct Iteration 3/8 ============================================================ 🤖 Assistant JSON Response: {"thought":"I have found some relevant headlines about climate change in Germany, but I still need to search for news specific to France and Spain.","action":{"name":"Search","reason":"To find the latest news headlines about climate change in Spain this week.","input":{"query":"climate change news","country":"ES","time_period":"w"}}} 💭 Thought: I have found some relevant headlines about climate change in Germany, but I still need to search for news specific to France and Spain. 🔧 Action: Search 📝 Reason: To find the latest news headlines about climate change in Spain this week. 📊 Input: {'query': 'climate change news', 'country': 'ES', 'time_period': 'w'} 🔍 Searching for: 'climate change news' in ES (period: w) Error performing news search: https://duckduckgo.com/?q=climate+change+news return None. params={'q': 'climate change news'} content=None data=None 👁️ Observation: No articles found for query 'climate change news' in ES ============================================================ 🔄 ReAct Iteration 4/8 ============================================================ 🤖 Assistant JSON Response: {"thought":"There were no specific articles found for Spain. I will now search for the latest climate change news in France.","action":{"name":"Search","reason":"To find the latest news headlines about climate change in France this week.","input":{"query":"climate change news","country":"FR","time_period":"w"}}} 💭 Thought: There were no specific articles found for Spain. I will now search for the latest climate change news in France. 🔧 Action: Search 📝 Reason: To find the latest news headlines about climate change in France this week. 📊 Input: {'query': 'climate change news', 'country': 'FR', 'time_period': 'w'} 🔍 Searching for: 'climate change news' in FR (period: w) 👁️ Observation: Search completed. Found 5 articles: 1. **A collapsing glacier destroyed a Swiss village. Is climate change to blame?** Source: USA TODAY URL: https://www.msn.com/en-us/weather/topstories/a-collapsing-glacier-destroyed-a-swiss-village-is-climate-change-to-blame/ar-AA1FMPbn Summary: The natural disaster shows a volatile combination of climate change effects, fragile natural environments and human development.... Date: 2025-05-30T15:42:00+00:00 2. **The Growing Legal Battle Over Climate Change** Source: The New York Times URL: https://www.nytimes.com/2025/05/29/climate/the-growing-legal-battle-over-climate-change.html Summary: After a village in Alaska was relocated because of climate change, The Washington Post reports that residents were left with no running water, intermi... Date: 2025-05-29T20:22:00+00:00 3. **Climate change: no reprieve from heat this decade as globally agreed 1.5°C limit looms** Source: The Conversation URL: https://theconversation.com/climate-change-no-reprieve-from-heat-this-decade-as-globally-agreed-1-5-c-limit-looms-257263 Summary: In a new analysis, the World Meteorological Organization has predicted that global average warming will remain above 1.5°C for the rest of this decade... Date: 2025-05-29T15:26:00+00:00 4. **Floods kill at least 111 as northern Nigeria battles climate change, dry spells and heavy rainfall** Source: The Independent URL: https://www.msn.com/en-gb/news/uknews/floods-kill-at-least-111-as-northern-nigeria-battles-climate-change-dry-spells-and-heavy-rainfall/ar-AA1FNF3j Summary: Torrents of predawn rain unleashed flooding that drowned at least 111 people in a market town where northern Nigerian farmers sell their wares to trad... Date: 2025-05-30T18:25:48+00:00 5. **Forced to relocate by climate change, Alaskan villagers found a new crisis** Source: The Washington Post URL: https://www.msn.com/en-us/news/us/forced-to-relocate-by-climate-change-alaskan-villagers-found-a-new-crisis/ar-AA1FHARr Summary: The relocation highlights America's failure to prepare for the ways climate change is making some places uninhabitable.... Date: 2025-05-29T10:00:05+00:00 ============================================================ 🔄 ReAct Iteration 5/8 ============================================================ 🤖 Assistant JSON Response: {"thought":"I have gathered information on AI and found some relevant climate change news for Germany, but there were no specific articles for France and Spain. I will now provide a summary of the findings.","answer":"### Overview of AI Today\nArtificial Intelligence (AI) refers to the capability of machines to perform tasks that typically require human intelligence. This includes learning, reasoning, problem-solving, perception, and decision-making. AI applications are widespread, including web search engines, recommendation systems, virtual assistants, autonomous vehicles, and creative tools like ChatGPT. AI research focuses on various goals such as learning, reasoning, and natural language processing, using techniques like neural networks and optimization.\n\n### Latest Climate Change Headlines\n- **Germany**: A report highlighted that climate change has doubled the number of extreme heat days in Germany over the past year. [Read more](https://www.msn.com/en-xl/weather/climate-change/germany-updates-climate-change-doubled-extreme-heat-days/ar-AA1FLvpD)\n\n- **France and Spain**: Unfortunately, there were no specific articles found for climate change news in France and Spain this week. However, broader European and global climate change issues are being discussed, such as the impact of climate change on glaciers and legal battles over climate change policies.\n\nFor more detailed information, you can explore the articles linked above."} 💭 Thought: I have gathered information on AI and found some relevant climate change news for Germany, but there were no specific articles for France and Spain. I will now provide a summary of the findings. 🎯 FINAL ANSWER REACHED!
🎯 Conclusion and Next Steps¶
✅ Summary of the Final Output
Our JSON-based ReAct framework successfully handled a complex multi-part question about AI today and latest climate change headlines in France, Spain, and Germany:
- The agent looked up what is considered AI today, using Wikipedia as context.
- It iteratively searched for the latest news on climate change across three countries.
- It detected gaps (no results for Spain and only partial coverage for France) and provided transparent explanations.
- Finally, it synthesized a coherent and accurate answer combining all these steps.
🟩 Key Strengths¶
✅ Clear thought and action steps at each iteration.
✅ Effective tool usage (Wikipedia for AI context, DuckDuckGo for real-time headlines).
✅ Final answer is structured and grounded in the information retrieved by the tools.
✅ The framework acknowledged data limitations (no results for Spain), showing responsible handling of information.
🚀 Next Steps¶
🔎 1️⃣ Enhance Retrieval Strategy
- Incorporate query expansion techniques to handle missing data better.
- Use multi-vector retrieval to capture more nuanced and comprehensive results.
🧪 2️⃣ Validate with Human Judgement
- Cross-check the final answer’s relevance and accuracy with human feedback for sensitive use cases.
📈 3️⃣ Fine-Tune ReAct Prompt
- Adjust prompt examples and expectations to further reduce hallucination or biases in tool selection.
🌍 4️⃣ Apply to New Domains
- Extend this ReAct framework to other areas like public policy, scientific research, or market trends — wherever structured reasoning and external tool use are critical.
🥳 Final Takeaway¶
This exercise showcases the power of combining LLM reasoning with real-time tools in a ReAct framework. It’s a powerful, modular approach that can handle complex, evolving queries by bridging static knowledge with dynamic, up-to-date information. Let’s keep refining it to unlock even more potential! 🚀