AI Agent Q&A Example
AI Agent Q&A Example
In this chapter, we will build our first real AI Agent.
We will start with a simple Q&A Agent and gradually add more features.
Prepare project structure
First, create the directory runoob-ai-agent:
mkdir runoob-ai-agent
Enter the runoob-ai-agent directory and create a virtual environment using the uv command:
Original prompt (Chinese, left untranslated)
cd runoob-ai-agent
# Create a virtual environment named .venv (default)
uv venv
# Activate environment (macOS/Linux)
source .venv/bin/activate
# Activate environment (Windows)
.venv\Scripts\activate
Use uv to create and activate a virtual environment; more related content can be read at uv Tutorial.
Create the project directory structure:
runoob-ai-agent/
├── .env
├── .gitignore
├── requirements.txt
├── test_basic_agent.py
├── README.md
├── src/
│ ├── __init__.py
│ └── simple_agent.py
└── tests/
└── __init__.py

Apply for API key from Alibaba BaiLian
This chapter requires search functionality, so we use the Alibaba Qwen model because it has built-in search capabilities.
The Tongyi Qianwen model in Alibaba BaiLian supports OpenAI compatible interfaces. You only need to adjust the API Key, BASE_URL, and model name to migrate your existing OpenAI code to use the Alibaba BaiLian service.
- base_url: Replace with https://dashscope.aliyuncs.com/compatible-mode/v1
- api_key: Replace with Alibaba Cloud Bailian API Key
- model: Replace with qwen3-max
Reference address:https://help.aliyun.com/zh/model-studio/compatibility-of-openai-with-dashscope
We need to enable the Alibaba Cloud Bailian model service and obtain an API-KEY.
We can first access the Bailian model service platform with the Alibaba Cloud main account:https://bailian.console.aliyun.com/, then click the login in the upper right corner. After successful login, click the gear icon ⚙️ in the upper right corner, select API key, and copy the API key. If there is none, you can also create an API key:


