chore: rename multiple files to improve importability and module structure
This commit is contained in:
@@ -1,16 +0,0 @@
|
||||
from langchain_core.tools import tool
|
||||
|
||||
@tool
|
||||
def get_weather(location):
|
||||
"""模拟获得天气信息"""
|
||||
return f"{location}当前天气:23℃,晴,风力2级"
|
||||
|
||||
@tool
|
||||
def get_user_name(user):
|
||||
"""模拟获得用户名字"""
|
||||
return f'用户名字是:{user}'
|
||||
|
||||
|
||||
# 封装好要用的工具
|
||||
tools = [get_weather,get_user_name]
|
||||
print('工具箱已封装完毕!')
|
||||
@@ -1,49 +0,0 @@
|
||||
from config import OPENAI_API_KEY
|
||||
from langchain_openai import ChatOpenAI
|
||||
# 在LangChain 1.0+版本中,以下俩组件移到了langchain-classic包中
|
||||
from langchain_classic.agents import AgentExecutor
|
||||
from langchain_classic.agents import create_tool_calling_agent
|
||||
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
||||
from langchain_core.tools import tool # 导入 @tool
|
||||
|
||||
# 配置LLM
|
||||
llm = ChatOpenAI(
|
||||
model="deepseek-chat",
|
||||
api_key=OPENAI_API_KEY,
|
||||
base_url="https://api.deepseek.com"
|
||||
)
|
||||
|
||||
# 配置prompt
|
||||
prompt = ChatPromptTemplate.from_messages([
|
||||
("system","你是一个聪明的智能助手。当你遇到解决不了的问题时,会调用工具来解决问题。"),
|
||||
("human","{input}"),
|
||||
MessagesPlaceholder(variable_name="agent_scratchpad") # 必加,Agent的思考过程
|
||||
])
|
||||
|
||||
# 配置tool
|
||||
@tool
|
||||
def get_weather(location):
|
||||
"""模拟获得天气信息"""
|
||||
return f"{location}当前天气:23℃,晴,风力2级"
|
||||
|
||||
@tool
|
||||
def get_user_name(user):
|
||||
"""模拟获得用户名字"""
|
||||
return f'用户名字是:{user}'
|
||||
|
||||
|
||||
tools = [get_weather,get_user_name]
|
||||
|
||||
# 创建Agent(大脑)
|
||||
agent = create_tool_calling_agent(llm=llm,prompt=prompt,tools=tools)
|
||||
# 创建AgentExecutor(执行器)--负责运行ReAct循环
|
||||
agent_executor = AgentExecutor(agent=agent,tools=tools,verbose=True) # 开启verbose以看到ai思考链
|
||||
# 运行
|
||||
response = agent_executor.invoke({
|
||||
'input':"今天北京的天气怎么样?"
|
||||
})
|
||||
|
||||
print(response)
|
||||
print()
|
||||
print(response['output'])
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
from config import OPENAI_API_KEY
|
||||
import sqlite3
|
||||
from langchain_openai import ChatOpenAI
|
||||
from langchain_community.agent_toolkits import create_sql_agent
|
||||
from langchain_community.utilities import SQLDatabase # 导入 SQLDatabase
|
||||
import os
|
||||
|
||||
# 配置llm
|
||||
llm = ChatOpenAI(
|
||||
model="deepseek-chat",
|
||||
api_key=OPENAI_API_KEY,
|
||||
base_url="https://api.deepseek.com"
|
||||
)
|
||||
|
||||
# 创建一个临时的数据库--用于演示
|
||||
db_file = "test_sql.db"
|
||||
if os.path.exists(db_file):
|
||||
os.remove(db_file)
|
||||
conn = sqlite3.connect(db_file)
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("CREATE TABLE users (id INT,name TEXT,age INT);")
|
||||
cursor.execute("INSERT INTO users (id,name,age) VALUES (1,'Alice',30);")
|
||||
cursor.execute("INSERT INTO users (id,name,age) VALUES (2,'Bob',25);")
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
# 连接数据库 -- LangChain 使用 SQLAlchemy URI (连接方式)
|
||||
db_uri = f'sqlite:///{db_file}'
|
||||
db = SQLDatabase.from_uri(db_uri)
|
||||
|
||||
# 创建sqlAgent -- 一键完成,无需定义tools,仅告诉它使用openai-tools,即Tool Calling(工具调用)模式
|
||||
agent_executor = create_sql_agent(
|
||||
llm=llm,
|
||||
db=db,
|
||||
agent_type="openai-tools",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# 运行
|
||||
response = agent_executor.invoke({"input":"告诉我Alice多大了?"})
|
||||
print(response['output'])
|
||||
|
||||
# 清理
|
||||
db._engine.dispose() # 关闭连接池,避免文件被占用
|
||||
if os.path.exists(db_file):
|
||||
os.remove(db_file)
|
||||
@@ -1,76 +0,0 @@
|
||||
from config import OPENAI_API_KEY
|
||||
from langchain_openai import ChatOpenAI
|
||||
from langchain_classic.agents import AgentExecutor
|
||||
from langchain_classic.agents import create_tool_calling_agent
|
||||
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
||||
from langchain_core.tools import tool # 导入 @tool
|
||||
from langchain_community.chat_message_histories import ChatMessageHistory
|
||||
from langchain_core.runnables import RunnableWithMessageHistory
|
||||
|
||||
|
||||
# 配置llm
|
||||
llm = ChatOpenAI(
|
||||
model="deepseek-chat",
|
||||
api_key=OPENAI_API_KEY,
|
||||
base_url="https://api.deepseek.com"
|
||||
)
|
||||
# 配置prompt(新增俩占位符 一个为对话历史记录,一个为agent的思考过程)
|
||||
prompt = ChatPromptTemplate.from_messages([
|
||||
('system','你是小智,一个帮助他人的智能助手。当你无法解答当前问题时,会调用工具来解决问题。'),
|
||||
MessagesPlaceholder(variable_name="history"),
|
||||
('human','{input}'),
|
||||
MessagesPlaceholder(variable_name="agent_scratchpad")
|
||||
])
|
||||
|
||||
# 配置tool
|
||||
@tool
|
||||
def get_weather(location):
|
||||
"""模拟获得天气信息"""
|
||||
return f"{location}当前天气:23℃,晴,风力2级"
|
||||
|
||||
|
||||
tools = [get_weather]
|
||||
# 配置agent
|
||||
agent = create_tool_calling_agent(llm=llm,prompt=prompt,tools=tools)
|
||||
# 配置AgentExecutor
|
||||
agent_executor = AgentExecutor(agent=agent,tools=tools) # 这里没加verbose=True,想打印日志看思考链的可以自行打印
|
||||
|
||||
|
||||
# 记忆存储--包装agent_executor
|
||||
store = {}
|
||||
def get_session_history(session_id:str):
|
||||
if session_id not in store:
|
||||
store[session_id] = ChatMessageHistory()
|
||||
return store[session_id]
|
||||
|
||||
|
||||
# 添加记忆功能
|
||||
agent_with_memory = RunnableWithMessageHistory(
|
||||
runnable=agent_executor,
|
||||
get_session_history=get_session_history,
|
||||
input_messages_key="input",
|
||||
history_messages_key="history"
|
||||
)
|
||||
# 打印测试
|
||||
session_id = 'user123'
|
||||
|
||||
if __name__ == '__main__':
|
||||
while 1:
|
||||
user_input = input('\n你:')
|
||||
if user_input == 'quit':
|
||||
print('拜拜~')
|
||||
break
|
||||
response = agent_with_memory.invoke(
|
||||
{'input': user_input},
|
||||
config={'configurable': {'session_id': session_id}}
|
||||
)
|
||||
print(f"AI:{response['output']}")
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
from config import OPENAI_API_KEY
|
||||
import time
|
||||
from langchain_openai import ChatOpenAI
|
||||
from langchain_core.globals import set_llm_cache
|
||||
from langchain_community.cache import InMemoryCache
|
||||
|
||||
# 配置llm
|
||||
llm = ChatOpenAI(
|
||||
model="deepseek-chat",
|
||||
api_key=OPENAI_API_KEY,
|
||||
base_url="https://api.deepseek.com"
|
||||
)
|
||||
# 设置全局缓存
|
||||
set_llm_cache(InMemoryCache())
|
||||
|
||||
# 第一次调用llm(会远程请求)
|
||||
query = "用中文写一句关于猫的五言诗。"
|
||||
start_time = time.time()
|
||||
response1 = llm.invoke(query).content
|
||||
print(f"第一次调用结果: {response1}")
|
||||
print(f"第一次运行时间: {time.time() - start_time:.4f} 秒")
|
||||
print('')
|
||||
|
||||
# 第二次调用llm(会命中缓存)
|
||||
start_time = time.time()
|
||||
response2 = llm.invoke(query).content
|
||||
print(f"第二次调用结果: {response2}")
|
||||
print(f"第二次运行时间 (已缓存): {time.time() - start_time:.4f} 秒")
|
||||
|
||||
# 清理
|
||||
set_llm_cache(None) # 关闭缓存,以免影响后续实例
|
||||
print('缓存清理完成')
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
from config import OPENAI_API_KEY
|
||||
from langchain_openai import ChatOpenAI
|
||||
from langchain_classic.agents import AgentExecutor
|
||||
from langchain_classic.agents import create_tool_calling_agent
|
||||
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
||||
from langchain_core.tools import tool # 导入 @tool
|
||||
from langchain_community.chat_message_histories import ChatMessageHistory
|
||||
from langchain_core.runnables import RunnableWithMessageHistory
|
||||
from langchain_core.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
|
||||
|
||||
|
||||
# 配置llm
|
||||
llm = ChatOpenAI(
|
||||
model="deepseek-chat",
|
||||
api_key=OPENAI_API_KEY,
|
||||
base_url="https://api.deepseek.com",
|
||||
streaming=True,
|
||||
callbacks=[StreamingStdOutCallbackHandler()]
|
||||
)
|
||||
# 配置prompt(新增俩占位符 一个为对话历史记录,一个为agent的思考过程)
|
||||
prompt = ChatPromptTemplate.from_messages([
|
||||
('system','你是小智,一个帮助他人的智能助手。当你无法解答当前问题时,会调用工具来解决问题。'),
|
||||
MessagesPlaceholder(variable_name="history"),
|
||||
('human','{input}'),
|
||||
MessagesPlaceholder(variable_name="agent_scratchpad")
|
||||
])
|
||||
|
||||
# 配置tool
|
||||
@tool
|
||||
def get_weather(location):
|
||||
"""模拟获得天气信息"""
|
||||
return f"{location}当前天气:23℃,晴,风力2级"
|
||||
|
||||
|
||||
tools = [get_weather]
|
||||
# 配置agent
|
||||
agent = create_tool_calling_agent(llm=llm,prompt=prompt,tools=tools)
|
||||
# 配置AgentExecutor
|
||||
agent_executor = AgentExecutor(agent=agent,tools=tools) # 这里没加verbose=True,想打印日志看思考链的可以自行打印
|
||||
|
||||
|
||||
# 记忆存储--包装agent_executor
|
||||
store = {}
|
||||
def get_session_history(session_id:str):
|
||||
if session_id not in store:
|
||||
store[session_id] = ChatMessageHistory()
|
||||
return store[session_id]
|
||||
|
||||
|
||||
agent_with_memory = RunnableWithMessageHistory(
|
||||
runnable=agent_executor,
|
||||
get_session_history=get_session_history,
|
||||
input_messages_key="input",
|
||||
history_messages_key="history"
|
||||
)
|
||||
# 打印测试
|
||||
session_id = 'user123'
|
||||
|
||||
if __name__ == '__main__':
|
||||
while 1:
|
||||
user_input = input('\n你:')
|
||||
if user_input == 'quit':
|
||||
print('拜拜~')
|
||||
break
|
||||
# 用于标记"AI:"这个内容
|
||||
# flush=True保证"AI:"立即输出,而不是等缓存区存满再输出
|
||||
print("AI: ", end="", flush=True)
|
||||
response = agent_with_memory.invoke(
|
||||
{'input': user_input},
|
||||
config={'configurable': {'session_id': session_id}}
|
||||
)
|
||||
print()
|
||||
|
||||
Reference in New Issue
Block a user