Implement AI Agent in Python
Implement AI Agent in Python
Before diving into the code, let's establish a clear understanding; you can imagine an AI Agent asan intelligent program with a brain and limbs.
- Brain (Core): One that canunderstand, reason, and make decisionsModels (such as Large Language Models LLM). It is responsible for processing information and making plans.
- Perception (Input): The Agent obtains external information through its senses, such as user instructions, database query results, web page content, sensor data, etc.
- Action (Output): The Agent influences the external world through its limbs, for example, calling a function, sending an email, outputting text on the screen, controlling a robotic arm, etc.
- Goal: All actions of the Agent revolve around a clearGoalExpand, for example: Check the weather in Beijing tomorrow for me.
Its core workflow is a classicPerception-Thinking-Actionloop, as shown in the figure below:

Simple test case
Original prompt (Chinese, left untranslated)
agent-demo/
agent.py # 主实现(下面给出)
tools.py # 工具实现(可单独文件)
memory.py # 简单记忆实现(可单独文件)
README.md
Example
"""
agent.py - Minimal AI Agent prototype (can run directly)
Description:
- The LLM part is simulated with a very simple "rule responder"; replace LLMInterface.generate(...) when actually integrating with an LLM.
- Components included: LLM abstraction, Brain (parsing/decision-making), Planner, Tool Registry, Memory, Executor
"""
from
typing
import
Any
,
Dict
,
List
,
Callable
import
time
-----------------------------
Memory (very lightweight)
-----------------------------
class
Memory:
def
init
(
self
)
:
self
.
short
=
{
}
Current session context
self
.
long
=
{
}
Long-term preferences/contacts, etc.
def
get_short
(
self
,
k
,
default
=
None
)
:
return
self
.
short
.
get
(
k
,
default
)
def
set_short
(
self
,
k
,
v
)
:
self
.
short
[
k
]
=
v
def
get_long
(
self
,
k
,
default
=
None
)
:
return
self
.
long
.
get
(
k
,
default
)
def
set_long
(
self
,
k
,
v
)
:
self
.
long
[
k
]
=
v
-----------------------------
LLM Abstraction (Replacement Point)
-----------------------------
class
LLMInterface:
def
generate
(
self
,
prompt:
str
)
str
:
"""
This provides a very simple rule-based simulated responder.
In actual use: replace it with the calling code for OpenAI/other models to return the model text.
"""
Minimal parsing example: identify whether to judge "rain"
if
"Is it raining"
in
prompt
or
"raining"
in
prompt:
return
"Please check the weather first; if it is raining, please generate a reminder and send it to the target contact."
if
"generate reminder"
in
prompt:
return
"Please remind Xiao Wang: it will rain in Beijing tomorrow, please bring an umbrella."
return
"I understand."
-----------------------------
Tool registration and simulation tools
-----------------------------
class
ToolRegistry:
def
init
(
self
)
:
self
.
tools
: Dict
[
str
,
Callable
[
...
,
Any
]
]
=
{
}
def
register
(
self
,
name:
str
,
fn: Callable
[
...
,
Any
]
)
:
self
.
tools
[
name
]
=
fn
def
call
(
self
,
name:
str
,
*args
,
**kwargs
)
:
if
name
not
in
self
.
tools
:
raise
ValueError
(
f
"Tool not registered: {name}"
)
return
self
.
tools
[
name
]
(
*args
,
**kwargs
)
Simulation tool: Weather query (will call weather API in real scenario)
def
mock_weather_api
(
city:
str
,
date:
str
)
Dict
[
str
,
Any
]
:
Simple rule: if city contains "Beijing" and date contains "tomorrow", return the rainy example
if
"Beijing"
in
city
and
"tomorrow"
in
date:
return
{
"city"
: city
,
"date"
: date
,
"cond"
:
"rain"
,
"precip_mm"
:
5
}
return
{
"city"
: city
,
"date"
: date
,
"cond"
:
"clear"
,
"precip_mm"
:
0
}
Simulation tool: Send message (in a real scenario, it will call SMS/email/WeCom, etc.)
def
mock_send_message
(
contact:
str
,
message:
str
)
bool
:
(
f
"[Send message] to={contact} message={message}"
)
return
True
Simulation tool: Simple search (illustration)
def
mock_search
(
query:
str
)
str
:
return
f
Simulated search results: A summary of information about{query}.
-----------------------------
Planner / Executor
-----------------------------
class
SimplePlanner:
def
plan
(
self
,
goal:
str
)
List
[
Dict
[
str
,
Any
]
]
:
"""
Decompose the goal into a list of steps (a very simplified implementation)
Each step includes: action (tool name or internal action), params
"""
steps
=
[
]
Example: If the prompt contains "weather", generate two steps: check weather, judge and possibly send a reminder
if
"weather"
in
goal
or
"raining"
in
goal:
steps.
append
(
{
"action"
:
"query_weather"
,
"params"
:
{
"city"
:
"Beijing"
,
"date"
:
"tomorrow"
}
}
)
steps.
append
(
{
"action"
:
"decide_and_notify"
,
"params"
:
{
"contact_name"
:
"Xiao Wang"
}
}
)
else
:
steps.
append
(
{
"action"
:
"search"
,
"params"
:
{
"query"
: goal
}
}
)
return
steps
class
Executor:
def
init
(
self
,
tools: ToolRegistry
,
memory: Memory
,
llm: LLMInterface
)
:
self
.
tools
=
tools
self
.
memory
=
memory
self
.
llm
=
llm
def
run_step
(
self
,
step: Dict
[
str
,
Any
]
)
:
action
=
step
[
"action"
]
params
=
step.
get
(
"params"
,
{
}
)
if
action
==
"query_weather"
:
res
=
self
.
tools
.
call
(
"weather"
,
params
[
"city"
]
,
params
[
"date"
]
)
self
.
memory
.
set_short
(
"last_weather"
,
res
)
return
res
if
action
==
"decide_and_notify"
:
weather
=
self
.
memory
.
get_short
(
"last_weather"
,
{
}
)
Simple rule decision
if
weather.
get
(
"cond"
)
==
"rain"
:
Let LLM generate reminder text (example)
prompt
=
f
"Based on weather information: {weather}, generate a reminder for {params['contact_name']}."
reminder
=
self
.
llm
.
generate
(
prompt
)
Retrieve contact information from long-term memory
contact
=
self
.
memory
.
get_long
(
params
[
"contact_name"
]
)
or
"13800000000"
ok
=
self
.
tools
.
call
(
"send_message"
,
contact
,
reminder
)
return
{
"notified"
: ok
,
"message"
: reminder
}
else
:
return
{
"notified"
:
False
,
"reason"
:
"Weather is clear"
}
if
action
==
"search"
:
return
self
.
tools
.
call
(
"search"
,
params
[
"query"
]
)
raise
ValueError
(
f
"Unknown action: {action}"
)
-----------------------------
Agent Body
-----------------------------
class
SimpleAgent:
def
init
(
self
)
:
self
.
memory
=
Memory
(
)
self
.
tools
=
ToolRegistry
(
)
self
.
llm
=
LLMInterface
(
)
self
.
planner
=
SimplePlanner
(
)
self
.
executor
=
Executor
(
self
.
tools
,
self
.
memory
,
self
.
llm
)
Register default tools
self
.
tools
.
register
(
"weather"
,
mock_weather_api
)
self
.
tools
.
register
(
"send_message"
,
mock_send_message
)
self
.
tools
.
register
(
"search"
,
mock_search
)
Assume that Xiao Wang's contact information is stored in the long-term memory
self
.
memory
.
set_long
(
"Xiao Wang"
,
"13911112222"
)
def
handle
(
self
,
user_prompt:
str
)
:
1) Brain parsing (abstracted by LLM)
intent
=
self
.
llm
.
generate
(
user_prompt
)
2) Planning
steps
=
self
.
planner
.
plan
(
user_prompt
)
3) Step-by-step execution
results
=
[
]
for
step
in
steps:
r
=
self
.
executor
.
run_step
(
step
)
results.
append
(
{
"step"
: step
,
"result"
: r
}
)
4) Output merging
return
{
"intent"
: intent
,
"steps"
: results
}
-----------------------------
Running example
-----------------------------
if
name
==
"main"
:
agent
=
SimpleAgent
(
)
task
=
"Check tomorrow's weather in Beijing, and if it rains, help me write a reminder and send it to Xiao Wang."
out
=
agent.
handle
(
task
)
import
json
(
json.
dumps
(
out
,
ensure_ascii
=
False
,
indent
=
2
)
)
Description:
- LLM Abstraction:
LLMInterface.generate()This is a replaceable point. You can replace this with code that interfaces with OpenAI, Claude, or a local LLM. - Planner: Responsible for breaking down natural language goals into ordered steps. Beginners can use rules or templates; advanced users can use LLM to output steps and parse them into actions.
- Tools: Each tool is an independent function, uniformly registered to
ToolRegistry. In real projects, this might be HTTP requests, SDK calls, database read/write, etc. - Memory: Distinguishes between short-term and long-term. Short-term is used for intermediate results of the current task, and long-term is used for contacts, preferences, etc.
- Executor: Maps steps to tool calls and handles return values, failure, and retry logic.
Build Your First AI Agent: Task Planning Assistant
We will build aTask Planning Assistant. Its goal is to automatically decompose a complex task given by the user (e.g., "I want to travel") into a series of ordered, executable specific steps.
The directory structure is as follows:

