通俗易懂理解AI 相关概念
Agent: Agent 是一个能像人一样思考、决策并自动完成任务的智能程序(代理本质上是一个在 MCP 客户端上构建的 while 循环!)。 MCP: MCP 是一个标准 API,用于暴露一组可以被连接到 LLMs 的工具。(mcp client 和 mcp server 进行交互) agent 和 mcp clien 之间进行交互 Function Call:
每个概念给出代码示例:
--- mcp 和agent的一种关系 MCP 提供类似于函数调用(tool calling)的能力,将工具封装成标准函数(包含名称、描述、参数 JSONSchema)。 LLM 可根据用户请求自动调用工具,agent 负责对接模型和 MCP 服务器,接收工具列表,并以循环方式处理用户请求,直到任务完成或对话中断。
Agent 通过 run 方法实现核心循环,自动处理工具调用、执行并将结果反馈给 LLM,直到退出条件满足。并可扩展控制流工具(如 task_complete、ask_question)便于任务结束或澄清问题。
# 简单AI Agent伪代码(聊天机器人示例)
# 1. 感知模块:获取用户输入
function get_user_input():
user_input = read_from_interface() # 从界面/终端读取文字
return user_input
# 2. 大脑模块:处理输入并生成回复
function process_input(input):
# 假设使用一个预训练模型或简单规则库
if input contains "你好":
response = "你好!有什么可以帮你的?"
else if input contains "天气":
response = query_weather_api() # 调用外部API获取天气
else:
response = "抱歉,我没听懂,能再说一遍吗?"
return response
# 3. 行动模块:执行回复
function take_action(response):
send_to_interface(response) # 将回复发送到界面/终端
# 4. 交互模块:主循环,管理用户交互
function main():
while True: # 持续运行
# 感知:获取用户输入
user_input = get_user_input()
# 停止条件
if user_input == "退出":
break
# 大脑:处理输入,生成回复
response = process_input(user_input)
# 行动:输出回复
take_action(response)
# 可选拓展:学习模块(简单示例)
function learn_from_feedback(user_input, user_feedback):
if user_feedback == "不好":
update_knowledge_base(user_input, "需要改进") # 记录问题输入
# 未来可加入模型微调或强化学习
# 启动Agent
main()说明
感知:
get_user_input模拟从界面获取用户输入。大脑:
process_input用简单条件语句模拟思考,实际可替换为AI模型(如LLM)。行动:
take_action将结果输出到界面。交互:
main循环让Agent持续与用户交互。学习(拓展):
learn_from_feedback模拟通过反馈改进,实际可加入机器学习。
拓展伪代码(复杂场景)
如果要扩展为更复杂的Agent(比如任务规划Agent),可以加以下模块:
# 拓展:任务规划Agent伪代码
function plan_task(task):
# 规划模块:分解任务
subtasks = break_down_task(task) # 拆分成小任务
for subtask in subtasks:
action = decide_action(subtask) # 为每个小任务决定行动
execute_action(action) # 执行
# 感知:从环境获取多源数据
function get_environment_data():
sensor_data = read_sensors() # 比如摄像头、麦克风
api_data = fetch_from_api() # 外部数据
return combine_data(sensor_data, api_data)
# 学习:通过经验优化
function optimize_model(experience):
update_model_weights(experience) # 使用强化学习或微调
# 主循环
function advanced_main():
while True:
data = get_environment_data()
task = analyze_data(data)
plan_task(task)
optimize_model(get_experience())