usaco范式展示了如何利用LangGraph构建一个智能代理系统,专门用于解决算法竞赛问题(如USACO,USA Computing Olympiad)。该范式通过结合大语言模型(LLM)、外部工具(如代码执行器)和图结构,模拟程序员解决算法问题的过程,包括问题理解、代码生成、测试验证和调试
主要3个部分
反思:在第一部分中,创建一个零样本工具,调用代理,并提示其反思测试用例结果以纠正初始错误。这与论文中报告的在 USACO 基准测试中通过率为 12.38 的代理类似。
检索:在第二部分中,为代理实现一个初始检索步骤,即“情景记忆”,该代理从我们的编程问题语料库中检索高质量的少量样本示例,以帮助解决青铜级问题。该代理与论文中基准测试分数为 20.2 的代理类似。
人机协同:在第三部分中,使用 interrupt_after 让用户辅助代理找到更好的答案。基准测试性能仅受与其配对的人的竞争力制约。

第 1 部分和第 2 部分与论文中基准测试的系统类似,通过率分别为 12.38 和 20.2。

代码定义了一个Python REPL工具,用于执行和验证代码:
from langchain_core.tools import tool
@tool
def python_repl(code: str) -> str:
"""
Execute the provided Python code and return the output or error message.
Args:
code (str): The Python code to execute.
Returns:
str: The output of the code or an error message if execution fails.
"""
try:
# Create a namespace for the code execution
namespace = {}
# Execute the code
exec(code, namespace)
# Capture output (assuming the code prints or returns something)
return "Code executed successfully"
except Exception as e:
return f"Error: {str(e)}"
- 功能:
- 输入:Python代码字符串。
- 执行:通过exec在隔离的命名空间中运行代码。
- 返回:成功执行返回确认消息,失败返回错误信息。
- 安全性:
- 使用namespace隔离代码执行环境,减少全局变量污染。
- 捕获所有异常,确保错误信息可控。
- 代码未明确限制危险操作(如文件操作),存在潜在安全风险。
分析:python_repl工具是usaco范式的核心组件,用于验证生成的代码。设计简单但功能强大,适合快速验证算法竞赛代码。然而,exec的使用在生产环境中需谨慎,建议在沙箱环境中运行。
2.3 系统提示与代理定义
代码定义了多个提示模板,用于不同解题阶段(问题分析、代码生成、调试等)。
2.3.1 问题分析提示(Analyze Prompt)
USACO问题描述。
from langchain_core.prompts import ChatPromptTemplate
analyze_prompt = ChatPromptTemplate.from_messages([
("system", """You are an expert in analyzing algorithmic problems. Your task is to understand the given problem and extract key information such as input format, output format, constraints, and the core algorithmic task.
Problem description:
{problem}
Please provide a structured analysis in JSON format:
```json
{
"input_format": "description of input format",
"output_format": "description of output format",
"constraints": "key constraints (e.g., size, range)",
"task": "core algorithmic task"
}
```"""),
("human", "Analyze the following problem:\n{problem}")
])
- 提示设计:
- 系统提示明确任务目标,要求提取关键信息。
- JSON格式化输出便于后续处理。
- 鼓励结构化思维,模拟程序员分析问题的过程。
2.3.2 代码生成提示(Generate Prompt)
- 输入:问题分析(JSON格式)。
- 输出:Python代码,解决指定问题
generate_prompt = ChatPromptTemplate.from_messages([
("system", """You are an expert programmer tasked with generating a solution to an algorithmic problem. Based on the provided problem analysis, write a Python solution.
Problem analysis:
{analysis}
Please provide the solution in the following format:
```python
{your_code}
```"""),
("human", "Generate a solution for the following problem analysis:\n{analysis}")
])
2.3.3 调试提示(Debug Prompt)
- 输入:问题分析、失败的代码和错误信息。
- 输出:修复后的代码和问题/修复说明(JSON格式)。
debug_prompt = ChatPromptTemplate.from_messages([
("system", """You are an expert in debugging Python code. The provided code failed to produce the correct output for a given problem. Analyze the code, the problem analysis, and the error message (if any) to suggest fixes.
Problem analysis:
{analysis}
2.3.4 代理定义
代码使用ChatOpenAI创建LLM,并结合提示模板和工具定义代理链:
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model="gpt-4o-mini")
analyze_chain = analyze_prompt | llm.with_structured_output(schema=dict)
generate_chain = generate_prompt | llm
debug_chain = debug_prompt | llm
- LLM:使用gpt-4o-mini,高效且适合推理任务。
- 分析链:analyze_prompt与LLM结合,输出结构化JSON。
- 生成链:generate_prompt与LLM结合,输出Python代码。
- 调试链:debug_prompt与LLM结合,输出修复代码和说明。
- 结构化输出:analyze_chain使用with_structured_output确保JSON格式,生成和调试链直接输出字符串。
分析:提示模板的设计是usaco范式的核心,分解了解题过程(分析、生成、调试),降低了LLM的单次任务复杂度。gpt-4o-mini的选择平衡了性能和成本,结构化输出提高了分析阶段的可靠性。
Paragoger衍生者AI训练营。发布者:稻草人,转载请注明出处:https://www.shxcj.com/archives/9676