You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Flask+LangChain+OpenAI的应用本地正常,部署Azure后无法读取文本文件

问题描述

我开发了一个基于Flask、LangChain和ChatGPT API的应用,能够从本地text.txt文件中查询数据并返回对应结果。本地运行时一切正常,但部署到Azure App Service后,应用虽能启动,却无法读取文本文件,所有查询都返回通用回答而非基于文件内容的结果。

相关代码如下:

from flask import Flask, render_template, request
import os
import langchain
from langchain.chains import ConversationalRetrievalChain
from langchain.chat_models import ChatOpenAI
from langchain.document_loaders import DirectoryLoader, TextLoader
from langchain.embeddings import OpenAIEmbeddings
from langchain.indexes import VectorstoreIndexCreator
from langchain.indexes.vectorstore import VectorStoreIndexWrapper
from langchain.indexes.vectorstore import Chroma
import myconstant

# Set the OPENAI API Key
os.environ["OPENAI_API_KEY"] = myconstant.APIKEY

# Configure whether to persist the index
PERSIST = True

app = Flask(__name__)

query = None
chat_history = []

@app.route('/')
@app.route('/index')
def index():
    return render_template('index.html', query=query)

@app.route('/', methods=['POST'])
def process_query():
    global query
    global chat_history

    query = request.form['query']

    if query in ['quit', 'q', 'exit']:
        return "Goodbye!"

    # Load index from persistence or create a new one
    if PERSIST and os.path.exists("persist"):
        vectorstore = Chroma(persist_directory="persist", embedding_function=OpenAIEmbeddings())
        index = VectorStoreIndexWrapper(vectorstore=vectorstore)
    else:
        loader = TextLoader("test.txt", encoding="utf-8")

        if PERSIST:
            # Create an index with persistence
            index = VectorstoreIndexCreator(vectorstore_kwargs={"persist_directory": "persist"}).from_loaders([loader])
        else:
            # Create an index without persistence
            index = VectorstoreIndexCreator().from_loaders([loader])

    # Create a conversational retrieval chain using the specified LLM model and index retriever
    chain = ConversationalRetrievalChain.from_llm(
        llm=ChatOpenAI(model="gpt-3.5-turbo"),
        retriever=index.vectorstore.as_retriever(search_kwargs={"k": 1}),
    )

    # Generate an answer using the conversational chain
    result = chain({"question": query, "chat_history": chat_history})

    # Add the query and answer to chat history
    chat_history.append((query, result['answer']))

    return render_template('index.html', query=query, result=result['answer'])

if __name__ == '__main__':
    app.run(debug=True)

可能的原因

  • 文件路径不匹配:Azure App Service的工作目录与本地不同,直接使用相对路径"test.txt"会导致文件找不到。
  • 文件未部署:text.txt未被包含在Azure部署包中,服务器上不存在该文件。
  • 持久化目录权限问题:Azure App Service对默认本地目录的写入/读取权限有限,persist目录无法正常创建或读取。

解决方案

1. 使用绝对路径定位文本文件

依赖Flask的app.root_path获取应用根目录,拼接出text.txt的绝对路径,避免相对路径的不确定性:

# 替换原loader初始化代码
loader = TextLoader(os.path.join(app.root_path, "test.txt"), encoding="utf-8")

2. 确保text.txt被部署到Azure

  • 若用Git部署,检查.gitignore文件,确认未忽略text.txt;
  • 若用Zip部署,打包时务必包含text.txt;
  • 可通过Azure Portal的「App Service -> 高级工具 -> Kudu -> 控制台」,查看站点根目录下是否存在text.txt,验证部署结果。

3. 调整持久化索引的存储位置

Azure App Service中仅/home目录支持持久化存储,将persist目录迁移到该路径:

# 修改持久化目录配置
PERSIST_DIR = os.path.join(os.environ.get("HOME", ""), "persist")

# 替换代码中所有"persist"路径为PERSIST_DIR
if PERSIST and os.path.exists(PERSIST_DIR):
    vectorstore = Chroma(persist_directory=PERSIST_DIR, embedding_function=OpenAIEmbeddings())
    index = VectorStoreIndexWrapper(vectorstore=vectorstore)
else:
    loader = TextLoader(os.path.join(app.root_path, "test.txt"), encoding="utf-8")
    if PERSIST:
        index = VectorstoreIndexCreator(vectorstore_kwargs={"persist_directory": PERSIST_DIR}).from_loaders([loader])
    else:
        index = VectorstoreIndexCreator().from_loaders([loader])

4. 添加日志排查问题

在代码中加入日志,确认文件路径和存在性:

import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 在process_query函数中添加日志
file_path = os.path.join(app.root_path, "test.txt")
logger.info(f"尝试加载文件路径:{file_path}")
logger.info(f"文件是否存在:{os.path.exists(file_path)}")

之后通过Azure Portal的「App Service -> 日志流」查看日志,定位具体问题。

内容的提问来源于stack exchange,提问作者Nina

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 11:53:16