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

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

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

相关推荐
梦在远山后3 小时前
Python 中两种 Queue 的区别
python·langchain
dunge20265 小时前
ChatGPT Plus / Pro + Codex 深度实战指南:2026年9月2日 从智能编程到自动化工作流的完整技术手册
运维·chatgpt·自动化
Easy_API15 小时前
8月31日,三份“模型合同”同时到期
人工智能·chatgpt
枫叶丹417 小时前
实时语音 Agent:从语音机器人到连续协作界面
人工智能·chatgpt·机器人·语音识别·agent·codex
花间相见18 小时前
【LangChain组件03】—— LangChain Agents 执行与状态:工作流程与状态管理实战
java·前端·langchain
Darling噜啦啦18 小时前
LLM 记忆管理三剑客:截断、总结、检索,彻底搞懂 Agent 的 Memory 系统
langchain·llm·agent
jyOverQ19 小时前
ChatGPT Windows 客户端点击无反应、有进程却没窗口?一次 MSIX 非系统盘启动卡死的完整排查
windows·chatgpt
QZSJTR19 小时前
2026年AI搜索引擎技术原理与GEO优化实战:从RAG到AI Agent
人工智能·搜索引擎·chatgpt
beyond谚语19 小时前
六、LangChain——StrOutputParser和JsonOutputParser
langchain·rag·ollama
凭君语未可1 天前
CC Switch 切换 Codex 中转站后历史会话打不开?一次 model_provider 绑定问题的排查与解决
chatgpt