不使用langchain_community改用langchain的代码怎么写
时间: 2025-06-19 12:14:06 浏览: 4
<think>我们注意到用户希望使用langchain而不是langchain_community来调用Ollama的API。实际上,在较新的LangChain版本中,推荐使用`langchain_community`包来集成各种第三方模型。但用户可能希望使用更核心的`langchain`包,或者用户的环境可能没有安装`langchain_community`。然而,需要澄清的是,从LangChain的0.1版本开始,社区集成(如Ollama)被移到了`langchain-community`包中。所以,如果用户不想使用`langchain_community`,我们可以考虑使用LangChain提供的更通用的API调用方式,比如使用`langchain`的`BaseLLM`或`LLMChain`等抽象,但需要自己实现与OllamaAPI的交互。但是,用户的问题中引用的内容提到了使用`langchain_community.chat_models.ChatOllama`。如果用户不想使用这个,我们可以使用LangChain的通用HTTP接口(如`langchain.llms.Ollama`)?但实际上,`Ollama`类也在`langchain_community`中。因此,在不使用`langchain_community`的情况下,我们可以使用LangChain的`BaseLLM`基类自定义一个Ollama的LLM包装器,或者使用LangChain的`GenericLLM`(如果存在)?但更直接的方法是使用LangChain的`API`调用功能结合请求库,然后封装成LangChain的LLM对象。不过,用户可能希望有一个简单的示例,直接使用LangChain的核心模块来调用Ollama。考虑到这一点,我们可以使用`langchain`中的`LLMChain`和自定义一个Ollama的LLM类(通过继承`BaseLLM`)来实现。但这样需要自己实现部分代码。但是,根据引用[1]中的描述,用户提到“用langchain提供的函数进行快捷编程,langchain的函数调用Ollama的接口”,所以我们可以理解为用户希望使用LangChain的高级接口(如链、代理等)来调用Ollama,但不想依赖`langchain_community`。实际上,在LangChain中,如果没有`langchain_community`,我们可以使用`langchain`的`OpenAI`类,但那是针对OpenAIAPI的。对于Ollama,官方推荐使用`langchain_community`。因此,这里有两种选择:1.使用`requests`直接调用Ollama的API(即不使用LangChain的任何模型封装),然后将其结果适配到LangChain的链中(例如,通过自定义一个简单的LLM包装器)。2.使用`langchain_community`(因为它是LangChain官方支持的,且用户可能误解了,以为`langchain_community`不是LangChain的一部分)。但是用户明确要求不使用`langchain_community`,所以我们采用第一种方法:自定义一个LLM类,继承自`langchain.llms.base.LLM`(或`BaseLLM`),然后实现必要的函数。步骤:1.创建一个自定义的OllamaLLM类,继承自`BaseLLM`(在`langchain_core.language_models.llms`中,或者从`langchain.llms.base`导入`BaseLLM`,取决于版本)。2.实现`_call`方法,在该方法中发送请求到Ollama的API。3.实现`_llm_type`属性,返回一个字符串标识。注意:由于LangChain版本差异,这里我们以0.1.x版本为例(当前最新版本)。在0.1.x中,我们可以从`langchain_core.language_models.llms`导入`BaseLLM`,但更常见的做法是从`langchain.llms.base`导入。然而,为了简化,我们使用`langchain`的核心基础类。但请注意,在0.1.x版本中,自定义LLM的基类位于`langchain_core.language_models.llms.BaseLLM`(或`langchain.llms.base.BaseLLM`,但后者已被标记为弃用)。根据LangChain文档,自定义LLM需要继承`langchain.llms.base.LLM`(在0.0.x版本中)或`langchain_core.language_models.llms.BaseLLM`(0.1.x)。由于版本问题,这里提供一个通用的方法,并假设使用较新的LangChain版本(>=0.1.0)。示例代码:首先,确保安装了必要的库:```bashpipinstalllangchain-corerequests```然后,编写自定义OllamaLLM类:```pythonfromtypingimportAny,Dict,List,Optionalfromlangchain_core.language_models.llmsimportBaseLLMfromlangchain_core.callbacksimportCallbackManagerForLLMRunimportrequestsclassOllamaLLM(BaseLLM):model_name:str#模型名称,例如"llama3"base_url:str="http://localhost:11434"#Ollama服务地址@propertydef_llm_type(self)->str:return"ollama-llm"def_call(self,prompt:str,stop:Optional[List[str]]=None,run_manager:Optional[CallbackManagerForLLMRun]=None,**kwargs:Any,)->str:#构造请求URLurl=f"{self.base_url}/api/generate"#请求数据data={"model":self.model_name,"prompt":prompt,"stream":False,#非流式}#可以添加其他参数,如temperature等data.update(kwargs)#发送POST请求response=requests.post(url,json=data)response.raise_for_status()#检查请求是否成功response_json=response.json()#返回生成的文本returnresponse_json.get("response","")@propertydef_identifying_params(self)->Dict[str,Any]:"""返回标识参数."""return{"model_name":self.model_name,"base_url":self.base_url}```然后,我们可以像使用其他LangChainLLM一样使用这个自定义类:```pythonfromlangchain.chainsimportLLMChainfromlangchain.promptsimportPromptTemplate#初始化自定义LLMollama_llm=OllamaLLM(model_name="llama3")#创建一个简单的提示模板template="""问题:{question}回答:让我们一步一步思考。"""prompt=PromptTemplate.from_template(template)#创建链chain=LLMChain(llm=ollama_llm,prompt=prompt)#运行链question="太阳系中最大的行星是什么?"result=chain.invoke({"question":question})print(result['text'])```注意:这个自定义类只实现了非流式调用。如果需要流式调用,可以扩展实现。另外,Ollama的聊天API(/api/chat)需要不同的请求格式(messages列表),所以上述自定义类只适用于生成API(/api/generate)。如果要支持聊天模型,需要额外实现一个聊天模型类(继承自`BaseChatModel`)。但是,用户问题中并没有明确要求聊天模型,所以我们只实现了生成API的调用。总结:通过自定义一个继承自`BaseLLM`的类,我们可以在不使用`langchain_community`的情况下集成Ollama,并利用LangChain的其他功能(如链、代理等)。相关问题:1.如何在使用LangChain时自定义大语言模型接口?2.Ollama的API除了生成文本还能做什么?3.如何优化自定义LLM类的性能?</think>### 使用 LangChain 核心库调用 Ollama 大模型 API(不使用 langchain_community)
以下是完全基于 LangChain 核心库(无需 langchain_community)调用 Ollama 大模型 API 的完整实现方案:
#### 方案原理
通过 LangChain 的 `BaseLLM` 基类自定义 Ollama 适配器,直接调用 Ollama 的 HTTP API 接口:
```mermaid
graph LR
A[LangChain应用] --> B[自定义OllamaLLM类]
B --> C[HTTP请求]
C --> D[Ollama本地服务]
D --> E[大语言模型]
```
#### 完整代码实现
```python
from langchain_core.language_models import BaseLLM
from langchain_core.prompts import PromptTemplate
from langchain.chains import LLMChain
import requests
import json
# 自定义 Ollama LLM 适配器
class OllamaLLM(BaseLLM):
model_name: str # 模型名称 (e.g. "llama3")
base_url: str = "http://localhost:11434" # Ollama API地址
temperature: float = 0.7 # 生成随机性
def _call(self, prompt: str, stop=None, **kwargs) -> str:
"""核心调用方法"""
url = f"{self.base_url}/api/generate"
payload = {
"model": self.model_name,
"prompt": prompt,
"stream": False,
"temperature": self.temperature,
**kwargs
}
response = requests.post(url, json=payload)
response.raise_for_status()
return response.json()["response"]
@property
def _llm_type(self) -> str:
return "ollama"
# 使用示例
if __name__ == "__main__":
# 初始化自定义LLM
ollama_llm = OllamaLLM(model_name="llama3", temperature=0.8)
# 创建提示模板
prompt_template = PromptTemplate.from_template(
"请用不超过三句话解释{concept}的工作原理"
)
# 创建LLM链
chain = LLMChain(llm=ollama_llm, prompt=prompt_template)
# 执行链式调用
result = chain.invoke({"concept": "量子纠缠"})
print("模型回复:", result["text"])
```
#### 关键组件说明
1. **自定义 LLM 类 (`OllamaLLM`)**:
- 继承 `BaseLLM` 实现核心接口
- `_call()` 方法处理 API 请求
- 支持自定义参数:
- `model_name`: Ollama 中的模型名称
- `base_url`: API 地址 (默认 `localhost:11434`)
- `temperature`: 生成随机性 (0-1)
2. **LangChain 集成**:
- 与标准 `LLMChain`、`PromptTemplate` 无缝集成
- 支持所有 LangChain 高级功能(代理、记忆等)
3. **API 参数扩展**:
可在调用时添加 Ollama 支持的所有参数:
```python
ollama_llm("问题", num_predict=100, top_k=40)
```
支持的完整参数参见 [Ollama API 文档](https://github.com/ollama/ollama/blob/main/docs/api.md)[^1]
#### 进阶用法:聊天模式实现
```python
# 在自定义类中添加聊天支持
def chat(self, messages: list) -> str:
"""聊天模式调用"""
url = f"{self.base_url}/api/chat"
payload = {
"model": self.model_name,
"messages": messages,
"stream": False,
"temperature": self.temperature
}
response = requests.post(url, json=payload)
return response.json()["message"]["content"]
# 使用示例
messages = [
{"role": "user", "content": "解释相对论"},
{"role": "assistant", "content": "相对论是爱因斯坦提出的..."},
{"role": "user", "content": "它与量子力学有何联系?"}
]
print(ollama_llm.chat(messages))
```
#### 部署注意事项
1. 确保 Ollama 服务已运行:
```bash
ollama serve
```
2. 模型需提前下载:
```bash
ollama pull llama3
```
3. 如需远程访问,修改 `base_url` 并配置防火墙规则
> 此方案完全基于 LangChain 核心架构实现,无需额外依赖 `langchain_community` 包,保持了代码的轻量性和框架兼容性[^1]。
阅读全文
相关推荐


















