实现输入指令让AI生成python代码并执行
导入相关库
import refrom langchain_core.prompts import ChatPromptTemplate
from langchain_core.tools import tool
from langgraph.prebuilt import create_react_agentfrom src.utils.models import gpt4o_model
编写工具,实现提取AI返回的内容,并执行代码
@tool
def extract_function_code(s_python, detail=0):"""执行传入的python函数代码"""def extract_code(s_python):"""如果输入的字符串s是一个包含Python代码的Markdown格式字符串,提取出代码部分。否则,返回原字符串。参数:s: 输入的字符串。返回:提取出的代码部分,或原字符串。"""# 判断字符串是否是Markdown格式if '```python' in s_python or 'Python' in s_python or 'PYTHON' in s_python:# 找到代码块的开始和结束位置code_start = s_python.find('def')code_end = s_python.find('```\n', code_start)# 提取代码部分code = s_python[code_start:code_end]else:# 如果字符串不是Markdown格式,返回原字符串code = s_pythonreturn code# 提取代码字符串code = extract_code(s_python)# 提取函数名称match = re.search(r'def (\w+)', code)function_name = match.group(1)# 将函数写入本地with open('%s.py' % function_name, 'w', encoding='utf-8') as f:f.write(code)print(f"生成的代码:{code}")# 执行该函数try:exec(code, globals())print("代码执行成功")except Exception as e:print("执行代码时发生错误:")print(e)# 打印函数名称if detail == 0:print("函数名称是:%s" % function_name)if detail == 1:with open('%s.py' % function_name, encoding='utf-8') as f:content = f.read()print(content)
使用 langchain_core 和 langgraph 库创建智能代理,通过 GPT-4 模型生成代码
agent = create_react_agent(model=gpt4o_model.bind_tools([extract_function_code]),tools=[extract_function_code]
)
chat_template = ChatPromptTemplate.from_messages([("system","你是一个python代码编辑器,你的功能是输出python代码,只输出代码即可,请勿输出任何其他内容,请在函数编写过程中,在函数内部加入中文编写的详细的函数说明文档"),("human", "{user_input},并使用extract_function_code执行"),]
)
result = agent.invoke({"messages": chat_template.format_messages(user_input="输出Hello World")})
我输入【输出Hello World】后,大模型生成一个python脚本,然后extract_function_code提取其中的内容进行执行
生成的代码:def print_hello_world():"""打印'Hello World'这句话。"""print('Hello World')
代码执行成功
函数名称是:print_hello_world
同理可以传入不同的提示词让他生成不同的代码来完成我们的任务