AI百事通

从零搭建AI聊天机器人:基于LangChain和GPT-4o实战教程

📅 2026-06-26📰 ai_generated👁 1 次阅读
从零搭建AI聊天机器人:基于LangChain和GPT-4o实战教程
AI教程LangChainGPT-4o聊天机器人实战Python

引言

聊天机器人是AI应用中最常见的场景之一。借助LangChain和GPT-4o,我们可以快速构建一个功能强大的聊天机器人。本教程将带你从零开始,实现一个具备记忆能力的智能助手。

环境准备

安装依赖

pip install langchain openai python-dotenv

获取API Key

登录OpenAI平台,创建API Key,并保存到.env文件:

OPENAI_API_KEY=your_api_key_here

基本聊天功能

创建LLM实例

from langchain.llms import OpenAI
from dotenv import load_dotenv

load_dotenv()

llm = OpenAI(model="gpt-4o", temperature=0.7)

简单对话

response = llm("Hello, who are you?")
print(response)

添加记忆功能

使用ConversationBufferMemory来记住对话历史。

from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationChain

memory = ConversationBufferMemory()
conversation = ConversationChain(
    llm=llm,
    memory=memory,
    verbose=True
)

conversation.predict(input="Hi, my name is Alice.")
conversation.predict(input="What is my name?")

自定义Prompt模板

为了让机器人更专业,我们可以设计特定的Prompt模板。

from langchain.prompts import PromptTemplate

template = """You are a helpful assistant specialized in technology. 
Current conversation:
{history}
Human: {input}
AI:"""

prompt = PromptTemplate(
    input_variables=["history", "input"],
    template=template
)

conversation = ConversationChain(
    llm=llm,
    memory=memory,
    prompt=prompt
)

添加工具(可选)

通过LangChain的Tool功能,可以让机器人调用外部API,比如查询天气。

from langchain.tools import Tool
from langchain.agents import initialize_agent, AgentType

def get_weather(city):
    # 调用天气API的代码
    return f"The weather in {city} is sunny."

tools = [
    Tool(
        name="Weather",
        func=get_weather,
        description="Get weather for a city"
    )
]

agent = initialize_agent(
    tools,
    llm,
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
    verbose=True
)

agent.run("What's the weather in Beijing?")

部署为Web服务

使用Flask或FastAPI将聊天机器人封装为API。

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route("/chat", methods=["POST"])
def chat():
    data = request.json
    user_input = data["message"]
    response = conversation.predict(input=user_input)
    return jsonify({"reply": response})

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)

完整代码

以上片段组合起来即可得到一个完整的聊天机器人。你可以在此基础上扩展更多功能,比如多轮对话优化、上下文窗口管理等。

总结

通过本教程,你学会了使用LangChain和GPT-4o构建聊天机器人的核心步骤。从基本对话到记忆功能,再到工具集成和部署,你已经具备了开发实际应用的能力。快去动手试试吧!