Guided project ยท Building with AI
Code an AI research assistant that uses tools (a ReAct agent)
Build an agent from scratch that decides when to search Wikipedia or use a calculator, reads the results and answers with sources.
What you'll build
A working tool-using agent with a think โ act โ observe loop, two tools, a step limit and a printed trace of every decision.
What you'll learn
- How function calling and tool use really work
- The ReAct loop: reason, act, observe, repeat
- Writing tool descriptions the model can follow
- Safety limits and tracing for agents
- Answering with sources to reduce hallucination
You'll need
Google Colab (free), a free Gemini API key and Wikipedia's free public API
Create a free account to unlock this project
The step-by-step instructions, copy-ready prompts, progress tracker and portfolio texts are for members. It's free, takes under a minute, and unlocks all guided projects.
Want to try first? These projects are open to everyone: Prompt lab and One idea, five posts.
Before you start
- Finish the first steps of the multi-agent project, or follow the same three set-up steps below.
Use any free AI chatbot (ChatGPT, Claude, Gemini or Copilot). Never paste private or confidential information.
Step by step
Get a free API key
Go to aistudio.google.com, sign in with a Google account and click Get API key โ Create API key. Treat it like a password: never paste it into a chat, a document or your code.
You should see: A long key starting with letters and numbers. Keep the tab open.
Why it matters: API keys let your code use an AI model. Anyone with your key can use your quota, so it stays secret.
Store the key safely in Colab
Open a new notebook at colab.research.google.com. Click the ๐ key icon on the left (Secrets), click Add new secret, name it GEMINI_API_KEY, paste the key as the value and switch on Notebook access.
You should see: A secret called GEMINI_API_KEY with notebook access turned on.
Connect to the model
Run this cell. It installs Google's library, loads your key from Secrets and asks the model to say hello.
Copy this code!pip install -q google-genai from google import genai from google.colab import userdata import json, re client = genai.Client(api_key=userdata.get('GEMINI_API_KEY')) MODEL = 'gemini-2.5-flash' # if this stops working, use the current Flash model name from AI Studio CALLS = {'n': 0} def ask(system, prompt, temperature=0.4): CALLS['n'] += 1 r = client.models.generate_content(model=MODEL, contents=prompt, config={'system_instruction': system, 'temperature': temperature}) return r.text def ask_json(system, prompt): text = ask(system + '\nReply with valid JSON only, no other text.', prompt, 0.2) m = re.search(r'\{.*\}|\[.*\]', text, re.S) return json.loads(m.group(0)) print(ask('You are friendly and brief.', 'Say hello to a new AI builder in one sentence.'))You should see: A short hello from the model. If you see an error about the model name, open AI Studio, copy the name of the current Flash model and put it in MODEL.
Why it matters: ask() sends a role (system instruction) and a prompt; ask_json() asks for structured output you can use in code.
Build tool 1: Wikipedia search
This tool searches Wikipedia and returns short summaries. It sends a polite name for your app, as Wikipedia asks.
Copy this codeimport requests HEADERS = {'User-Agent': 'AIFromZeroLearningProject/1.0 (educational demo)'} def wiki_search(query): r = requests.get('https://en.wikipedia.org/w/api.php', headers=HEADERS, timeout=15, params={'action': 'query', 'list': 'search', 'srsearch': query, 'format': 'json', 'srlimit': 2}) out = [] for hit in r.json()['query']['search']: title = hit['title'] s = requests.get('https://en.wikipedia.org/api/rest_v1/page/summary/' + title.replace(' ', '_'), headers=HEADERS, timeout=15).json() out.append({'title': title, 'summary': s.get('extract', '')[:600], 'url': s.get('content_urls', {}).get('desktop', {}).get('page', '')}) return out print(wiki_search('transformer machine learning')[0]['summary'][:300])You should see: A short summary of the top Wikipedia results for "transformer machine learning".
Build tool 2: a safe calculator
Language models are bad at exact maths, so we give the agent a calculator. It only accepts numbers and + โ ร รท for safety.
Copy this codedef calculator(expression): if not re.fullmatch(r'[0-9+\-*/(). ]+', expression) or '**' in expression: return 'Error: only numbers and + - * / ( ) are allowed.' return str(eval(expression, {'__builtins__': {}})) print(calculator('2500 * 500'))You should see: 1,250,000.
Why it matters: Never let an AI run any code it likes. This tool checks the input against an allow-list first.
Describe the tools to the agent
The agent only knows what you tell it. These instructions explain the tools and the exact JSON format to reply in.
Copy this codeAGENT = '''You are a research assistant. Answer the user's question using tools. Tools: - wiki_search(query): searches Wikipedia, returns titles, summaries and URLs. - calculator(expression): exact arithmetic with numbers and + - * / ( ). At every step reply with ONE JSON object: {"thought": "what you think next", "tool": "wiki_search" or "calculator", "input": "..."} or, when you have enough information: {"thought": "...", "final": "your answer", "sources": ["url", ...]} Only use facts from tool results. If the tools don't give the answer, say you don't know.''' TOOLS = {'wiki_search': wiki_search, 'calculator': calculator}You should see: No output; the agent's instructions are ready.
Why it matters: Clear tool names, short descriptions and a fixed reply format are what make tool use reliable.
Write the agent loop
This is the heart of every agent: ask the model what to do, run the tool it chose, give it the result, and repeat. MAX_STEPS stops it from looping forever.
Copy this codeMAX_STEPS = 6 def run_agent(question): history = f'Question: {question}' for step_no in range(1, MAX_STEPS + 1): move = ask_json(AGENT, history) print(f'\n๐ญ Step {step_no}:', move.get('thought', '')) if 'final' in move: print('\nโ Answer:', move['final']) print('๐ Sources:', move.get('sources', [])) return move tool = TOOLS.get(move.get('tool')) if not tool: history += '\nObservation: unknown tool, use wiki_search or calculator.' continue result = tool(move.get('input', '')) print(f'๐ง {move["tool"]}({move.get("input")})') history += f'\nAction: {json.dumps(move)}\nObservation: {json.dumps(result)[:2500]}' print('\nโ Stopped: step limit reached.')You should see: No output yet; the run_agent function is defined.
Ask a question that needs searching
Run the agent and read its trace: each thought, each tool it used and what it found.
Copy this coderun_agent('Who introduced the transformer architecture, and in which year was the paper published?')You should see: 2โ4 steps with thoughts and tool calls, then an answer with Wikipedia links.
Ask a question that needs search and maths
Now it must look something up and then calculate.
Copy this coderun_agent('How many years passed between the release of the first iPhone and the release of ChatGPT? Use the tools.')You should see: A search step, a calculator step, and an answer with the working shown.
Test the limits
Ask something the tools can't answer, and something unsafe for the calculator.
Copy this coderun_agent('What did my manager have for lunch yesterday?') print(calculator('__import__("os").listdir()'))You should see: An honest "I don't know" for the first, and an error message from the calculator for the second, not a crash.
Why it matters: Good agents admit what they don't know, and tools refuse inputs they shouldn't accept.
Brilliant work. Share it below, then pick your next project.
Level up
- Add a third tool, e.g. today's date or a currency converter, and describe it in the instructions.
- Use the model's built-in function calling instead of JSON text and compare the reliability.
- Save each trace to a file so you can review and evaluate the agent's decisions later.
Lessons behind this project
Show it off
Finished? Post about it on LinkedIn. Here's a starting point; add a screenshot and your own words.
I built an AI research agent from scratch: it decides when to search Wikipedia or use a calculator, reads the results and answers with sources, with a step limit and a full trace. Now I really understand how tool use and the ReAct loop work. Learned with AI From Zero.Add it to your portfolio
Employers love seeing what you've built. Use these ready-made texts, then add your own results and a screenshot.
1. A line for your CV or LinkedIn "Projects" section
Code an AI research assistant that uses tools (a ReAct agent): A working tool-using agent with a think โ act โ observe loop, two tools, a step limit and a printed trace of every decision. Skills: How function calling and tool use really work, The ReAct loop, Writing tool descriptions the model can follow, Safety limits and tracing for agents, Answering with sources to reduce hallucination. Tools: Google Colab (free), a free Gemini API key and Wikipedia's free public API.2. A README for GitHub
Create a free GitHub account, make a new repository, add a file called README.md and paste this in along with your notebook (File โ Download โ .ipynb).
# Code an AI research assistant that uses tools (a ReAct agent)
Build an agent from scratch that decides when to search Wikipedia or use a calculator, reads the results and answers with sources.
## What I built
A working tool-using agent with a think โ act โ observe loop, two tools, a step limit and a printed trace of every decision.
## What I learned
- How function calling and tool use really work
- The ReAct loop: reason, act, observe, repeat
- Writing tool descriptions the model can follow
- Safety limits and tracing for agents
- Answering with sources to reduce hallucination
## Tools
Google Colab (free), a free Gemini API key and Wikipedia's free public API
## How it works
1. Get a free API key
2. Store the key safely in Colab
3. Connect to the model
4. Build tool 1: Wikipedia search
5. Build tool 2: a safe calculator
6. Describe the tools to the agent
7. Write the agent loop
8. Ask a question that needs searching
9. Ask a question that needs search and maths
10. Test the limits
## Results
(Add a screenshot and 2โ3 sentences about what you found. Never include API keys or personal data.)
## Next steps
- Add a third tool, e.g. today's date or a currency converter, and describe it in the instructions.
- Use the model's built-in function calling instead of JSON text and compare the reliability.
- Save each trace to a file so you can review and evaluate the agent's decisions later.
---
Built by following the free guided project at https://learnaifromzero.com/projects/ai-research-assistant.html