快速开始
通过加载模板 flow、运行它,然后在 /run
API 端点提供服务来开始使用 Langflow。
先决条件
-
创建 Langflow API 密钥
Langflow API 密钥是您可以与 Langflow 一起使用的用户特定 token。
要创建 Langflow API 密钥,请执行以下操作:
-
在 Langflow 中,点击您的用户图标,然后选择设置。
-
点击 Langflow API Keys,然后点击 Add New。
-
为您的密钥命名,然后点击 Create API Key。
-
复制 API 密钥并安全存储。
-
要在请求中使用您的 Langflow API 密钥,请在终端中设置
LANGFLOW_API_KEY
环境变量,然后在请求中包含x-api-key
头部或查询参数。 例如:_13# Set variable_13export LANGFLOW_API_KEY="sk..."_13_13# Send request_13curl --request POST \_13--url 'http://LANGFLOW_SERVER_ADDRESS/api/v1/run/FLOW_ID' \_13--header 'Content-Type: application/json' \_13--header 'x-api-key: LANGFLOW_API_KEY' \_13--data '{_13"output_type": "chat",_13"input_type": "chat",_13"input_value": "Hello"_13}'
-
运行 Simple Agent 模板 flow
- 在 Langflow 中,点击 New Flow,然后选择 Simple Agent 模板。
Simple Agent flow 由连接到 Chat I/O 组件、Calculator 组件和 URL 组件 的 Agent 组件组成。当您运行此 flow 时,您通过 Chat Input 组件向 Agent 提交查询,Agent 使用 Calculator 和 URL 工具生成响应,然后通过 Chat Output 组件返回响应。
许多组件都可以作为 Agent 的工具,包括 Model Context Protocol (MCP) 服务器。Agent 根据给定查询的上下文决定调用哪些工具。
-
在 Agent 组件的设置中,在 OpenAI API Key 字段中,直接输入您的 OpenAI API 密钥,或点击 Globe 来创建全局变量。
此指南使用 OpenAI 模型作为演示目的。如果您想使用不同的提供商,请更改 Model Provider 和 Model Name 字段,然后为您选择的提供商提供凭据。
-
要运行 flow,请点击 Playground。
-
要测试 Calculator 工具,请向 Agent 问一个简单的数学问题,例如
I want to add 4 and 4.
为了帮助您测试和评估您的 flow,Playground 展示了 Agent 在分析提示、选择工具、然后使用工具生成响应时的推理过程。 在这种情况下,数学问题使 Agent 选择 Calculator 工具并使用像evaluate_expression
这样的操作。
-
要测试 URL 工具,请向 Agent 询问当前事件。 对于此请求,Agent 选择 URL 工具的
fetch_content
操作,然后返回当前新闻头条的摘要。 -
当您完成 flow 测试后,点击 Close。
现在您已经运行了第一个 flow,试试这些下一步:
- 通过附加不同的工具或向 flow 添加更多组件来编辑您的 Simple Agent flow。
- 从头开始或通过修改其他模板 flow 来构建您自己的 flow。
- 将 flow 集成到您的应用程序中,如从外部应用程序运行您的 flow 中所解释的。
从外部应用程序运行您的 flow
Langflow 是一个 IDE,但它也是一个运行时,您可以通过 Python、JavaScript 或 HTTP 使用 Langflow API 调用它。
当您在本地启动 Langflow 时,您可以向本地 Langflow 服务器发送请求。 对于生产应用程序,您需要部署稳定的 Langflow 实例来处理 API 调用。
例如,您可以使用 /run
端点运行 flow 并获得结果。
Langflow 提供代码片段来帮助您开始使用 Langflow API。
-
要打开 API 访问面板,在 Playground 中点击 Share,然后 点击 API access。
API 访问面板中的默认代码使用 Langflow 服务器
url
、headers
和请求数据的payload
构造请求。 代码片段自动包含 flow 的LANGFLOW_SERVER_ADDRESS
和FLOW_ID
值,以及如果您在终端会话中将其设置为环境变量,则包含您的LANGFLOW_API_KEY
的脚本。 如果您为不同的服务器或 flow 使用代码,请替换这些值。 默认的 Langflow 服务器地址是http://localhost:7860
。- Python
- JavaScript
- curl
_29import requests_29_29url = "http://LANGFLOW_SERVER_ADDRESS/api/v1/run/FLOW_ID" # The complete API endpoint URL for this flow_29_29# Request payload configuration_29payload = {_29"output_type": "chat",_29"input_type": "chat",_29"input_value": "hello world!"_29}_29_29# Request headers_29headers = {_29"Content-Type": "application/json",_29"x-api-key": "$LANGFLOW_API_KEY"_29}_29_29try:_29# Send API request_29response = requests.request("POST", url, json=payload, headers=headers)_29response.raise_for_status() # Raise exception for bad status codes_29_29# Print response_29print(response.text)_29_29except requests.exceptions.RequestException as e:_29print(f"Error making API request: {e}")_29except ValueError as e:_29print(f"Error parsing response: {e}")_20const payload = {_20"output_type": "chat",_20"input_type": "chat",_20"input_value": "hello world!",_20"session_id": "user_1"_20};_20_20const options = {_20method: 'POST',_20headers: {_20'Content-Type': 'application/json',_20'x-api-key': 'LANGFLOW_API_KEY'_20},_20body: JSON.stringify(payload)_20};_20_20fetch('http://LANGFLOW_SERVER_ADDRESS/api/v1/run/FLOW_ID', options)_20.then(response => response.json())_20.then(response => console.log(response))_20.catch(err => console.error(err));_11curl --request POST \_11--url 'http://LANGFLOW_SERVER_ADDRESS/api/v1/run/FLOW_ID?stream=false' \_11--header 'Content-Type: application/json' \_11--header "x-api-key: LANGFLOW_API_KEY" \_11--data '{_11"output_type": "chat",_11"input_type": "chat",_11"input_value": "hello world!"_11}'_11_11# A 200 response confirms the call succeeded. -
复制片段,将其粘贴到脚本文件中,然后运行脚本发送请求。 如果您使用 curl 片段,您可以直接在终端中运行命令。
如果请求成功,响应包含关于 flow 运行的许多详细信息,包括会话 ID、输入、输出、组件、持续时间等。 以下是运行 Simple Agent 模板 flow 的响应示例:
Result
_162{_162 "session_id": "29deb764-af3f-4d7d-94a0-47491ed241d6",_162 "outputs": [_162 {_162 "inputs": {_162 "input_value": "hello world!"_162 },_162 "outputs": [_162 {_162 "results": {_162 "message": {_162 "text_key": "text",_162 "data": {_162 "timestamp": "2025-06-16 19:58:23 UTC",_162 "sender": "Machine",_162 "sender_name": "AI",_162 "session_id": "29deb764-af3f-4d7d-94a0-47491ed241d6",_162 "text": "Hello world! 🌍 How can I assist you today?",_162 "files": [],_162 "error": false,_162 "edit": false,_162 "properties": {_162 "text_color": "",_162 "background_color": "",_162 "edited": false,_162 "source": {_162 "id": "Agent-ZOknz",_162 "display_name": "Agent",_162 "source": "gpt-4o-mini"_162 },_162 "icon": "bot",_162 "allow_markdown": false,_162 "positive_feedback": null,_162 "state": "complete",_162 "targets": []_162 },_162 "category": "message",_162 "content_blocks": [_162 {_162 "title": "Agent Steps",_162 "contents": [_162 {_162 "type": "text",_162 "duration": 2,_162 "header": {_162 "title": "Input",_162 "icon": "MessageSquare"_162 },_162 "text": "**Input**: hello world!"_162 },_162 {_162 "type": "text",_162 "duration": 226,_162 "header": {_162 "title": "Output",_162 "icon": "MessageSquare"_162 },_162 "text": "Hello world! 🌍 How can I assist you today?"_162 }_162 ],_162 "allow_markdown": true,_162 "media_url": null_162 }_162 ],_162 "id": "f3d85d9a-261c-4325-b004-95a1bf5de7ca",_162 "flow_id": "29deb764-af3f-4d7d-94a0-47491ed241d6",_162 "duration": null_162 },_162 "default_value": "",_162 "text": "Hello world! 🌍 How can I assist you today?",_162 "sender": "Machine",_162 "sender_name": "AI",_162 "files": [],_162 "session_id": "29deb764-af3f-4d7d-94a0-47491ed241d6",_162 "timestamp": "2025-06-16T19:58:23+00:00",_162 "flow_id": "29deb764-af3f-4d7d-94a0-47491ed241d6",_162 "error": false,_162 "edit": false,_162 "properties": {_162 "text_color": "",_162 "background_color": "",_162 "edited": false,_162 "source": {_162 "id": "Agent-ZOknz",_162 "display_name": "Agent",_162 "source": "gpt-4o-mini"_162 },_162 "icon": "bot",_162 "allow_markdown": false,_162 "positive_feedback": null,_162 "state": "complete",_162 "targets": []_162 },_162 "category": "message",_162 "content_blocks": [_162 {_162 "title": "Agent Steps",_162 "contents": [_162 {_162 "type": "text",_162 "duration": 2,_162 "header": {_162 "title": "Input",_162 "icon": "MessageSquare"_162 },_162 "text": "**Input**: hello world!"_162 },_162 {_162 "type": "text",_162 "duration": 226,_162 "header": {_162 "title": "Output",_162 "icon": "MessageSquare"_162 },_162 "text": "Hello world! 🌍 How can I assist you today?"_162 }_162 ],_162 "allow_markdown": true,_162 "media_url": null_162 }_162 ],_162 "duration": null_162 }_162 },_162 "artifacts": {_162 "message": "Hello world! 🌍 How can I assist you today?",_162 "sender": "Machine",_162 "sender_name": "AI",_162 "files": [],_162 "type": "object"_162 },_162 "outputs": {_162 "message": {_162 "message": "Hello world! 🌍 How can I assist you today?",_162 "type": "text"_162 }_162 },_162 "logs": {_162 "message": []_162 },_162 "messages": [_162 {_162 "message": "Hello world! 🌍 How can I assist you today?",_162 "sender": "Machine",_162 "sender_name": "AI",_162 "session_id": "29deb764-af3f-4d7d-94a0-47491ed241d6",_162 "stream_url": null,_162 "component_id": "ChatOutput-aF5lw",_162 "files": [],_162 "type": "text"_162 }_162 ],_162 "timedelta": null,_162 "duration": null,_162 "component_display_name": "Chat Output",_162 "component_id": "ChatOutput-aF5lw",_162 "used_frozen_result": false_162 }_162 ]_162 }_162 ]_162}
在生产应用程序中,您可能希望选择此响应的部分内容返回给用户、存储在日志中等等。下一步骤演示了如何从 Langflow API 响应中提取数据以在您的应用程序中使用。
从响应中提取数据
以下示例基于 API 面板的示例代码,在您的终端中创建一个存储 Agent 上一个答案的问答聊天。
-
将您的 Simple Agent flow 的
/run
片段合并到以下脚本中。 此脚本在您的终端中运行问答聊天,并存储 Agent 的上一个答案,以便您可以比较它们。- Python
- JavaScript
_59import requests_59import json_59_59url = "http://LANGFLOW_SERVER_ADDRESS/api/v1/run/FLOW_ID"_59_59def ask_agent(question):_59payload = {_59"output_type": "chat",_59"input_type": "chat",_59"input_value": question,_59}_59_59headers = {_59"Content-Type": "application/json",_59"x-api-key": "LANGFLOW_API_KEY"_59}_59_59try:_59response = requests.post(url, json=payload, headers=headers)_59response.raise_for_status()_59_59# Get the response message_59data = response.json()_59message = data["outputs"][0]["outputs"][0]["outputs"]["message"]["message"]_59return message_59_59except Exception as e:_59return f"Error: {str(e)}"_59_59def extract_message(data):_59try:_59return data["outputs"][0]["outputs"][0]["outputs"]["message"]["message"]_59except (KeyError, IndexError):_59return None_59_59# Store the previous answer from ask_agent response_59previous_answer = None_59_59# the terminal chat_59while True:_59# Get user input_59print("\nAsk the agent anything, such as 'What is 15 * 7?' or 'What is the capital of France?')")_59print("Type 'quit' to exit or 'compare' to see the previous answer")_59user_question = input("Your question: ")_59_59if user_question.lower() == 'quit':_59break_59elif user_question.lower() == 'compare':_59if previous_answer:_59print(f"\nPrevious answer was: {previous_answer}")_59else:_59print("\nNo previous answer to compare with!")_59continue_59_59# Get and display the answer_59result = ask_agent(user_question)_59print(f"\nAgent's answer: {result}")_59# Store the answer for comparison_59previous_answer = result_74const readline = require('readline');_74_74const rl = readline.createInterface({_74input: process.stdin,_74output: process.stdout_74});_74_74const url = 'http://LANGFLOW_SERVER_ADDRESS/api/v1/run/FLOW_ID';_74_74// Store the previous answer from askAgent response_74let previousAnswer = null;_74_74// the agent flow, with question as input_value_74async function askAgent(question) {_74const payload = {_74"output_type": "chat",_74"input_type": "chat",_74"input_value": question_74};_74_74const options = {_74method: 'POST',_74headers: {_74'Content-Type': 'application/json',_74'x-api-key': 'LANGFLOW_API_KEY'_74},_74body: JSON.stringify(payload)_74};_74_74try {_74const response = await fetch(url, options);_74const data = await response.json();_74_74// Extract the message from the nested response_74const message = data.outputs[0].outputs[0].outputs.message.message;_74return message;_74} catch (error) {_74return `Error: ${error.message}`;_74}_74}_74_74// the terminal chat_74async function startChat() {_74console.log("\nAsk the agent anything, such as 'What is 15 * 7?' or 'What is the capital of France?'");_74console.log("Type 'quit' to exit or 'compare' to see the previous answer");_74_74const askQuestion = () => {_74rl.question('\nYour question: ', async (userQuestion) => {_74if (userQuestion.toLowerCase() === 'quit') {_74rl.close();_74return;_74}_74_74if (userQuestion.toLowerCase() === 'compare') {_74if (previousAnswer) {_74console.log(`\nPrevious answer was: ${previousAnswer}`);_74} else {_74console.log("\nNo previous answer to compare with!");_74}_74askQuestion();_74return;_74}_74_74const result = await askAgent(userQuestion);_74console.log(`\nAgent's answer: ${result}`);_74previousAnswer = result;_74askQuestion();_74});_74};_74_74askQuestion();_74}_74_74startChat(); -
要查看 Agent 的上一个答案,请输入
compare
。要关闭终端聊天,请输入exit
。
使用 tweaks 对 flow 运行应用临时覆盖
您可以在请求中包含 tweaks 来临时修改 flow 参数。 Tweaks 被添加到 API 请求中,并临时更改您 flow 中的组件参数。 Tweaks 仅对单次运行覆盖 flow 组件的设置。 它们不会修改底层 flow 配置或在运行之间持久化。
Tweaks 被添加到 /run
端点的 payload
中。
为了帮助格式化,您可以在复制代码片段之前在 Langflow 的 Input Schema 面板中定义 tweaks。
- 要打开 Input Schema 面板,从 API access 面板中点击 Input Schema。
- 在 Input Schema 面板中,选择您在下一次请求中要修改的参数。 在 Input Schema 面板中启用参数并不允许修改列出的参数。它只是将它们添加到示例代码中。
- 例如,要将 LLM 提供商从 OpenAI 更改为 Groq,并在请求中包含您的 Groq API 密钥,请选择值 Model Providers、Model 和 Groq API Key。
Langflow 根据您的输入参数更新代码片段中的
tweaks
对象,并包含默认值来指导您。 在您的脚本中使用更新的代码片段来使用您的覆盖运行 flow。
_12payload = {_12 "output_type": "chat",_12 "input_type": "chat",_12 "input_value": "hello world!",_12 "tweaks": {_12 "Agent-ZOknz": {_12 "agent_llm": "Groq",_12 "api_key": "GROQ_API_KEY",_12 "model_name": "llama-3.1-8b-instant"_12 }_12 }_12}