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

如何在Azure Function API中返回LangChain生成的可视化图表

问题

我基于LangChain和OpenAI开发了一段CSV数据分析的Azure Function API代码,目前可以正常返回文本分析结果,但当用户请求生成图表时,不知道如何将图表结果通过API返回。现有代码如下:

def main(req: func.HttpRequest) -> func.HttpResponse:
    try:
        req_body = req.get_json()
        query = req_body.get('query')
        if not query:
            return func.HttpResponse(
                "Please provide a 'query' parameter in the request.",
                status_code=400
            )        
        blob_service_client = BlobServiceClient.from_connection_string(azure_connection_string)
        container_client = blob_service_client.get_container_client(container_name)
        blob_list = container_client.list_blobs()
        csv_files = [blob.name for blob in blob_list if blob.name.lower().endswith('.csv')]
        latest_csv = max(csv_files, key=lambda blob_name: container_client.get_blob_client(blob_name).get_blob_properties().last_modified)
        with tempfile.NamedTemporaryFile(delete=False) as temp_file:
            temp_filename = temp_file.name
            blob_client = container_client.get_blob_client(latest_csv)
            blob_data = blob_client.download_blob()
            temp_file.write(blob_data.readall())
        df = pd.read_csv(temp_filename)
        df = df.replace(0, np.nan)      
        agent = create_pandas_dataframe_agent(
            ChatOpenAI(temperature=0, engine="gpt3516k"),
            df,
            verbose=True,
            agent_type=AgentType.OPENAI_FUNCTIONS,
            )
        result = agent.run(query)
        image_bytes = "No result"
        final_result = json.dumps({"text":[{"message":query,"text_response": result,"sources":"","suggested_queries":"","graph":image_bytes}]})
        return func.HttpResponse(final_result, mimetype='application/json')
    except Exception as e:
        return func.HttpResponse(
            f"An error occurred: {str(e)}",
            status_code=500
        )
解决方案

要实现图表返回,核心是把生成的图表转换成可嵌入JSON的格式(比如Base64编码字符串),同时扩展LangChain Agent的能力以支持调用画图函数。具体步骤如下:

1. 添加图表生成工具函数

定义生成图表的函数,使用matplotlib实现(需确保Function环境安装matplotlib依赖),并设置非交互式后端避免环境报错:

import matplotlib.pyplot as plt
import base64
from io import BytesIO

# 设置matplotlib非交互式后端,适配Azure Function无图形界面环境
plt.switch_backend('Agg')

def generate_chart(df, chart_type, x_col, y_col, title):
    """生成指定类型的图表并返回Base64编码字符串"""
    plt.figure(figsize=(10,6))
    
    if chart_type == 'bar':
        plt.bar(df[x_col], df[y_col])
    elif chart_type == 'line':
        plt.plot(df[x_col], df[y_col])
    elif chart_type == 'scatter':
        plt.scatter(df[x_col], df[y_col])
    else:
        return "Unsupported chart type"
    
    plt.title(title)
    plt.xlabel(x_col)
    plt.ylabel(y_col)
    
    # 将图表转为字节流,再编码为Base64字符串
    buffer = BytesIO()
    plt.savefig(buffer, format='png')
    buffer.seek(0)
    img_base64 = base64.b64encode(buffer.getvalue()).decode('utf-8')
    plt.close()  # 关闭图表释放内存资源
    
    return img_base64

2. 将工具函数注册到LangChain Agent

用@tool装饰器把画图函数注册为Agent可调用的工具,让Agent能识别并执行图表生成请求:

from langchain.tools import tool

@tool
def generate_chart_tool(df: pd.DataFrame, chart_type: str, x_col: str, y_col: str, title: str) -> str:
    """
    生成数据图表
    参数:
    - df: 输入的DataFrame
    - chart_type: 图表类型,可选值: bar, line, scatter
    - x_col: X轴对应的列名
    - y_col: Y轴对应的列名
    - title: 图表标题
    返回: 图表的Base64编码字符串
    """
    return generate_chart(df, chart_type, x_col, y_col, title)

# 初始化Agent时传入自定义工具列表
agent = create_pandas_dataframe_agent(
    ChatOpenAI(temperature=0, engine="gpt3516k"),
    df,
    verbose=True,
    agent_type=AgentType.OPENAI_FUNCTIONS,
    tools=[generate_chart_tool]  # 添加图表生成工具
)

3. 修改结果处理与返回逻辑

调整结果解析逻辑,区分文本响应和图表响应,将Base64编码的图表字符串嵌入返回的JSON中:

# 运行Agent获取结果
result = agent.run(query)

# 初始化图表Base64字符串
image_base64 = "No result"

# 判断返回结果是否为图表Base64(可根据实际情况调整判断逻辑)
if isinstance(result, str):
    # 若Agent直接返回Base64,添加图片前缀方便前端解析
    if len(result) > 1000 and not result.startswith('data:image'):
        image_base64 = f'data:image/png;base64,{result}'
    elif result.startswith('data:image/png;base64,'):
        image_base64 = result

# 构造最终返回的JSON结构
final_result = json.dumps({
    "text": [{
        "message": query,
        "text_response": "图表已生成" if image_base64 != "No result" else result,
        "sources": "",
        "suggested_queries": "",
        "graph": image_base64
    }]
})

return func.HttpResponse(final_result, mimetype='application/json')

4. 配置依赖

确保Azure Function的requirements.txt包含以下必要依赖:

azure-functions
azure-storage-blob
pandas
numpy
langchain
langchain-openai
matplotlib
注意事项
  • 若图表生成耗时较长,需在Azure Function配置中调整超时时间(默认5分钟)
  • 大型图表的Base64字符串会增大JSON体积,这种情况下可改为将图表上传至Azure Blob存储,返回Blob的访问URL
  • 用户查询需明确要求生成图表(比如“生成月度销量的柱状图”),Agent才能触发工具调用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 04:55:34