This tutorial begins by creating a meta-reasoning system that determines its own thinking process before even starting to do so. We design a system to evaluate complexity and choose between fast heuristics or deep chain of thought reasoning. Then, it adapts in real-time. We can understand, by examining the components, how an agent intelligently regulates its cognitive effort to balance accuracy and speed, as well as follow a strategy aligned with a problem’s characteristics. We can then see the transition from reactive to strategic thinking. See the FULL CODE NOTEBOOK.
Import Re
import time
Random Import
Typing imports Dict, Lists, Tuples, Literal
Import dataclasses and fields
@dataclass
CLASS QUERYAnalysis
query: str
Complexity: Literal["simple", "medium", "complex"]
strategy: Literal["fast", "cot", "tool"]
Confidence: floating
Reasoning:
Execution_time : float = 0.
Success: bool = True
class MetaReasoningController:
def __init__(self):
Self-query_history : List[QueryAnalysis] = []
self.patterns = were)',
def analyze_query(self, query: str) -> QueryAnalysis:
query_lower = query.lower()
has_math = bool(re.search(self.patterns['math'], query_lower))
needs_search = bool(re.search(self.patterns['search'], query_lower))
is_creative = bool(re.search(self.patterns['creative'], query_lower))
is_logical = bool(re.search(self.patterns['logical'], query_lower))
is_simple = bool(re.search(self.patterns['simple_fact'], query_lower))
word_count = len(query.split())
has_multiple_parts="?" in query[:-1] or ';' in query
if you have_math
Complexity "medium"
strategy = "tool"
Reasoning = "Math detected - using calculator tool for accuracy"
Confidence = 0.09
Elif needs_search
Complexity "medium"
strategy = "tool"
Reasoning = "Current/dynamic info - needs search tool"
Confidence = 0,85
Elif word_count and is_simple 30:
Complexity = "complex"
strategy = "cot"
Reasoning = "Complex reasoning required - using chain-of-thought"
Confidence = 0.8
Elif is_creative
Complexity "medium"
strategy = "cot"
Reasoning = "Creative task - chain-of-thought for idea generation"
Confidence = 0,75
else:
Complexity "medium"
strategy = "cot"
Reasoning = "Unclear complexity - defaulting to chain-of-thought"
Confidence = 0.6
Return QueryAnalysis. (query complexity, strategy confidence reasoning, & more)
The core structure is what allows our agent to analyse incoming queries. We decide how to classify the complexity of a query, identify patterns and determine our reasoning strategy. While we construct this foundation, the brain determines our thinking before we respond. Take a look at the FULL CODE NOTEBOOK.
class FastHeuristicEngine:
def __init__(self):
self.knowledge_base = {
Paris is the capital city of France.
Madrid, the capital city of Spain
"Speed of Light": 299,792,458 metres per second
'boiling point of water': '100°C or 212°F at sea level',
}
def answer(self, query: str) -> str:
q = query.lower()
for k, v in self.knowledge_base.items():
if k in q:
The return of f"Answer: {v}"
If you see a 'hello in Q' or a 'hi in Q':
Return to the Homepage "Hello! How can I help you?"
You can return to your original language by clicking here. "Fast heuristic: No direct match found."
class ChainOfThoughtEngine:
def answer(self, query: str) -> str:
s = []
s.append("Step 1: Understanding the question")
s.append(f" → The query asks about: {query[:50]}...")
s.append("nStep 2: Breaking down the problem")
if 'why' in query.lower():
s.append(" → This is a causal question requiring explanation")
s.append(" → Need to identify causes and effects")
elif 'how' in query.lower():
s.append(" → This is a procedural question")
s.append(" → Need to outline steps or mechanisms")
else:
s.append(" → Analyzing key concepts and relationships")
s.append("nStep 3: Synthesizing answer")
s.append(" → Combining insights from reasoning steps")
s.append("nStep 4: Final answer")
s.append(" → [Detailed response based on reasoning chain]")
You can return to your original language by clicking here. "n".join(s)
class ToolExecutor:
def calculate(self, expression: str) -> float:
M = re.search (r'(d+.?d*)s*([+-*/])s*(d+.?d*)', expression)
If m
A, Op, B = M.Groups()
A, B = float (a), float (b)ops =
ops = {
'+': lambda: x+y
'-': Lambda x and y:
'*': lambda x, y: x * y,
'/': lambda x, y: x / y if y != 0 else float('inf'),
}
return ops[op](a, b)
Return None
def search(self, query: str) -> str:
The return of f"[Simulated search results for: {query}]"
def execute(self, query: str, tool_type: str) -> str:
if tool_type== "calculator":
r = self.calculate(query)
If r is Not None:
The return of f"Calculator result: {r}"
Return to the Homepage "Could not parse mathematical expression"
If tool_type >= "search":
Search self.
You can return to your original language by clicking here. "Tool execution completed"
Engines are developed that perform thinking. We develop a heuristic engine that is fast for quick lookups. A chain-of thought engine performs deeper reasoning. And we create tool functions to compute or search. We prepare the agent for switching between modes of intelligence as we build these components. Click here to see the FULL CODE NOTEBOOK.
Class MetaReasoningAgent
def __init__(self):
self.controller = MetaReasoningController()
self.fast_engine = FastHeuristicEngine()
Self.cot_engine = chainOfThoughtengine()
self.tool_executor = ToolExecutor()
self.stats = {
'fast': {'count': 0, 'total_time': 0},
'cot': {'count': 0, 'total_time': 0},
'tool': {'count': 0, 'total_time': 0},
}
def process_query(self, query: str, verbose: bool = True) -> str:
if verbose:
print("n" + "="*60)
print(f"QUERY: {query}")
print("="*60)
t0 = time.time()
analysis = self.controller.analyze_query(query)
if verbose:
print(f"n🧠 META-REASONING:")
print(f" Complexity: {analysis.complexity}")
print(f" Strategy: {analysis.strategy.upper()}")
print(f" Confidence: {analysis.confidence:.2%}")
print(f" Reasoning: {analysis.reasoning}")
print(f"n⚡ EXECUTING {analysis.strategy.upper()} STRATEGY...n")
If strategy == "fast":
resp = self.fast_engine.answer(query)
Analysis.strategy == "cot":
resp = self.cot_engine.answer(query)
Analysis.Strategy == "tool":
if re.search(self.controller.patterns['math'], query.lower()):
resp = self.tool_executor.execute(query, "calculator")
else:
resp = self.tool_executor.execute(query, "search")
dt = time.time() - t0
analysis.execution_time = dt
self.stats[analysis.strategy]['count'] += 1
self.stats[analysis.strategy]['total_time'] += dt
self.controller.query_history.append(analysis)
if verbose:
print(resp)
print(f"n⏱️ Execution time: {dt:.4f}s")
Return to resp
def show_stats(self):
print("n" + "="*60)
print("AGENT PERFORMANCE STATISTICS")
print("="*60)
For s, d on self.stats.items():
if d['count'] > 0:
avg = d['total_time'] The /d['count']
print(f"n{s.upper()} Strategy:")
print(f" Queries processed: {d['count']}")
print(f" Average time: {avg:.4f}s")
print("n" + "="*60)
We combine all the components into one agent. We control the flow of meta-reasoning, execution and performance. Our agent is deciding, adapting, and reasoning in real time as we run the system. See the FULL CODE NOTEBOOK.
def run_tutorial():
print("""
METAREASONING AGENT Tutorial
"When Should I Think Hard vs Answer Fast?"
The agent shows:
1. Rapid vs. deep reasoning
2. Cognitive strategy: Choosing the right one
3. Adaptive intelligence
""")
MetaReasoningAgent = agent()
test_queries = [
"What is the capital of France?",
"Calculate 156 * 23",
"Why do birds migrate south for winter?",
"What is the latest news today?",
"Hello!",
"If all humans need oxygen and John is human, what can we conclude?",
]
Test_queries for Q:
agent.process_query(q, verbose=True)
time.sleep(0.5)
agent.show_stats()
print("nTutorial complete!")
print("• Meta-reasoning chooses how to think")
print("• Different queries need different strategies")
print("• Smart agents adapt reasoning dynamicallyn")
To demonstrate the abilities of this agent, we built a demonstration runner. Watch as the agent selects its strategies and responds to our queries. We get to experience adaptive reasoning in action as we work with the system. Click here to see the FULL CODE NOTEBOOK.
If __name__ is equal to "__main__":
run_tutorial()
Initialize the tutorial using a main block. The demonstration is run and we can see the complete meta-reasoning system in action. While we are executing this we finish the journey of a design into a fully functional adaptive agent.
As a conclusion, we can see that building a meta reasoning agent allows us move away from fixed patterns of responses towards adaptive intelligence. The agent is observed analyzing each query and selecting the best reasoning mode. It then executes this efficiently, while monitoring its performance. Through the design and experimentation of these components, practical insights are gained into how agents with advanced capabilities can optimize their effort, self-regulate and achieve better outcomes.
Click here to find out more FULL CODE NOTEBOOK. Check out our GitHub Page for Tutorials, Codes and Notebooks. Also, feel free to follow us on Twitter Join our Facebook group! 100k+ ML SubReddit Subscribe Now our Newsletter. Wait! Are you using Telegram? now you can join us on telegram as well.
Asif Razzaq serves as the CEO at Marktechpost Media Inc. As an entrepreneur, Asif has a passion for harnessing Artificial Intelligence to benefit society. Marktechpost is his latest venture, a media platform that focuses on Artificial Intelligence. It is known for providing in-depth news coverage about machine learning, deep learning, and other topics. The content is technically accurate and easy to understand by an audience of all backgrounds. This platform has over 2,000,000 monthly views which shows its popularity.

