From a76f73d1e00b89be3a5a953a67a232ba64715b1e Mon Sep 17 00:00:00 2001 From: guanjihuan Date: Wed, 5 Nov 2025 16:09:31 +0800 Subject: [PATCH] update --- 2025.11.02_langchain/langchain_example.py | 4 +- .../langchain_example_with_Ollama.py | 38 +++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 2025.11.02_langchain/langchain_example_with_Ollama.py diff --git a/2025.11.02_langchain/langchain_example.py b/2025.11.02_langchain/langchain_example.py index e8171f8..95b48a1 100644 --- a/2025.11.02_langchain/langchain_example.py +++ b/2025.11.02_langchain/langchain_example.py @@ -3,7 +3,7 @@ This code is supported by the website: https://www.guanjihuan.com The newest version of this code is on the web page: https://www.guanjihuan.com/archives/47909 """ -import langchain_openai +from langchain_openai import ChatOpenAI from langchain_core.prompts import ChatPromptTemplate import dotenv import os @@ -12,7 +12,7 @@ import os dotenv.load_dotenv() # 创建聊天模型 -llm = langchain_openai.ChatOpenAI( +llm = ChatOpenAI( api_key=os.getenv("OPENAI_API_KEY"), # 从环境变量获取 API 密钥 base_url=os.getenv("DASHSCOPE_BASE_URL"), # 指定 API 端点 model="qwen-plus", # 使用通义千问 Plus 模型 diff --git a/2025.11.02_langchain/langchain_example_with_Ollama.py b/2025.11.02_langchain/langchain_example_with_Ollama.py new file mode 100644 index 0000000..06832dc --- /dev/null +++ b/2025.11.02_langchain/langchain_example_with_Ollama.py @@ -0,0 +1,38 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/47909 +""" + +from langchain_openai import ChatOpenAI +from langchain_core.prompts import ChatPromptTemplate +import dotenv + +# 加载环境变量(包含API密钥) +dotenv.load_dotenv() + +# 创建聊天模型 - 修改为调用 Ollama +llm = ChatOpenAI( + api_key="ollama", # 对于 Ollama,API key 可以设为任意值或 "ollama" + base_url="http://localhost:11434/v1", # Ollama 的本地 API 地址 + model="qwen2.5:3b", # 替换为你本地安装的模型名称,如 qwen2.5 等 + temperature=0.7, # 控制回复的随机性(0-1,越高越有创意) + streaming=True, # 启用流式模式 +) + +# 创建简单的提示词模板 +prompt = ChatPromptTemplate.from_messages([ + ("system", "你是一个友好的聊天助手。"), # 系统角色设定 + ("human", "{question}") # 用户输入占位符 +]) + +# 创建处理链 +chain = prompt | llm # 使用管道操作符连接组件 + +# 使用 stream() 实现流式输出 +for chunk in chain.stream({"question": "你好"}): + print(chunk.content, end="", flush=True) +print() # 换行 + +# # 非流式输出 +# response = chain.invoke({"question": "你好"}) +# print(response.content) \ No newline at end of file