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

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

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

相关推荐
换个网名有点难15 分钟前
OpenAI 最新发布的 GPT-4o mini 模型
chatgpt·aigc·agi
人工智能中文站2 小时前
阿里「轨迹可控版Sora」,告别「抽卡」,让视频生成更符合物理规律
人工智能·ai·chatgpt·开源·音视频
三月七(爱看动漫的程序员)10 小时前
Can Large Language Models Provide Feedback to Students? A Case Study on ChatGPT
人工智能·机器学习·语言模型·自然语言处理·chatgpt·文心一言
AI逍遥子10 小时前
如何利用 ChatGPT 提高工作效率?
chatgpt
AI逍遥子10 小时前
ChatGPT等生成式AI在个性化教育方案的应用
人工智能·chatgpt
nidieolc18 小时前
【langchain学习】使用Langchain生成多视角查询
langchain
三月七(爱看动漫的程序员)1 天前
Evaluating the Generation Capabilities of Large Chinese Language Models
人工智能·microsoft·语言模型·自然语言处理·chatgpt·langchain·aigc
wly4769230831 天前
ChatGPT能代替网络作家吗?
人工智能·macos·chatgpt·ai作画·stable diffusion·aigc·文心一言
白如意i1 天前
langchain 入门指南 - 让 LLM 自动选择不同的 Prompt
人工智能·爬虫·ai·langchain·prompt
嫦娥妹妹等等我1 天前
论文阅读:HuggingGPT: Solving AI Tasks with ChatGPT and its Friends in Hugging Face
论文阅读·人工智能·chatgpt