简单实现一个本地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)

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

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

相关推荐
UIUV7 小时前
RAG技术学习笔记(含实操解析)
javascript·langchain·llm
神秘的猪头13 小时前
🚀 拒绝“一本正经胡说八道”!手把手带你用 LangChain 实现 RAG,打造你的专属 AI 知识库
langchain·llm·openai
栀秋66613 小时前
重塑 AI 交互边界:基于 LangChain 与 MCP 协议的全栈实践
langchain·llm·mcp
大模型真好玩14 小时前
LangChain DeepAgents 速通指南(三)—— 让Agent告别混乱:Tool Selector与Todo List中间件解析
人工智能·langchain·trae
是一碗螺丝粉2 天前
LangChain 链(Chains)完全指南:从线性流程到智能路由
前端·langchain·aigc
前端付豪2 天前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
神秘的猪头2 天前
🔌 给 AI 装上“三头六臂”!实战大模型接入第三方 MCP 全攻略
langchain·llm·mcp
前端付豪2 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
神秘的猪头2 天前
🔌 把 MCP 装进大脑!手把手带你构建能“热插拔”工具的 AI Agent
langchain·llm·mcp
是一碗螺丝粉3 天前
5分钟上手LangChain.js:用DeepSeek给你的App加上AI能力
前端·人工智能·langchain