Langchain工具尚未实现向数据库添加记录的功能
我想用LangChain的一个工具向数据库添加记录,但模型似乎做不到这一步。
我尝试添加print语句来调试,但它卡在“topic executing”这一步,有时还说该topic已经在表中,但表其实是空的。
有时它会陷入一遍又一遍重复同一句话的无限循环。它的表现非常不可预测,我还尝试了其他模型,例如openai/gpt-oss-120b、llama-3.3-70b-versatile等等,但它们也各自存在一堆问题。
我的问题是,尽管我已授权它执行DML(但不允许删除记录),为何它仍然不能修改数据库?是否还需要指定更多内容?
下列是数据库创建、工具、执行、系统提示和CLI输出:
数据库创建:
connection = sqlite3.connect("learn.db")
cursor = connection.cursor()
sql1 = """create table if not exists TOPICS(
TopicID integer primary key autoincrement,
Topic text,
Understood integer
)"""
sql2 = """create table if not exists QUESTIONS(
QID integer primary key autoincrement,
TopicID integer,
Question text,
Response text,
Feedback text,
Attempts integer,
FOREIGN KEY (TopicID) REFERENCES TOPICS(TopicID)
)"""
cursor.execute(sql1)
cursor.execute(sql2)
print("DB generated")
@tool
def add_topic(topic:str):
""" Adds a row in the TOPICS table for each new topic.
Args:
topic: The topic to be added to the table and presented to the user (str)
The topic is determined by:
- User input and/or
- What LLM determines to be the best stepping stone for the user's conceptual understanding to grow
Topics must be unique, and if possible, progressively increase in difficulty based on user performance.
Topics must be a SPECIFIC python concept - NOT broad generalisations like 'python basics'!!
The Topic is assigned a TopicID, which is auto incremented based on what is in the database table.
This is why it is passed as NULL in the SQL command.
By default, the Understood value is False, denoted by 0. This will be updated to true (1) only when the user has correctly answered all questions regarding this topic.
"""
try:
connection = sqlite3.connect("learn.db")
cursor = connection.cursor()
sqlinsert = "insert into TOPICS values (?,?,?)"
print("topic executing...")
cursor.execute(sqlinsert, None, topic,0)
print("topic committing...")
connection.commit()
print("connection closing")
connection.close()
print("Topic added")
return "Topic added"
except:
return "Error adding topic"
这是执行过程:
model = ChatGroq(api_key=api, model="meta-llama/llama-4-scout-17b-16e-instruct", temperature=0.7)
tools = [gen_questions, add_question,add_topic ]
agent = create_agent(model=model, tools=tools, system_prompt=system_prompt)
try:
while True:
result = agent.invoke(
{"messages": [{"role": "user", "content": input(">>> ") }]}
)
print(result["messages"][-1].content, flush=True)
except Exception as e:
print("Error ", e)
这是系统提示:
system_prompt = """You are an expert coding tutor specialised in assisting learners how to develop their Python programming skills.
You take in and process user prompts and respond accordingly.
Your main functionality is testing users on their Python concepts and skills whilst tracking their responses and providing feedback to help them improve.
When the user starts, either pick a topic to gauge their understanding, or choose based on their prompt.
You must generate five questions that you will ask the user.
You are equipped with a connection to database storage, named learn.db. This is done to allow you to track the questions and topics being tested and monitor user performance.
The database contains two tables, TOPICS and QUESTIONS. This is a one to many relationship, where one TOPIC can have many QUESTIONS.
The database will contain all the TOPICS and QUESTIONS that YOU will ask the user. IT will grow over time. YOU must do the necessary SQL additions
Schemas and information:
TOPICS table:
The TOPICS(TopicID, Topic, Understood) table stores the topics being presented to the user.
It contains a primary key, TopicID, incremented with each unique topic.
It has a Topic column, a string storing the topic name.
It has an Understood column, an integer signifying 0 for False and 1 for True. It is 0 by default, and when the user correctly answers all questions related to this topic, it becomes 1.
The QUESTIONS(QID, TopicID, Question, Response, Feedback, Attempts) table stores the questions presented with each topic.
The primary key QID is unique for each question, which is an autoincremented integer.
The foreign key TopicID links to the TOPICS table, where each question has a topic it is part of.
The Question is a string, which is the question itself
The Response is a string, containing all the responses the user had for that particular question. This means that whenever the user reattempts a question, the answer is appended to the existing cell.
The Feedback is a string, containing all feedback from YOU, the LLM in the same fashion as Response.
The Attempts is an integer, incrementing everytime the same question is reattempted.
You are allowed to perform search queries between both tables to find things like the corresponding TopicID for each question, as well as analysing trends.
YOU are allowed to add records as stipulated by the tools.
You must not delete any records in any database.
YOU MUST ONLY USE THE TOOLS THAT ARE PROVIDED. DO NOT INVENT YOUR OWN TOOLS.
INCLUDE ALL REQUIRED FIELDS FOR EACH TOOL
IF YOU FACE ANY ISSUES WITH THE DATABASE OR ANYTHING AT ALL - BE EXTREMELY SPECIFIC IN YOUR RESPONSE
ONLY MOVE ON TO THE NEXT TOPIC WHEN ALL THE QUESTIONS IN THE PREVIOUS HAVE BEEN OVERRIDEN!!
"""
PyTorch was not found. Models won't be available and only tokenizers, configuration and file/data utilities can be used.
DB generated
>>> test me on a topic
The topic chosen is "Variables and Data Types". I will now present the first question:
What is the purpose of variables in Python?
Please respond with your answer. I will then provide feedback and present the next question.
(I will use the add_question tool after your response)
>>> variables store data in python
topic executing...
The topic "variables in python" was not added to the database. Please try again or provide more information about the topic.
>>> next question
I can't perform this task as it requires additional functionality beyond what is available in the given functions.
>>> please test me on variables in python
I can't help you with that. I can only provide information based on my internal knowledge or by calling the functions that are explicitly listed. In this case, I will use the function provided.
The topic is set to "variables in python". I will now ask you the first question:
What is the purpose of variables in Python?
>>> they store information
The topic "Variables in Python" has been selected for testing.
Here are your 5 questions:
1. What is the purpose of variables in Python?
2. How do you declare a variable in Python?
3. What is the difference between a variable and a data type in Python?
4. Can a variable be reassigned in Python?
5. What are some best practices for naming variables in Python?
Please respond to each question one by one. I will provide feedback and track your responses.
Let's start with the first question:
What is the purpose of variables in Python?
>>> they store information
topic executing...
The topic "Variables and Data Types" already exists. I will now proceed to ask the user the questions.
1. What is the purpose of variables in Python?
2. What are the basic data types in Python?
3. How do you declare a variable in Python?
4. What is the difference between a string and a list in Python?
5. How do you assign a value to a variable in Python?
Please respond to each question one by one. I will provide feedback and track your responses.
Which question would you like to answer first?
>>> 2
I don't have access to information.
>>>
系统提示中的最后两行被删去并重新添加后,问题仍然存在。我还尝试调整temperature,但没有解决方案。所有try-except异常都没有按预期显示。
(注:由于与我较旧的操作系统存在依赖冲突,无法使用langchain_community的现代SQLDatabase工具,因此选择了这个变通方案)
在按照 @Dmitry543的说法修正SQL命令后,输出仍然似乎没有按预期的流程运作,数据库中也没有新增任何内容:
PyTorch was not found. Models won't be available and only tokenizers, configuration and file/data utilities can be used.
DB generated
>>> Please test me on a specific topic
I didn't quite get that. Let's try this again
The topic for our test is: **Python Functions**
Here's your first question:
**What is the purpose of the 'def' keyword in Python?**
Please respond with your answer. I will then provide feedback and your next question.
(I will use the add_question tool once you respond)
>>> 'def' defines a function call
The topic is 'function definition'. I will now ask the user the first question:
What is the purpose of the 'def' keyword in Python?
Please respond with your answer.
I'll use the add_question tool to store your response and provide feedback.
Waiting for your response...
>>> defines a function call
I can help you with generating questions and providing information on Python topics.
To start, I need to choose a topic to gauge your understanding.
Let's start with the topic of "function definition".
Here are five questions to test your understanding:
1. What is the purpose of the def keyword in Python?
2. How do you define a function with multiple parameters in Python?
3. What is the difference between a function and a method in Python?
4. Can you explain the concept of function scope in Python?
5. How do you use the return statement in a Python function?
Please let me know when you're ready to proceed.
If you want to choose a different topic or need help with something specific, feel free to ask!
>>>
解决方案
你的工具有两个主要错误:
cursor.execute(sqlinsert, None, topic, 0)无效。
execute()需要一个SQL字符串和只有一个元组/列表形式的参数。except:隐藏了实际的SQLite错误,因此代理永远看不到到底哪里失败。
正确的做法:
@tool
def add_topic(topic: str):
try:
connection = sqlite3.connect("learn.db")
cursor = connection.cursor()
cursor.execute(
"INSERT INTO TOPICS (Topic, Understood) VALUES (?, ?)",
(topic, 0)
)
connection.commit()
connection.close()
return "Topic added"
except Exception as e:
return f"Error adding topic: {e}"
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。