Skip to main content
Takin AI Academy

Zero-Cost AI Agent Blueprint Architecture

Learn the methodologies to bypass heavy LLM API costs. Build autonomous, tool-equipped AI agents using free cloud tiers and local models.

Visual ReAct Agent Loop Flowchart

📥

1. Input Question

User Query or task

▶️
🧠

2. Thought Engine

LLM analyzes and plans

▶️
⚙️

3. Tool Execution

Web search, calculations, files

💡 The ReAct loop cycles dynamically (Thought -> Action -> Observation) until the model reaches a Final Answer. It operates entirely on free-tier APIs.

Configure Python Agent

Specify the architecture details of your agent:

tekin_agent.py
import os
import time
import google.generativeai as genai

# =====================================================================
# TAKIN ACADEMY: ZERO-COST REACT AGENT BLUEPRINT
# =====================================================================

# Setup free Gemini API Key (Get a free key from Google AI Studio)
api_key = os.getenv("GEMINI_API_KEY", "YOUR_FREE_GEMINI_API_KEY")
genai.configure(api_key=api_key)
model_name = "gemini-1.5-flash"

SYSTEM_PROMPT = """You are a smart agent operating in a ReAct loop (Thought, Action, Observation).
Your task is to answer user queries logically. You have access to:
- web_search(query): Searches the web. Input a search query string.
- calculate(expression): Solves math formulas. Example: calculate("2 + 2 * 10")

Each cycle contains:
Thought: think about what to do next.
Action: tool_name(argument) - if you need to call a tool.
Observation: result of the tool (will be fed back to you).
... (Repeat until you have the final answer)
Thought: when you know the final answer.
Final Answer: your detailed response to the user.

Your identity and role:
You are an intelligent content writer. Always use search to find latest information before drafting.

Begin!"""
# Define agent tools (Completely free, no API cost)
tools = {}

def web_search(query: str) -> str:
    """Simple web search mockup utilizing DuckDuckGo scrapers without keys."""
    try:
        import urllib.request
        from bs4 import BeautifulSoup
        import urllib.parse
        url = f"https://html.duckduckgo.com/html/?q={urllib.parse.quote(query)}"
        req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
        with urllib.request.urlopen(req) as response:
            soup = BeautifulSoup(response.read(), 'html.parser')
            results = [a.text.strip() for a in soup.find_all('a', class_='result__snippet')[:3]]
            return " | ".join(results) if results else "No results found."
    except Exception as e:
        return f"Error executing search: {str(e)}"

tools["web_search"] = web_search

def calculate(expression: str) -> str:
    """Evaluates mathematical expressions safely using Python."""
    try:
      allowed = "0123456789+-*/(). "
      if all(c in allowed for c in expression):
          return str(eval(expression))
      return "Error: Invalid characters in math formula."
    except Exception as e:
      return f"Math error: {str(e)}"

tools["calculate"] = calculate


# Define ReAct Loop execution
def run_agent(question: str):
    model = genai.GenerativeModel(model_name)
    chat = model.start_chat(history=[])
    
    prompt = f"{SYSTEM_PROMPT}\nQuestion: {question}\n"
    
    print(f"🚀 Starting ReAct Loop for: '{question}'")
    for step in range(6):
        response = chat.send_message(prompt).text
        print(f"\n[Thought]:\n{response}\n")
        
        if "Action:" in response:
            # Extract Action name and argument
            try:
                action_line = [l for l in response.split("\n") if "Action:" in l][0]
                action_val = action_line.replace("Action:", "").strip()
                tool_name = action_val.split("(")[0].strip()
                tool_arg = action_val.split("(")[1].split(")")[0].replace('"', '').replace("'", "").strip()
                
                if tool_name in tools:
                    # Execute selected tool
                    observation = tools[tool_name](tool_arg)
                    prompt = f"Observation: {observation}\n"
                else:
                    prompt = f"Observation: Tool '{tool_name}' is not defined.\n"
            except Exception as e:
                prompt = f"Observation: Error parsing Action format. Make sure to use tool_name(arg).\n"
                
        elif "Final Answer:" in response:
            # Render the final answer
            final_answer = response.split("Final Answer:")[1].strip()
            print("====================================")
            print(f"🎉 Final Result:\n{final_answer}")
            print("====================================")
            break
        else:
            break

if __name__ == "__main__":
    # Define question and run the agent loop
    test_question = "What is the latest AI gaming news?"
    run_agent(test_question)

Local Setup & Execution Guide

1. Obtain Free API Key

Go to Google AI Studio and generate a free API key for Gemini. It offers a generous free tier of up to 15 requests per minute.

2. Install Python Packages

pip install google-generativeai beautifulsoup4

Execute this package manager installation in your terminal to enable Google Generative AI and web parsing modules.

3. Execute Script

python tekin_zero_cost_agent.py

Execute the saved python script to initialize the automated ReAct reasoning loop locally on your system.