第11章:目标设定与监控
为了使智能体真正有效且具有目的性,它们需要的不仅仅是处理信息或使用工具的能力;它们还需要一个明确的方向感,以及一种了解自己是否真正成功的方法。这就是目标设定和监控模式发挥作用的地方。它涉及为智能体提供具体的目标去努力实现,并为他们配备跟踪进度和判断目标是否实现的方式。
目标设定与监控模式概述
想象一下规划一次旅行。你不会突然出现在目的地。你需要决定你想去哪里(目标状态),弄清楚你从哪里出发(初始状态),考虑可用的选项(交通方式、路线、预算),然后规划出一连串的步骤:预订机票、打包行李、前往机场/车站、登交通工具、到达、寻找住宿等。这个逐步的过程,通常需要考虑依赖性和约束条件,就是我们所说的智能体系统中规划的本质。
在人工智能智能体的语境中,规划通常涉及智能体接受一个高层次目标,并自主或半自主地生成一系列中间步骤或子目标。这些步骤可以依次执行,或者在一个更复杂的流程中执行,可能涉及其他模式,如工具使用、路径规划或多智能体协作。规划机制可能涉及复杂的搜索算法、逻辑推理,或者越来越多地利用大型语言模型(LLM)的能力,根据其训练数据和任务理解生成合理且有效的计划。
良好的规划能力使智能体能够应对复杂问题,而不仅仅是简单的单步查询。它使它们能够处理多方面的请求,通过重新规划来适应不断变化的情况,并协调复杂的流程。这是一个基础模式,支撑了许多高级智能体行为,将简单的反应性系统转变为能够积极朝着既定目标工作的系统。
实际应用与用例
目标设定与监控模式对于构建能够在复杂、真实世界场景中自主且可靠运行的智能体至关重要。以下是一些实际应用:
- 客户支持自动化: 智能体的目标可能是“解决客户的账单查询”。它监控对话,检查数据库条目,并使用工具调整账单。通过确认账单变更并收到积极的客户反馈来监控成功。如果问题未得到解决,则升级处理。
- 个性化学习系统:一个学习智能体的目标可能是“提高学生对代数的理解”。它监控学生在练习中的进度,调整教学材料,并跟踪性能指标,如准确率和完成时间,如果学生遇到困难,会调整其方法。
- 项目管理助手: 智能体可以负责“确保项目里程碑X在Y日期前完成”。它将监控任务状态、团队沟通和资源可用性,如果目标有风险,将标记延迟并建议纠正措施。
- 自动交易机器人:智能体的目标可能是“在风险承受范围内最大化投资组合收益。”它持续监控市场数据、当前投资组合价值以及风险指标,当条件符合其目标时执行交易,如果风险阈值被突破,则调整策略。
- 机器人与自动驾驶汽车: 自主汽车的主要目标是“安全地将乘客从A点运送到B点。”它持续监测其环境(其他车辆、行人、交通信号)、自身状态(速度、燃油)以及沿预定路线的进展,调整其驾驶行为,以安全高效地实现目标。
- 内容审核: 智能体的目标可能是“从平台X中识别并移除有害内容。”它监控传入的内容,应用分类模型,并跟踪如误报/漏报等指标,调整其过滤标准或将模糊不清的案件提升至人工审核员。
这种模式对于需要可靠运行、实现特定目标并适应动态条件的智能体至关重要,为智能自我管理提供了必要的框架。
动手代码示例
为了说明目标设定和监控模式,我们提供了一个使用LangChain和OpenAI API的示例。这个Python脚本概述了一个自主的AI智能体,该智能体被设计用于生成和优化Python代码。其核心功能是针对特定问题生成解决方案,并确保符合用户定义的质量标准。
它采用了一种“目标设定与监控”的模式,不仅仅生成一次代码,而是进入一个迭代周期,包括创作、自我评估和改进。智能体的成功由其自身AI驱动的判断来衡量,即生成的代码是否成功满足初始目标。最终输出的是一个经过打磨、注释齐全且可直接使用的Python文件,代表了这一精炼过程的成果。
依赖项:
pip install langchain_openai openai python-dotenv .env file with key in OPENAI_API_KEY
您可以通过将其想象为一个分配给项目的自主AI程序员(见图1)来最好地理解此脚本。过程开始于您向AI提供详细的项目概述,这是它需要解决的特定编码问题。
# MIT License
# Copyright (c) 2025 Mahtab Syed
# https://www.linkedin.com/in/mahtabsyed/
"""
Hands-On Code Example
- Iteration 2 - To illustrate the Goal Setting and Monitoring pattern, we have an example using LangChain and OpenAI APIs:
Objective: Build an AI Agent which can write code for a specified use case based on specified goals:
- Accepts a coding problem (use case) in code or can be as input.
- Accepts a list of goals (e.g., "simple", "tested", "handles edge cases") in code or can be input.
- Uses an LLM (like GPT-4o) to generate and refine Python code until the goals are met. (I am using max 5 iterations, this could be based on a set goal as well)
- To check if we have met our goals I am asking the LLM to judge this and answer just True or False which makes it easier to stop the iterations.
- Saves the final code in a .py file with a clean filename and a header comment.
"""
import os
import random
import re
from pathlib import Path
from langchain_openai import ChatOpenAI
from dotenv import load_dotenv, find_dotenv
# 🔐 Load environment variables
_ = load_dotenv(find_dotenv())
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
if not OPENAI_API_KEY:
raise EnvironmentError("❌ Please set the OPENAI_API_KEY environment variable.")
# ✅ Initialize OpenAI model
print("📡 Initializing OpenAI LLM (gpt-4o)...")
llm = ChatOpenAI(
model="gpt-4o",
# If you don't have access to gpt-4o use other OpenAI LLMs
temperature=0.3,
openai_api_key=OPENAI_API_KEY,
)
# --- Utility Functions ---
def generate_prompt(use_case: str, goals: list[str], previous_code: str = "", feedback: str = "") -> str:
print("📝 Constructing prompt for code generation...")
base_prompt = f""" You are an AI coding agent. Your job is to write Python code based on the following use case:
Use Case: {use_case}
Your goals are: {chr(10).join(f"- {g.strip()}" for g in goals)} """
if previous_code:
print("🔄 Adding previous code to the prompt for refinement.")
base_prompt += f"\nPreviously generated code:\n{previous_code}"
if feedback:
print("📋 Including feedback for revision.")
base_prompt += f"\nFeedback on previous version:\n{feedback}\n"
base_prompt += "\nPlease return only the revised Python code. Do not include comments or explanations outside the code."
return base_prompt
def get_code_feedback(code: str, goals: list[str]) -> str:
print("🔍 Evaluating code against the goals...")
feedback_prompt = f""" You are a Python code reviewer. A code snippet is shown below. Based on the following goals:
{chr(10).join(f"- {g.strip()}" for g in goals)} Please critique this code and identify if the goals are met. Mention if improvements are needed for clarity, simplicity, correctness, edge case handling, or test coverage.
Code: {code} """
return llm.invoke(feedback_prompt)
def goals_met(feedback_text: str, goals: list[str]) -> bool:
""" Uses the LLM to evaluate whether the goals have been met based on the feedback text.
Returns True or False (parsed from LLM output).
"""
review_prompt = f""" You are an AI reviewer. Here are the goals:
{chr(10).join(f"- {g.strip()}" for g in goals)} Here is the feedback on the code: \"\"\"
{feedback_text}
\"\"\"
Based on the feedback above, have the goals been met? Respond with only one word: True or False. """
response = llm.invoke(review_prompt).content.strip().lower()
return response == "true"
def clean_code_block(code: str) -> str:
lines = code.strip().splitlines()
if lines and lines[0].strip().startswith("```"):
lines = lines[1:]
if lines and lines[-1].strip() == "```":
lines = lines[:-1]
return "\n".join(lines).strip()
def add_comment_header(code: str, use_case: str) -> str:
comment = f"# This Python program implements the following use case:\n# {use_case.strip()}\n"
return comment + "\n" + code
def to_snake_case(text: str) -> str:
text = re.sub(r"[^a-zA-Z0-9 ]", "", text)
return re.sub(r"\\s+", "_", text.strip().lower())
def save_code_to_file(code: str, use_case: str) -> str:
print("💾 Saving final code to file...")
summary_prompt = (
f"Summarize the following use case into a single lowercase word or phrase, "
f"no more than 10 characters, suitable for a Python filename:\n\n{use_case}"
)
raw_summary = llm.invoke(summary_prompt).content.strip()
short_name = re.sub(r"[^a-zA-Z0-9_]", "", raw_summary.replace(" ", "_").lower())[:10]
random_suffix = str(random.randint(1000, 9999))
filename = f"{short_name}_{random_suffix}.py"
filepath = Path.cwd() / filename
with open(filepath, "w") as f:
f.write(code)
print(f"✅ Code saved to: {filepath}")
return str(filepath)
# --- Main Agent Function ---
def run_code_agent(use_case: str, goals_input: str, max_iterations: int = 5) -> str:
goals = [g.strip() for g in goals_input.split(",")]
print(f"\n🎯 Use Case: {use_case}")
print("🎯 Goals:")
for g in goals:
print(f" - {g}")
previous_code = ""
feedback = ""
for i in range(max_iterations):
print(f"\n=== 🔁 Iteration {i + 1} of {max_iterations} ===")
prompt = generate_prompt(use_case, goals, previous_code, feedback if isinstance(feedback, str) else feedback.content)
print("🚧 Generating code...")
code_response = llm.invoke(prompt)
raw_code = code_response.content.strip()
code = clean_code_block(raw_code)
print("\n🧾 Generated Code:\n" + "-" * 50 + f"\n{code}\n" + "-" * 50)
print("\n📤 Submitting code for feedback review...")
feedback = get_code_feedback(code, goals)
feedback_text = feedback.content.strip()
print("\n📥 Feedback Received:\n" + "-" * 50 + f"\n{feedback_text}\n" + "-" * 50)
if goals_met(feedback_text, goals):
print("✅ LLM confirms goals are met. Stopping iteration.")
break
print("🛠️ Goals not fully met. Preparing for next iteration...")
previous_code = code
final_code = add_comment_header(code, use_case)
return save_code_to_file(final_code, use_case)
# --- CLI Test Run ---
if __name__ == "__main__":
print("\n🧠 Welcome to the AI Code Generation Agent")
# Example 1
use_case_input = "Write code to find BinaryGap of a given positive integer"
goals_input = "Code simple to understand, Functionally correct, Handles comprehensive edge cases, Takes positive integer input only, prints the results with few examples"
run_code_agent(use_case_input, goals_input)
# Example 2
# use_case_input = "Write code to count the number of files in current directory and all its nested sub directories, and print the total count"
# goals_input = (
# "Code simple to understand, Functionally correct, Handles comprehensive edge cases, Ignore recommendations for performance, Ignore recommendations for test suite use like unittest or pytest"
# )
# run_code_agent(use_case_input, goals_input)
# Example 3
# use_case_input = "Write code which takes a command line input of a word doc or docx file and opens it and counts the number of words, and characters in it and prints all"
# goals_input = "Code simple to understand, Functionally correct, Handles edge cases"
# run_code_agent(use_case_input, goals_input)
除了这份简报之外,您还提供了一份严格的质量检查清单,该清单代表了最终代码必须达到的目标——例如“解决方案必须简单”、“必须功能正确”或“需要处理意外的边缘情况”等标准。

