您是否尝试过构建自己的大型语言模型 (LLM) 应用程序?您是否想过人们是如何通过构建自己的 LLM 应用程序来提高工作效率的?LLM 应用程序已被证明在各个方面都非常有用。如今,构建 LLM 应用程序已变得触手可及。这要归功于 AI 模型和强大框架的普及。在本教程中,我们将以尽可能简单的方式构建我们的第一个 LLM 应用程序。让我们开始这个过程。我们将逐一深入探讨从构思到代码再到部署的每个流程。
为什么LLM应用如此重要?
LLM 应用的独特之处在于它们使用自然语言来处理用户问题,并以自然语言进行响应。此外,LLM 应用能够感知用户查询的上下文并进行相应的回答。LLM 应用的常见用例包括聊天机器人、内容生成和问答代理。它通过整合对话式 AI(当今 AI 领域的驱动力)显著提升用户体验。
LLM应用的关键组件
创建 LLM 应用涉及创建 LLM 应用不同组件的步骤。最终,我们将使用这些组件构建一个功能齐全的应用程序。让我们逐一了解这些组件,以全面理解每个组件。
- 基础模型:这涉及选择将在应用程序后端使用的基础 AI 模型或 LLM。您可以将其视为应用程序的大脑。
- 快速工程:这是最重要的组件,它为您的 LLM 应用提供上下文。这包括定义你的 LLM 的语气、个性和角色,以便它能够做出相应的回答。
- 编排层:像 Langchain、LlamaIndex 这样的框架充当编排层,处理所有 LLM 调用并输出到你的应用程序。这些框架将你的应用程序与 LLM 绑定,以便你可以轻松访问 AI 模型。
- 工具:工具是构建 LLM 应用程序时最重要的组件。LLM 通常使用这些工具来执行 AI 模型无法直接执行的任务。
选择合适的工具
选择合适的工具是创建 LLM 应用程序最重要的任务之一。人们经常跳过这一步,直接使用任何可用的工具从头开始构建 LLM 应用程序。这种方法非常模糊。在进入开发阶段之前,应该有效地定义工具。让我们来定义我们的工具。
- 选择 LLM:LLM 是你应用程序背后的核心。选择合适的 LLM 是至关重要的一步,需要考虑成本和可用性参数。您可以使用 OpenAI、Groq 和 Google 的 LLM。您必须从他们的平台获取 API 密钥才能使用这些 LLM。
- 框架:框架充当您的应用程序和 LLM 之间的集成。它帮助我们简化对 LLM 的提示,链接定义应用程序工作流程的逻辑。像 Langchain 和 LlamaIndex 这样的框架被广泛用于创建 LLM 应用程序。Langchain 被认为是最适合初学者且最容易使用的框架。
- 前端库:Python 为以尽可能少的代码为您的应用程序构建前端提供了良好的支持。Streamlit、Gradio 和 Chainlit 等库能够以最少的代码为您的 LLM 应用程序提供漂亮的前端。
分步实施
我们已经介绍了构建 LLM 应用程序的所有基本先决条件。让我们开始实际实施,并从头开始编写开发 LLM 应用程序的代码。在本指南中,我们将创建一个 LLM 应用程序,该应用程序接收查询作为输入,将查询分解为多个子部分,搜索互联网,然后将结果编译成美观的 Markdown 报告,并包含所使用的参考文献。
1. 设置Python及其环境
第一步是从 Python 官方网站下载并安装 Python 解释器。安装时,请记得勾选/选择“Add PATH VARIABLE to the system”选项。
此外,请在命令行中输入 python
来确认您已安装 Python。
2. 安装所需的依赖项
此步骤将库依赖项安装到您的系统中。打开终端并输入以下命令来安装依赖项。
pip install streamlit dotenv langchain langchain-openai langchain-community langchain-core
此命令将运行终端并安装运行应用程序所需的所有依赖项。
3. 导入所有依赖项
安装依赖项后,转到 IDE 代码编辑器(例如 VS Code),并在所需路径中打开它。现在,创建一个 Python 文件“app.py”,并将以下导入语句粘贴到文件中
import streamlit as st import os from dotenv import load_dotenv from langchain_openai import ChatOpenAI from langchain_community.tools.tavily_search import TavilySearchResults from langchain.agents import AgentExecutor, create_tool_calling_agent from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder from langchain_core.messages import AIMessage, HumanMessage
4. 环境设置
我们为 LLM 和其他工具创建一些环境变量。为此,请在同一目录中创建一个“.env”文件,并使用环境变量将 API 密钥粘贴到其中。例如,在我们的 LLM 应用程序中,我们将使用两个 API 密钥:一个用于 LLM 的 OpenAI API 密钥(可从此处访问);以及一个用于实时搜索互联网的 Tavily API 密钥(可从此处访问)。
OPENAI_API_KEY="Your_API_Key" TAVILY_API_KEY="Your_API_Key"
现在,在你的 app.py 中,编写以下代码。此代码将把所有可用的环境变量直接加载到你的工作环境中。
# --- ENVIRONMENT SETUP --- load_dotenv() OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") TAVILY_API_KEY = os.getenv("TAVILY_API_KEY") if not OPENAI_API_KEY: st.error("🚨 OpenAI API key not found. Please set it in your .env file (OPENAI_API_KEY='sk-...')") if not TAVILY_API_KEY: st.error("🚨 Tavily API key not found. Please set it in your .env file (TAVILY_API_KEY='tvly-...')") if not OPENAI_API_KEY or not TAVILY_API_KEY: st.stop()
5. 代理设置
所有环境变量都已加载完毕。接下来,让我们创建代理工作流,在使用 LLM 应用程序时,每个查询都会经过该工作流。这里我们将创建一个工具,即 Tavily 搜索,用于搜索互联网。此外,我们还将创建一个代理执行器,用于使用工具执行代理。
# --- AGENT SETUP --- @st.cache_resource def get_agent_executor(): """ Initializes and returns the LangChain agent executor. """ # 1. Define the LLM llm = ChatOpenAI(model="gpt-4o-mini", temperature=0.2, api_key=OPENAI_API_KEY) # 2. Define Tools (simplified declaration) tools = [ TavilySearchResults( max_results=7, name="web_search", api_key=TAVILY_API_KEY, description="Performs web searches to find current information" ) ] # 3. Updated Prompt Template (v0.3 best practices) prompt_template = ChatPromptTemplate.from_messages( [ ("system", """ You are a world-class research assistant AI. Provide comprehensive, accurate answers with Markdown citations. Process: 1. Decomplexify questions into sub-queries 2. Use `web_search` for each sub-query 3. Synthesize information 4. Cite sources using Markdown footnotes 5. Include reference list Follow-up questions should use chat history context. """), MessagesPlaceholder("chat_history", optional=True), ("human", "{input}"), MessagesPlaceholder("agent_scratchpad"), ] ) # 4. Create agent (updated to create_tool_calling_agent) agent = create_tool_calling_agent(llm, tools, prompt_template) # 5. AgentExecutor with modern configuration return AgentExecutor( agent=agent, tools=tools, verbose=True, handle_parsing_errors=True, max_iterations=10, return_intermediate_steps=True )
这里我们使用了一个提示模板,用于指导 GPT-4O-mini LLM 的学习,包括如何进行搜索部分以及如何编写包含参考文献的报告。此部分负责你的 LLM 申请的所有后端工作。此部分的任何更改都将直接影响你的 LLM 申请结果。
6. Streamlit UI
我们已经为 LLM 申请设置了所有后端逻辑。现在,让我们为应用程序创建 UI,它将负责应用程序的前端视图。
# --- STREAMLIT UI --- st.set_page_config(page_title="AI Research Agent 📚", page_icon="🤖", layout="wide") st.markdown(""" <style> .stChatMessage { border-radius: 10px; padding: 10px; margin-bottom: 10px; } .stChatMessage.user { background-color: #E6F3FF; } .stChatMessage.assistant { background-color: #F0F0F0; } </style> """, unsafe_allow_html=True) st.title("📚 AI Research Agent") st.caption("Your advanced AI assistant to search the web, synthesize information, and provide cited answers.") if "chat_history" not in st.session_state: st.session_state.chat_history = [] for message_obj in st.session_state.chat_history: role = "user" if isinstance(message_obj, HumanMessage) else "assistant" with st.chat_message(role): st.markdown(message_obj.content) user_query = st.chat_input("Ask a research question...") if user_query: st.session_state.chat_history.append(HumanMessage(content=user_query)) with st.chat_message("user"): st.markdown(user_query) with st.chat_message("assistant"): with st.spinner("🧠 Thinking & Researching..."): try: agent_executor = get_agent_executor() response = agent_executor.invoke({ "input": user_query, "chat_history": st.session_state.chat_history[:-1] }) answer = response["output"] st.session_state.chat_history.append(AIMessage(content=answer)) st.markdown(answer) except Exception as e: error_message = f"😕 Apologies, an error occurred: {str(e)}" st.error(error_message) print(f"Error during agent invocation: {e}")
在本节中,我们将定义应用程序的标题、标题、描述和聊天记录。Streamlit 提供了许多自定义功能来定制我们的应用程序。我们在这里使用了少量的自定义选项,以降低应用程序的复杂性。您可以根据自己的需求自由定制应用程序。
7. 运行应用程序
我们已经定义了应用程序的所有部分,现在可以启动了。让我们直观地查看我们创建的内容并分析结果。
打开终端并输入
streamlit run app.py
这将初始化您的应用程序,并且您将被重定向到您的默认浏览器。
这是您的 LLM 应用程序的 UI:
让我们对我们的LLM应用程序进行测试
查询:“What is the latest langchain documentation version?”
查询:“How langchain is changing the game of AI?”
从输出结果中,我们可以看到我们的 LLM 应用程序显示出了预期的结果。详细的结果包含参考链接。任何人都可以点击这些参考链接,访问我们的 LLM 程序解答问题的上下文。至此,我们成功创建了我们的第一个 LLM 应用程序。您可以随意修改此代码,并以此代码为参考,创建一些更复杂的应用程序。
小结
创建 LLM 应用程序比以往任何时候都更容易。如果您正在阅读本文,则意味着您拥有足够的知识来创建自己的 LLM 应用程序。在本指南中,我们介绍了环境设置、代码编写、代理逻辑、应用程序 UI 定义,以及将其转换为 Streamlit 应用程序。这涵盖了开发 LLM 应用程序的所有主要步骤。您可以尝试使用提示模板、LLM 链和 UI 自定义,根据您的需求个性化您的应用程序。这仅仅是个开始;更丰富的 AI 工作流正在等着您,包括代理、内存和特定领域任务。
常见问题解答
Q1. 我需要从头开始训练模型吗?
A. 不需要,您可以从预训练的 LLM(例如 GPT 或开源 LLM)开始,专注于提示设计和应用逻辑。
Q2. 为什么要使用像 LangChain 这样的框架?
A. 它们简化了链接提示、内存处理和工具集成,而无需重新设计轮子。
Q3. 如何添加对话内存?
A. 在框架(例如 LangChain)中使用缓冲内存类或集成向量数据库进行检索。
Q4. 什么是 RAG?为什么要使用它?
A. 检索增强生成 (RAG) 将外部数据引入模型的上下文中,从而提高特定领域查询的响应准确性。
Q5. 我可以在哪里部署我的 LLM 应用?
A. 首先使用 Gradio 进行本地演示,然后使用 Hugging Face Spaces、Streamlit Cloud、Heroku、Docker 或云平台进行扩展。
评论留言