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

FastAPI与LangGraph集成异常:无法通过接口传入输入参数并触发工作流

FastAPI与LangGraph集成异常:无法通过接口传入输入参数并触发工作流

看起来你遇到的核心问题是FastAPI接口没正确配置请求参数,导致Swagger Docs里找不到输入区域,同时还需要把前端(比如HTML搜索框)的输入正确传递给LangGraph工作流。我来一步步帮你解决:

1. 先排查FastAPI接口的参数定义问题

你当前的接口大概率没明确声明要接收的输入参数,或者参数类型配置不对。比如如果是直接写了无参数的接口,Swagger自然不会显示输入框:

# 错误示范:无参数接口,Swagger找不到输入入口
@app.get("/generate")
def generate():
    result = graph.invoke(...)
    return result

2. 正确定义接收输入的FastAPI接口

首先要和LangGraph的输入格式对齐,用Pydantic模型规范输入结构,再写对应的接口:

步骤1:定义输入模型

from pydantic import BaseModel

# 对应你LangGraph里inp函数的输入结构
class QueryInput(BaseModel):
    question: str

步骤2:编写POST接口(推荐用于提交数据)

@app.post("/generate")
def run_langgraph_workflow(input_data: QueryInput):
    # 转换成LangGraph需要的输入格式(和你之前输出里的结构一致)
    langgraph_input = {"question": [input_data.question]}
    # 触发LangGraph工作流
    workflow_result = graph.invoke(langgraph_input)
    return workflow_result

可选:如果要用GET接口(配合HTML搜索框的GET请求)

@app.get("/generate")
def run_langgraph_workflow(question: str):
    langgraph_input = {"question": [question]}
    workflow_result = graph.invoke(langgraph_input)
    return workflow_result

修改后刷新Swagger Docs,就能看到对应的输入框,点击「Try it out」就能输入参数测试了。

3. 对接HTML搜索框的前端逻辑

假设你有一个简单的HTML页面,用JavaScript发送请求到FastAPI接口:

<input type="text" id="questionInput" placeholder="输入你的问题">
<button onclick="submitQuery()">提交</button>
<div id="resultContainer"></div>

<script>
async function submitQuery() {
    const question = document.getElementById('questionInput').value;
    try {
        const response = await fetch('/generate', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({question: question}),
        });
        const result = await response.json();
        document.getElementById('resultContainer').textContent = JSON.stringify(result, null, 2);
    } catch (error) {
        console.error('请求失败:', error);
    }
}
</script>

这样用户在搜索框输入内容后,点击按钮就能把参数传给FastAPI,触发LangGraph工作流并展示结果。

4. 验证LangGraph的输入格式匹配度

确保你传给graph.invoke()的输入结构和LangGraph定义的完全一致——从你之前的输出能看到格式是{'question': ['helo']},所以要把输入转成列表形式,别直接传字符串,避免工作流报错。

备注:内容来源于stack exchange,提问作者user113156

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.16 08:24:29