trinhhuy's picture
update 1
25d2fd4 verified
import warnings
warnings.filterwarnings('ignore', category=FutureWarning)
warnings.filterwarnings('ignore', category=DeprecationWarning)
print("agent: > thu vien")
print("-------------")
from langchain.agents import AgentExecutor, create_tool_calling_agent
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_community.chat_message_histories import ChatMessageHistory
from tools import (model_gemini,
get_weather,
toeic_question)
tools = [get_weather, toeic_question]
# Store để lưu chat history
store = {}
def get_session_history(session_id: str):
if session_id not in store:
store[session_id] = ChatMessageHistory()
return store[session_id]
system = """Bạn là một AI có thể sử dụng các công cụ (tool) sau [get_weather, toeic_question]:
1. toeic_question tool: Trả lời các câu hỏi liên quan đến bài thi TOEIC (không hỏi thêm thông tin ngoài lề).
2. get_weather tool: Trả lời câu hỏi về thời tiết hiện tại hoặc thời gian của một thành phố.
3. Nếu câu hỏi không thuộc 2 nhóm trên và bạn biết câu trả lời, hãy trả lời trực tiếp mà không dùng tool.
Quy tắc:
- Luôn xác định loại câu hỏi trước khi trả lời.
- Nếu câu hỏi yêu cầu thông tin về TOEIC → dùng tool toeic_question.
- Các câu hỏi về TOEIC thì nên giữ nguyên hoặc viết lại rõ hơn trước khi đưa vào tool.
- Nếu câu hỏi yêu cầu thời tiết hoặc thời gian ở một địa điểm cụ thể → dùng tool get_weather.
- Nếu có thể trả lời ngay mà không cần tool → trả lời trực tiếp.
- Không đoán thông tin nếu không chắc, hãy nói rõ nếu bạn không biết.
- Khi dùng tool, chỉ chọn đúng 1 tool phù hợp nhất với câu hỏi.
"""
prompt = ChatPromptTemplate.from_messages([
("system", system),
MessagesPlaceholder("chat_history"),
("human", "{input}"),
MessagesPlaceholder("agent_scratchpad")
])
agent = create_tool_calling_agent(
llm=model_gemini,
tools=tools,
prompt=prompt,
)
agent_executor = AgentExecutor(
agent=agent,
tools=tools,
verbose=True,
handle_parsing_errors=True,
)
agent_with_chat_history = RunnableWithMessageHistory(
agent_executor,
get_session_history,
input_messages_key="input",
history_messages_key="chat_history",
)
def chat_with_agent(user_input: str, session_id: str = "default"):
response = agent_with_chat_history.invoke(
{"input": user_input},
config={"configurable": {"session_id": session_id}}
)
return response["output"]
print("agent: DONE")
print("-------------")