Enabling Alibaba Cloud Bailian will not incur any fees; only model calls (after exceeding the free quota), model deployment, and model fine-tuning will incur corresponding charges.
Now that we need to use the API, billing is based on tokens, but fortunately, they are not expensive. We can first purchase the cheapest package: Alibaba Cloud Bailian Large Model Service Platform.
You can also directly use the Coding Plan package of Bailian and Volcengine Ark:https://www.runoob.com/claude-code/coding-plan.html.
Create the base Agent class:
Instance
src/simple_agent.py
import
os
from
typing
import
List
,
Dict
,
Any
from
openai
import
OpenAI
from
dotenv
import
load_dotenv
Load environment variables
load_dotenv
(
)
class
SimpleQAAgent:
"""Simple Q&A Agent"""
def
init
(
self
,
model:
str
=
"qwen3-max"
)
:
Set the default model to DeepSeek
"""
Initialize Agent
Args:
model: The name of the model to use, defaults to DeepSeek
"""
api_key = os.getenv("OPENAI_API_KEY")
api_key
=
"sk-xxx"
The API key you applied for
base_url
=
"https://dashscope.aliyuncs.com/compatible-mode/v1"
if
not
api_key:
raise
ValueError
(
"Please set the OPENAI_API_KEY environment variable"
)
self
.
client
=
OpenAI
(
api_key
=
api_key
,
base_url
=
base_url
)
self
.
model
=
model
self
.
conversation_history
: List
[
Dict
[
str
,
str
]
]
=
[
]
self
.
system_prompt
=
"You are a helpful AI assistant. Please answer the user's questions politely and accurately."
def
add_to_history
(
self
,
role:
str
,
content:
str
)
:
"""Add message to conversation history"""
self
.
conversation_history
.
append
(
{
"role"
: role
,
"content"
: content
}
)
Keep the history length no more than 10 turns (to prevent token overflow)
if
len
(
self
.
conversation_history
)
10
:
self
.
conversation_history
=
self
.
conversation_history
[
10
:
]
def
ask
(
self
,
question:
str
)
str
:
"""
Ask the Agent a question
Args:
question: The user's question
Returns:
The agent's response
"""
Add user question to history
self
.
add_to_history
(
"user"
,
question
)
Prepare message list
messages
=
[
{
"role"
:
"system"
,
"content"
:
self
.
system_prompt
}
]
messages.
extend
(
self
.
conversation_history
)
try
:
Call OpenAI API
response
=
self
.
client
.
chat
.
completions
.
create
(
model
=
self
.
model
,
messages
=
messages
,
temperature
=
0.7
,
max_tokens
=
500
)
Extract answer
answer
=
response.
choices
[
0
]
.
message
.
content
Add assistant response to history
self
.
add_to_history
(
"assistant"
,
answer
)
return
answer
except
Exception
as
e:
error_msg
=
f
"Error calling API: {str(e)}"
(
error_msg
)
return
error_msg
def
clear_history
(
self
)
:
"""Clear conversation history"""
self
.
conversation_history
.
clear
(
)
Create a test script to test the basic Agent:
instance
test_basic_agent.py
from
src.
simple_agent
import
SimpleQAAgent
def
test_basic_agent
(
)
:
"""Test basic Q&A Agent"""
(
"=== Test Basic Q&A Agent ==="
)
Create Agent
agent
=
SimpleQAAgent
(
)
Test Q&A
questions
=
[
"Hello, please introduce yourself."
,
"What is Python?"
,
"What is the difference between machine learning and artificial intelligence?"
]
for
question
in
questions:
(
f
"\nUser: {question}"
)
answer
=
agent.
ask
(
question
)
(
f
"Assistant: {answer}"
)
Test dialogue coherence
(
=== Test conversation coherence ===
)
agent.
clear_history
(
)
First round
q1
=
"My favorite color is blue"
a1
=
agent.
ask
(
q1
)
(
f
"User: {q1}"
)
(
f
"Assistant: {a1}"
)
Second round (should be able to remember the previous conversation)
q2
=
"What color did I just say I like the most?"
a2
=
agent.
ask
(
q2
)
(
f
"\nUser: {q2}"
)
(
f
"Assistant: {a2}"
)
(
"Test completed!"
)
if
name
==
"main"
:
test_basic_agent
(
)
Run test:
Original prompt (Chinese, left untranslated)
python test_basic_agent.py
=== 测试基础问答 Agent ===
用户: 你好,请介绍一下自己
runoob
助理: 你好!我是通义千问(Qwen),是阿里巴巴集团自主研发的超大规模语言模型。我可以帮助你回答问题、创作文字,比如写故事、写公文、写邮件、写剧本、逻辑推理、编程等等,还能表达观点,玩游戏等。如果你有任何问题或需要帮助,随时告诉我!
用户: Python是什么?
助理: 你好!Python 是一种**高级、解释型、通用的编程语言**,由荷兰程序员 **吉多·范罗苏姆(Guido van Rossum)** 于1991年首次发布。它的设计哲学强调代码的**可读性**和**简洁性**,语法清晰简洁,使得初学者也能快速上手。
...
This basic Agent has several obvious limitations:
- It can only answer knowledge in the training data
- Cannot obtain real-time information
- Cannot perform calculations
- Cannot operate external systems
This is why we need to add tools to the Agent.
Add search tool
Qwen has a built-in search function; passing the enable_search: true parameter enables internet search.
Original prompt (Chinese, left untranslated)
# 导入依赖与创建客户端...
completion = client.chat.completions.create(
# Must use a model that supports internet search
model="qwen3-max",
messages=[{"role": "user", "content": "杭州明天天气如何"}],
# Since enable_search is not a standard OpenAI parameter, it needs to be passed via extra_body when using the Python SDK (it needs to be passed as a top-level parameter when using the Node.js SDK)
extra_body={"enable_search": True}
)
Documentation:https://help.aliyun.com/zh/model-studio/web-search
Agent integrating search tool
Now we will integrate the search tool into the Agent, create the agent_with_search.py file in the src directory:
Instance
src/agent_with_search.py
import
os
from
openai
import
OpenAI
from
dotenv
import
load_dotenv
load_dotenv
(
)
class
AgentWithSearch:
"""Agent based on Qwen's built-in internet search capabilities"""
def
init
(
self
,
model:
str
=
"qwen3-max"
)
:
api_key
=
"sk-xxx"
base_url
=
"https://dashscope.aliyuncs.com/compatible-mode/v1"
if
not
api_key:
raise
ValueError
(
"Please set the OPENAI_API_KEY environment variable (DashScope Key)"
)
self
.
client
=
OpenAI
(
api_key
=
api_key
,
base_url
=
base_url
)
self
.
model
=
model
self
.
system_prompt
=
"""
You are a helpful AI assistant.
When the question involves real-time information, the latest events, or requires fact-checking,
you can obtain the latest information through web search and state in the answer that the information comes from the web.
"""
def
ask
(
self
,
question:
str
)
str
:
messages
=
[
{
"role"
:
"system"
,
"content"
:
self
.
system_prompt
}
,
{
"role"
:
"user"
,
"content"
: question
}
]
try
:
response
=
self
.
client
.
chat
.
completions
.
create
(
model
=
self
.
model
,
messages
=
messages
,
temperature
=
0.7
,
max_tokens
=
800
,
extra_body
=
{
"enable_search"
:
True
}
)
return
response.
choices
[
0
]
.
message
.
content
except
Exception
as
e:
return
f
"Error: {repr(e)}"
def
interactive_chat
(
self
)
:
(
"=== Qwen Web Search Agent ==="
)
(
"Enter quit / exit to end the conversation"
)
while
True
:
question
=
input
(
"\nYou: "
)
.
strip
(
)
if
question.
lower
(
)
in
{
"quit"
,
"exit"
}
:
break
(
"Assistant:"
,
self
.
ask
(
question
)
)
Test Search Agent
Create the file test_search_agent.py in the root directory:
Instance
test_search_agent.py
from
src.
agent_with_search
import
AgentWithSearch
def
test_search_agent
(
)
:
agent
=
AgentWithSearch
(
)
questions
=
[
"What is the weather like in Beijing today?"
,
"What is the latest technology news?"
,
"Where will the 2024 Olympics be held?"
,
What is Python?
]
for
q
in
questions:
(
f
"\nUser: {q}"
)
(
"Assistant:"
,
agent.
ask
(
q
)
[
:
300
]
,
"..."
)
if
name
==
"main"
:
test_search_agent
(
)
Run test:
Original prompt (Chinese, left untranslated)
python test_search_agent.py
用户: 今天北京的天气怎么样?
Assistant: Today is Saturday, February 7, 2026. According to the latest weather forecast, the weather in Beijing today is as follows:
- **天气状况**:多云转晴
- **气温范围**:最低气温约 **-9℃**,最高气温约 **2℃**(部分区域如海淀区记录为 **-5℃ ~ 5℃**)
- **风向风力**:白天到夜间有 **东北风1级**,部分地区午后转为 **南风转西北风,小于3级**
- **空气质量**:**37(优)**
- **穿衣建议**:建议穿棉衣、冬大衣、皮夹克、厚呢外套、羽绒服等厚重保暖衣物,并佩戴手套、帽子等防寒配件
...