Step 1: Build the Intelligent Brain
The Agent's brain requires reasoning capabilities. We will use OpenAI's GPT model (via API call) as our Agent's brain.
You need to prepare an OpenAI API key, or you can use a DeepSeek API key, which is compatible.
This chapter's test examples use DeepSeek's API key, which we can apply for first.https://platform.deepseek.com/api_keysWe can also directly use the Bailian and Volcengine Ark Coding Plan package:
.https://www.runoob.com/claude-code/coding-plan.htmlFirst, install the necessary libraries:
You can use the following code to test successful execution:
pip3 install openai
Instance
import
import
os
from
openai
import
OpenAI
DEEPSEEK_API_KEY
=
"sk-xxxxxxx"
Set the key you applied for here
DEEPSEEK_API_URL
=
"https://api.deepseek.com/v1"
client
=
OpenAI
(
api_key
=
DEEPSEEK_API_KEY
,
base_url
=
DEEPSEEK_API_URL
)
response
=
client.
chat
.
completions
.
create
(
model
=
"deepseek-v4-flash"
,
messages
=
[
{
"role"
:
"system"
,
"content"
:
"You are a helpful assistant"
}
,
{
"role"
:
"user"
,
"content"
:
"Hello"
}
,
]
,
stream
=
False
)
(
response.
choices
[
0
]
.
message
.
content
)
If the installation and configuration are successful, the following content will be outputted:
Hello! How can I assist you today?
Then, let's create the simplest brain module:
brain.py file code
brain.py
from
openai
import
OpenAI
import
os
DEEPSEEK_API_KEY
=
"sk-xxxxxxx"
Set the key you applied for here
DEEPSEEK_API_URL
=
"https://api.deepseek.com/v1"
client
=
OpenAI
(
api_key
=
DEEPSEEK_API_KEY
,
base_url
=
DEEPSEEK_API_URL
)
class
AgentBrain:
"""The brain of the Agent, responsible for thinking and decision-making"""
def
init
(
self
,
model
=
"deepseek-v4-flash"
)
:
self
.
model
=
model
def
think
(
self
,
prompt
)
:
Core thinking function: receives a prompt and returns the model's thinking result
try
:
Use the client to call the Chat Completions API (v1.x version syntax)
response
=
client.
chat
.
completions
.
create
(
model
=
self
.
model
,
messages
=
[
{
"role"
:
"user"
,
"content"
: prompt
}
]
,
temperature
=
0.5
,
Control creativity, lower is more focused
max_tokens
=
500
Control response length
)
Extract the text content returned by the model (v1.x version attribute path change)
reasoning
=
response.
choices
[
0
]
.
message
.
content
return
reasoning.
strip
(
)
except
Exception
as
e:
return
f
"Thinking process error: {e}"
Simple test to see if the brain is working
if
name
==
"main"
:
brain
=
AgentBrain
(
)
test_prompt
=
"Hello, please briefly introduce yourself."
(
"Test question:"
,
test_prompt
)
(
"Brain response:"
,
brain.
think
(
test_prompt
)
)
Execute the above code, the output will be approximately as follows:
Original prompt (Chinese, left untranslated)
测试提问: 你好,请简单介绍一下你自己。
大脑回复: 你好!我是DeepSeek,由深度求索公司创造的AI助手,很高兴认识你!😊
Let me introduce myself briefly:
My features:
Completely free: Currently there are no paid plans, you can use it with peace of mind.
**Knowledge Rich**: Knowledge cutoff is July 2024, covering various fields.
Strong conversational ability: Supports 128K context, enabling long and in-depth conversations
Code analysis:
- We created a
AgentBrainclass to encapsulate interaction with the LLM. thinkThe method is the core; it receives a stringprompt(prompt) and sends it to the GPT API.temperatureThe parameter is important: setting it to 0.5 allows the Agent to balance creativity and stability, which is suitable for planning tasks.- Finally, it returns the text generated by the model, which is the result of the Agent's thinking.
Step two: defining hands and feet: tools and actions
The Agent needs execution capabilities. We define several simple tools (functions) for it to be able to take action.
tools.py file code
tools.py
import
datetime
class
AgentTools:
"Set of tools that the Agent can use"
@
staticmethod
def
search_web
(
query
)
:
"""Simulate network search tool (this is a simulation)"""
mock_results
=
{
"Travel Destination Recommendations"
:
"Paris, Tokyo, Maldives, Lijiang Yunnan..."
,
"Beijing Weather"
:
"Tomorrow will be sunny, temperature 15-25°C, light breeze."
,
"Python Tutorial"
:
"Recommend websites like Beginner Tutorial."
}
for
key
,
value
in
mock_results.
items
(
)
:
if
key
in
query:
return
f
"[Web Search] Results for '{query}': {value}"
return
f
"[Web search] No explicit information found for '{query}'."
@
staticmethod
def
make_schedule
(
steps
)
:
"""Schedule planning tool"""
schedule
=
Generated schedule plan:
for
i
,
step
in
enumerate
(
steps
,
1
)
:
schedule +
=
f
"{i}. {step}\n"
return
schedule
@
staticmethod
def
get_current_time
(
)
:
"""Get current time tool"""
now
=
datetime
.
datetime
.
now
(
)
return
f
"[System time] Now is: {now.strftime('%Y-%m-%d %H:%M:%S')}"
@
staticmethod
def
calculate
(
expression
)
:
"""Simple calculator tool (secure version, compatibility issues fixed)"""
try
:
1. Strictly filter illegal characters (only allow numbers, basic operators, parentheses, spaces)
allowed_chars
=
set
(
"0123456789+-*/(). "
)
if
not
all
(
c
in
allowed_chars
for
c
in
expression
)
:
return
"[Calculator] Expression contains illegal characters, calculation rejected."
2. Simplify security checks: remove error-prone ast.walk logic and use basic syntax checking
First replace spaces to avoid empty expressions
clean_expr
=
expression.
strip
(
)
.
replace
(
" "
,
""
)
if
not
clean_expr:
return
"[Calculator] Expression cannot be empty."
3. Securely execute computations (restrict built-in functions, only retain basic arithmetic)
Custom secure global environment, only allowing basic mathematical operations
safe_globals
=
{
'builtins'
:
{
}
,
'pow'
:
pow
,
'abs'
:
abs
}
Using eval but strictly limiting the environment and filtering illegal characters significantly reduces the risk
result
=
eval
(
clean_expr
,
safe_globals
)
return
f
"[Calculator] {expression} = {result}"
except
ZeroDivisionError
:
return
"[Calculator] Error: Divisor cannot be zero."
except
SyntaxError
:
return
"[Calculator] Expression syntax error (e.g., mismatched parentheses, operator error)."
except
Exception
as
e:
return
f
"[Calculator] Calculation error: {str(e)}"
Test tools
if
name
==
"main"
:
(
AgentTools.
search_web
(
"Beijing weather"
)
)
(
AgentTools.
get_current_time
(
)
)
(
AgentTools.
calculate
(
"3 + 5 * 2"
)
)
Normal calculation
(
AgentTools.
calculate
(
"10 / 0"
)
)
Division by zero error
(
AgentTools.
calculate
(
"import('os').system('ls')
)
)
Illegal character filtering
Code parsing:
- Each
@staticmethodDefines a tool that an Agent can call. search_webCurrently simulated; real scenarios require integration with actual search APIs.make_scheduleUsed to format a list of tasks into a plan.- Important security notice:
calculateFunctions in the toolseval()are extremely dangerous in a real product and must be replaced or completely removed using a safer method (such asast.literal_eval). This is only for demonstration of how the Agent calls functions.
Step 3: Assemble the Agent: Implement the core loop
Now, we will assemble the brain and the tools, and implement the core decision loop. We will design a simple rule: let the brain decide which tool to use based on the task.
Example
agent.py
from
brain
import
AgentBrain
from
tools
import
AgentTools
class
SimpleAgent:
"""A simple task planning AI Agent"""
def
init
(
self
)
:
self
.
brain
=
AgentBrain
(
)
Static utility classes do not need to be instantiated
self
.
tools
=
AgentTools
Define the list of tools known to the Agent and their descriptions for prompting the brain
self
.
tool_descriptions
=
"""
You can use the following tools:
1. Search tool: Use when you need to get the latest or unknown information, for example, 'search Beijing weather'.
2. Planning tool: Use when you need to organize multiple steps into a plan, for example, 'create plan [step1, step2]'.
3. Time tool: Use when you need to know the current time, the command is 'get time'.
4. Calculation tool: Use when you need to perform mathematical calculations, for example, 'calculate 3+5*2'.
"""
def
run
(
self
,
user_task
)
:
"""Main loop for running the Agent"""
(
f
"🎯 User task: {user_task}"
)
(
"="
40
)
Step 1: Perception and Initial Thinking
initial_prompt
=
f
"""
Your role is a task planning assistant.
{self.tool_descriptions}
The user's task is: {user_task}
Please answer strictly according to the following fixed format, do not add extra content:
Thought: [Briefly analyze what the task requires]
Tool: [Select the name of the tool to be used, or write 'None' if none is suitable]
Instruction: [Specific instruction content to be sent to the tool]
"""
initial_response
=
self
.
brain
.
think
(
initial_prompt
)
(
"🧠 Initial thought result:"
)
(
initial_response
)
(
"-"
20
)
Step two: Parse the thinking results and extract tools and instructions (robustness optimization)
lines
=
[
line.
strip
(
)
for
line
in
initial_response.
split
(
'\n'
)
if
line.
strip
(
)
]
tool_to_use
=
"None"
tool_instruction
=
""
for
line
in
lines:
if
line.
startswith
(
"Thinking:"
)
:
continue
Skip thought line
elif
line.
startswith
(
"Tool:"
)
:
tool_to_use
=
line.
replace
(
"Tool:"
,
""
)
.
strip
(
)
elif
line.
startswith
(
"Instruction:"
)
:
tool_instruction
=
line.
replace
(
"Instruction:"
,
""
)
.
strip
(
)
Step three: Execute action
result
=
self
._use_tool
(
tool_to_use
,
tool_instruction
)
(
"🛠️ Execution result:"
)
(
result
)
(
"="
40
)
Step four: Integrate results and provide feedback to the user
final_prompt
=
f
"""
User's original task: {user_task}
You have thought and used tools.
Thought process: {initial_response}
Tool execution result: {result}
Now, please generate a complete final response to the user, providing a directly helpful answer or plan in a natural and friendly tone.
"""
final_response
=
self
.
brain
.
think
(
final_prompt
)
(
"💡 Final reply to the user:"
)
(
final_response
)
return
final_response
def
_use_tool
(
self
,
tool_name
,
instruction
)
:
"""Call the specific tool function based on the tool name"""
Unified tool name matching (case/extra space compatible)
tool_name
=
tool_name.
strip
(
)
if
tool_name
==
"Search tool"
:
return
self
.
tools
.
search_web
(
instruction
)
elif
tool_name
==
"Planning tool"
:
Supports Chinese and English commas and parentheses, handles empty instructions
if
not
instruction:
return
"[Plan tool] No plan steps provided, cannot generate schedule."
Remove parentheses and split steps (compatible with []/()/{} brackets)
clean_instr
=
instruction.
strip
(
)
.
strip
(
)
Supports splitting by both Chinese and English commas
steps
=
[
s.
strip
(
)
for
s
in
clean_instr.
replace
(
','
,
','
)
.
split
(
,
)
if
s.
strip
(
)
]
return
self
.
tools
.
make_schedule
(
steps
)
elif
tool_name
==
"Time Tool"
:
return
self
.
tools
.
get_current_time
(
)
elif
tool_name
==
"Calculation Tool"
:
return
self
.
tools
.
calculate
(
instruction
)
elif
tool_name
==
"None"
:
return
"[System] No need to use tools, just answer the user directly."
else
:
return
f
"[System] Unknown tool: {tool_name}, cannot execute."
Run our Agent!
if
name
==
"main"
:
(
"🤖 Starting SimpleAgent..."
)
my_agent
=
SimpleAgent
(
)
Test several different tasks
test_tasks
=
[
"I want to travel, help me plan what I need to prepare"
,
"What time is it now?"
,
"Calculate 15 squared plus one-third of 20"
,
]
for
task
in
test_tasks:
my_agent.
run
(
task
)
(
"\n"
"#"
50
"\n"
)
Execute code, output similar to the following:
Original prompt (Chinese, left untranslated)
启动 SimpleAgent...
用户任务: 我想去旅行,帮我规划一下需要准备什么
========================================
Initial thought results:
思考:用户需要规划旅行前的准备工作。这是一个通用任务,不需要最新信息或计算,但需要将多个准备步骤整理成一个清晰的计划。
工具:计划工具
指令:制定计划 [1. 确定目的地和旅行时间,2. 预订交通票(机票/火车票)和住宿,3. 准备旅行证件(身份证、护照、签证等),4. 安排行程和景点门票,5. 打包行李(衣物、洗漱用品、药品、充电器等),6. 安排家中事务(宠物、植物、邮件等),7. 兑换货币或准备支付方式,8. 购买旅行保险]
--------------------
执行结果:
...
Code parsing and execution flow:
- Initialization: The Agent creates its own brain (
AgentBrain) and toolbox (AgentTools). - Receive task:
runMethod starts, receivinguser_task(e.g., "I want to travel"). - Thinking phase: Combines the task and tool descriptions into
initial_prompt, and sends it to the brain. The text returned by the brain includes the "tool" it selected and the "instruction" for the tool. - Action phase:
_use_toolThe function calls the corresponding tool function based on the brain's selection and returns the result. - Feedback and Summary: Sends the original task, thinking process, and action results back to the brain to generate a user-friendly final response.
When you run this program, you will see how the Agent analyzes the task step by step, selects tools, executes, and provides an answer.
Practice Exercise: Upgrade Your Agent
You already have a working AI Agent! But this is just the beginning. Try completing the following exercises to make it more powerful:
-
Exercise One: Add Memory Functionality
SimpleAgentAdd aself.conversation_history = []list to the class. Each time it is called, not only the current prompt is sent, but the previous conversation history is also sent as context. After execution, add the new conversation turn (user input, AI thought, tool result) to the history list.brain.thinkAt this time, not only is the current prompt sent, but the previous conversation history is also sent as context. After execution, the new dialogue turn (user input, AI thought, tool result) is added to the history list.-
Exercise Two: Implement automatic tool selection
{"thought": "…", "tool": "…", "instruction": "…"}. Then usejson.loads()to parse it in the code to improve stability and accuracy.-
Exercise Three: Add a new tool
AgentToolsaddtodo_list = []and two new methods:add_todo(item)andshow_todos(). Tell the brain about the existence of this new tool in the tool description and update_use_toolHow to call it.Summary and Outlook
Congratulations! You have successfully built an AI Agent with basicperception-thought-actionloop. Let's review the key points:
- Core Concepts: AI Agent = Brain (LLM) + Perception + Action + Goal.
- Key implementations:
This is just the tip of the iceberg in the AI Agent world. Industrial-grade frameworks such asLangChain,AutoGenprovide more powerful features like tool integration, memory management, and multi-Agent collaboration. To explore further, we suggest you: