从本地开发到云部署的完整教程,加速 LLM 应用上线的实战指南。
最近,我产生了一个想法,在自己的网站 www.akshaymakes.com 上添加一个 AI 助手。我希望它能回答关于我的项目和个人的问题,以及大量讨论机器学习和人工智能的相关内容。我的网站是用 SvelteKit 构建的,我本可以直接从前端使用 OpenAI 的 API。但是,我希望这个助手是可扩展的。也就是说,将来我希望它能够浏览我网站上的博客、项目和其他材料,以更好地回答问题。为了实现这个目标并保持网站的简洁,我使用 FastAPI 创建了一个 LangChain 应用,通过 REST API 与网站集成。我希望用户体验类似于 ChatGPT,即它应该能够记住对话的上下文并自然地继续对话。我将应用部署在 Deta Space 上,这做起来非常简单。让我逐步引导你完成这个过程。我们现在会保持应用的简洁性。在未来的博客中,我会解释如何使用 Weaviate 或 Pinecone 这样的向量数据库将你的网站作为上下文添加进来,使聊天助手对你有更多的了解。
在本教程中,我将展示如何使用 LangChain、FastAPI 和 Deta Space 创建一个 API 来获取 OpenAI 的输出。让我们开始吧。
在新目录中启动一个新的 Python 项目。在我们的示例中,我们将项目目录称为 LangChainAPI。
在新目录中启动一个新的 Python 项目。在我们的示例中,我们将项目目录称为 LangChainAPI。
在 LangChainAPI 中创建一个名为 app 的目录和一个新的 .env 文件。
在 LangChainAPI 中创建一个名为 app 的目录和一个新的 .env 文件。
在 app 文件夹内,创建一个空的 init.py 文件以及一个新的 main.py 和 conversation.py 文件。
在 app 文件夹内,创建一个空的 init.py 文件以及一个新的 main.py 和 conversation.py 文件。
在这个新目录中,使用以下终端命令启动虚拟环境。
python -m venv venv
项目结构看起来会像这样
├── app
│ ├── __init__.py
│ ├── main.py
│ ├── conversation.py
├── .venv
├── .gitignore
└── .env
激活环境。
对于 Windows:
venv\Scripts\activate.bat
对于 MacOS/Linux:
source venv/bin/activate
安装依赖。
pip install langchain fastapi "uvicorn[standard]" openai python-dotenv
安装 Deta Space CLI
对于 Windows:
iwr https://deta.space/assets/space-cli.ps1 -useb | iex
对于 MacOS/Linux:
curl -fsSL get.deta.dev/space-cli.sh | sh
初始化 Git 仓库并提交
git init
git add .
git commit -m "First Commit"
在 https://deta.space/signup 上创建账户,并从设置中获取你的访问令牌。
在 CLI 中登录 Deta Space。它会要求你输入访问令牌。粘贴它。
space login
到此为止,所有的设置都完成了。现在让我们创建 API。
在 app 文件夹中打开 conversation.py。这是我们将编写 LangChain 逻辑的地方。
from langchain import OpenAI, ConversationChain, LLMChain, PromptTemplate
load_dotenv()
def conversation(human_input):
template = """Assistant is a large language model trained by OpenAI.
Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.
Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.
Overall, Assistant is a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.
{history}
Human: {human_input}
Assistant:"""
prompt = PromptTemplate(
input_variables=["history", "human_input"],
template=template
)
chatgpt_chain = LLMChain(
llm=OpenAI(temperature=0),
prompt=prompt,
verbose=True,
)
output = chatgpt_chain.predict(human_input=human_input)
return output
在 main.py 中,添加以下代码:
from fastapi import FastAPI
from langcorn import create_service
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from app.conversation import conversation
class Input(BaseModel):
human_input: str
class Output(BaseModel):
output: str
app=FastAPI()
@app.post("/conversation")
async def input(input: Input):
output = Output(output=conversation(input.human_input))
return output
origins = [
"http://localhost",
"http://localhost:5173",
"...Your Domains..."
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
在 origins 中,你可以添加其他将向你的 API 发出请求的域名。
在终端中使用此命令在本地启动服务器。它将在 localhost:8000 上启动。
uvicorn app.main:app --reload
要测试你的 API,在浏览器中访问 localhost:8000/docs。这应该会打开 Swagger 文档。
你可以输入你的提示并检查是否得到响应。一旦这有效,请随意使用 LangChain。你可以添加内存、上下文等。目前,Deta Space 不支持本地向量数据库。所以如果你需要保存上下文文件和嵌入,就必须使用远程向量数据库。
一旦你对 API 感到满意,将更改提交到 git
git add .
git commit -m "API Works"
运行此命令:
space new
这将在项目中创建一个新的 SpaceFile。打开此文件并用以下内容覆盖它:
# Spacefile Docs: https://go.deta.dev/docs/spacefile/v0
v: 0
micros:
- name: LangChainAPI
src: ./
engine: python3.9
primary: true
run: uvicorn app.main:app
presets:
env:
- name: OPENAI_API_KEY
description: Secret message only available to this Micro
default: "OpenAPI Key"
api_keys: true
保存文件并在终端中运行此命令。
space push
这将在 Deta Space 仪表板上创建一个 API 实例。在本例中,它被称为 "gpt_server"。在你的情况下,它将是 "LangChainAPI"。
进入实例设置,从 "Configurations" 选项卡添加你的 OpenAI API 密钥。然后,进入 domains 选项卡并获取你的 API 的基本 URL。你可以先在浏览器中使用 Swagger 文档对其进行测试,然后在你的应用中将其用作 REST API。