简单实现一个本地ChatGPT web服务(langchain框架)

简单实现一个本地ChatGPT 服务,用到langchain框架,fastapi,并且本地安装了ollama。

依赖安装:

python 复制代码
pip install langchain
pip install langchain_community
pip install langchain-cli # langchain v0.2 2024年5月最新版本
pip install bs4
pip install langchainhub
pip install FastAPI

实现本地chatGPT代码:

python 复制代码
from fastapi import FastAPI
from langchain_community.llms.ollama import Ollama
from langchain_core.prompts import ChatPromptTemplate
from langserve import add_routes
from langchain_core.output_parsers import StrOutputParser
from langchain_core.messages import HumanMessage, SystemMessage

# 创建LLM模型
model = Ollama(model="qwen2:7b")

messages = [
    SystemMessage(content="你好!我是你的虚拟助理。今天我能为您做些什么?"),
    HumanMessage(content="你好!"),
]

result = model.invoke(messages)

print('-----------------------相当于启动测试模型回复-----------------------')
print(result)
print('-----------------------相当于启动测试模型回复-----------------------')

parser = StrOutputParser()

prompt_template = ChatPromptTemplate.from_messages([
    ('system', "你好!我是你的虚拟助理。"),
    ('user', '{text}')
])

chain = prompt_template | model | parser

# 定义web服务
app = FastAPI(
    title="LangChain Server",
    version="1.0",
    description="一个简单的 web API 服务",
)

add_routes(
    app,
    chain,
    path="/chain",
)

if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="localhost", port=8000)

服务运行启动web服务结果:

客户端调用web服务测试代码:

python 复制代码
from langserve import RemoteRunnable

remote_chain = RemoteRunnable("http://localhost:8000/chain/")
r = remote_chain.invoke({ "text": "帮我用java写1个排序算法"})
print(r)

测试结果回答准确,如下图:

服务端非常简单,后面再写个前端对接一下即可方便使用。

相关推荐
BeforeEasy1 小时前
从零搭建一个完整的ai-agent小项目
人工智能·langchain
DS随心转小程序7 小时前
deepseek导出word
人工智能·chatgpt·edge·word·deepseek·ds随心转
西柚小萌新9 小时前
【人工智能:Agent】--9.2.Langchain自定义中间件
langchain
cs.shunzhang10 小时前
Windows 下 OpenCode使用 ChatGPT Pro/Plus 鉴权报错 403 的排查与解决
windows·chatgpt
科技前线13 小时前
服装进销存软件测评
人工智能·chatgpt·chat gpt·马斯克·open ai
Loo国昌1 天前
深入理解 FastAPI:Python高性能API框架的完整指南
开发语言·人工智能·后端·python·langchain·fastapi
Sarvartha1 天前
LangChain 入门核心知识学习笔记
笔记·学习·langchain
勇气要爆发1 天前
Docker+Ollama+LangChain:从零搭建企业级“隐私优先”本地 RAG 知识库 (附源码)
docker·容器·langchain·lora·rag·ollama·llama 3
DS随心转APP1 天前
豆包排版乱码怎么办?
人工智能·ai·chatgpt·deepseek·ds随心转
懈尘2 天前
基于Spring Boot与LangChain4j的AI驱动新闻系统设计与工程实现
java·大数据·人工智能·spring boot·后端·langchain