图1:目标设定与监控示例
手握这项任务,AI程序员开始工作并完成了代码的第一稿。然而,它并没有立即提交这个初始版本,而是暂停下来执行一个关键步骤:严格的自我审查。它仔细地将自己的作品与您提供的质量检查清单上的每一项进行对比,充当自己的质量保证检查员。经过这次检查后,它对自己的进度给出一个简单、公正的判断:“True”(如果工作符合所有标准)或“False”(如果未达到标准)。
如果判断结果是“False”,AI不会放弃。它会进入一个深思熟虑的修订阶段,利用自我批评的洞察力来找出弱点,并智能地重写代码。这个起草、自我审查和精炼的循环持续进行,每次迭代都旨在更接近目标。这个过程会一直重复,直到AI最终通过满足所有要求达到“True”状态,或者达到预定义的尝试次数上限,就像开发者面对截止日期一样。一旦代码通过最后的检查,脚本会将经过打磨的解决方案打包,添加有用的注释,并将其保存到一个干净的新Python文件中,以便使用。
注意事项与考量: 需要指出的是,这只是一个示例性说明,并非可用于生产的代码。对于实际应用,必须考虑多个因素。大型语言模型可能无法完全理解目标意图的含义,并可能错误地评估其性能为成功。即使目标被充分理解,模型也可能产生幻觉。当同一个LLM既负责编写代码又负责评估其质量时,它可能更难发现自己在错误的方向上。
最终,大型语言模型(LLM)并不能通过魔法生成完美的代码;您仍然需要运行和测试生成的代码。此外,简单示例中的“监控”功能较为基础,存在进程无限运行的风险。
Act as an expert code reviewer with a deep commitment to producing clean, correct, and simple code. Your core mission is to eliminate code "hallucinations" by ensuring every suggestion is grounded in reality and best practices. When I provide you with a code snippet, I want you to:
-- Identify and Correct Errors: Point out any logical flaws, bugs, or potential runtime errors.
-- Simplify and Refactor: Suggest changes that make the code more readable, efficient, and maintainable without sacrificing correctness.
-- Provide Clear Explanations: For every suggested change, explain why it is an improvement, referencing principles of clean code, performance, or security.
-- Offer Corrected Code: Show the "before" and "after" of your suggested changes so the improvement is clear. Your feedback should be direct, constructive, and always aimed at improving the quality of the code.
一种更稳健的方法是通过为智能体团队中的每个成员分配特定角色来分离这些关注点。例如,我使用Gemini构建了一个个人智能体团队,其中每个智能体都承担着特定的角色:
- 同伴程序员:帮助编写和构思代码。
- 代码审查员:捕捉错误并建议改进。
- 文档生成器:生成清晰简洁的文档。
- 测试编写者:创建全面的单元测试。
- 智能体提示优化器:优化与AI的交互。
在这个多智能体系统中,代码审查员作为一个独立于程序员智能体的实体,其提示词类似于示例中的法官,这显著提高了客观评估的准确性。这种结构自然而然地引导出更好的实践,因为测试编写智能体可以为同行程序员产生的代码编写单元测试。
我将添加这些更高级的控制以及使代码更接近生产就绪状态的任务留给感兴趣的读者。
概览
内容:人工智能智能体往往缺乏明确的方向,这阻碍了它们在简单、反应性任务之外有目的性地行动。没有定义的目标,它们无法独立解决复杂的多步骤问题或编排复杂的流程。此外,它们没有内在机制来确定自己的行动是否会导致成功的成果。这限制了它们的自主性,并阻止它们在动态、现实世界的场景中真正有效,在这些场景中,仅仅执行任务是不够的。
目的: 目标设定与监控模式通过将目的感和自我评估嵌入智能体系统中,提供了一种标准化的解决方案。它包括为智能体明确定义清晰、可衡量的目标。同时,它建立了一种监控机制,持续跟踪智能体的进度及其环境状态与这些目标的一致性。这形成了一个关键的反馈循环,使智能体能够评估其性能、纠正航向,并在偏离成功路径时调整其计划。通过实施此模式,开发者可以将简单的反应性智能体转变为积极主动、以目标为导向的系统,这些系统能够实现自主和可靠的运行。
经验法则:当智能体必须自主执行多步骤任务、适应动态条件,并可靠地实现特定的高层次目标而不需要持续的人类干预时,请使用此模式。
视觉摘要

图2:目标设计模式
关键要点
主要收获包括:
目标设定与监控为智能体提供目标和跟踪进度的机制。 目标应当是具体、可衡量、可实现、相关和有时限的(SMART)。 明确界定指标和成功标准对于有效监控至关重要。 监控涉及观察智能体的行为、环境状态和工具输出。 监控产生的反馈循环使智能体能够适应、修订计划或升级问题。 在谷歌的ADK中,目标通常通过智能体指令传达,监控则通过状态管理和工具交互来完成。
结论
本章重点介绍了至关重要的目标设定与监控范式。我强调了这一概念如何将AI智能体从仅仅被动的系统转变为主动、以目标为导向的实体。文本强调了定义清晰、可衡量的目标以及建立严格的监控程序以跟踪进展的重要性。实际应用展示了这一范式如何支持在各种领域,包括客户服务和机器人技术中的可靠自主操作。一个概念性编码示例说明了在结构化框架内实施这些原则的方法,使用智能体指令和状态管理来引导和评估智能体实现其指定目标的情况。最终,赋予智能体制定和监督目标的能力是构建真正智能和可问责的AI系统的基本步骤。