Connect applications to agents
This tutorial shows you how to connect a JavaScript application to a Langflow agent.
With the agent connected, your application can use any connected tools to retrieve more contextual and timely data without changing any application code. The tools are selected by the agent's internal LLM to solve problems and answer questions.
Prerequisites
- A running Langflow instance
- A Langflow API key
- An OpenAI API key
- Langflow JavaScript client installed
This tutorial uses an OpenAI LLM. If you want to use a different provider, you need a valid credential for that provider.
Create an agentic flow
The following steps modify the Simple agent template to connect Directory and Web search components as tools for an Agent component. The Directory component loads all files of a given type from a target directory on your local machine, and the Web search component performs a DuckDuckGo search. When connected to an Agent component as tools, the agent has the option to use these components when handling requests.
-
In Langflow, click New Flow, and then select the Simple agent template.
-
Remove the URL and Calculator tools, and then drag the Directory and Web search components into your workspace.
-
In the Directory component's Path field, enter the directory path and file types that you want to make available to the Agent component.
In this tutorial, the agent needs access to a record of customer purchases, so the directory name is
customer_orders
and the file type is.csv
. Later in this tutorial, the agent will be prompted to findemail
values in the customer data.You can adapt the tutorial to suit your data, or, to follow along with the tutorial, you can download
customer-orders.csv
and save it in acustomer_orders
folder on your local machine. -
In the component header menu for the Directory and Web search components, enable Tool Mode so you can use the components with an agent.
-
For both tool components, connect the Toolset port to the Agent component's Tools port.
-
In the Agent component, enter your OpenAI API key.
If you want to use a different provider or model, edit the Model Provider, Model Name, and API Key fields accordingly.
-
To test the flow, click Playground, and then ask the LLM a question, such as
Recommend 3 used items for carol.davis@example.com, based on previous orders.
Given the example prompt, the LLM would respond with recommendations and web links for items based on previous orders in
customer_orders.csv
.The Playground prints the agent's chain of thought as it selects tools to use and interacts with functionality provided by those tools. For example, the agent can use the Directory component's
as_dataframe
tool to retrieve a DataFrame, and the Web search component'sperform_search
tool to find links to related items.
Add a prompt component to the flow
In this example, the application sends a customer's email address to the Langflow agent. The agent compares the customer's previous orders within the Directory component, searches the web for used versions of those items, and returns three results.
-
To include the email address as a value in your flow, add a Prompt component to your flow between the Chat Input and Agent.
-
In the Prompt component's Template field, enter
Recommend 3 used items for {email}, based on previous orders.
Adding the{email}
value in curly braces creates a new input in the Prompt component, and the component connected to the{email}
port is supplying the value for that variable. This creates a point for the user's email to enter the flow from your request. If you aren't using thecustomer_orders.csv
example file, modify the input to search for a value in your dataset.At this point your flow has six components. The Chat Input is connected to the Prompt component's
email
input port. Then, the Prompt component's output port is connected to the Agent component's input port. The Directory and Web search components are connected to the Agent's Tools port. Finally, the Agent component's output port is connected to the Chat Output component, which returns the final response to the application.
Send requests to your flow from a JavaScript application
With your flow operational, connect it to a JavaScript application to use the agent's responses.
-
To construct a JavaScript application to connect to your flow, gather the following information:
LANGFLOW_SERVER_ADDRESS
: Your Langflow server's domain. The default value is127.0.0.1:7860
. You can get this value from the code snippets on your flow's API access pane.FLOW_ID
: Your flow's UUID or custom endpoint name. You can get this value from the code snippets on your flow's API access pane.LANGFLOW_API_KEY
: A valid Langflow API key. To create an API key, see API keys.
-
Copy the following script into a JavaScript file, and then replace the placeholders with the information you gathered in the previous step. If you're using the
customer_orders.csv
example file, you can run this example as-is with the example email address in the code sample. If not, modify theconst email = "isabella.rodriguez@example.com"
to search for a value in your dataset._60import { LangflowClient } from "@datastax/langflow-client";_60_60const LANGFLOW_SERVER_ADDRESS = 'LANGFLOW_SERVER_ADDRESS';_60const FLOW_ID = 'FLOW_ID';_60const LANGFLOW_API_KEY = 'LANGFLOW_API_KEY';_60const email = "isabella.rodriguez@example.com";_60_60async function runAgentFlow(): Promise<void> {_60try {_60// Initialize the Langflow client_60const client = new LangflowClient({_60baseUrl: LANGFLOW_SERVER_ADDRESS,_60apiKey: LANGFLOW_API_KEY_60});_60_60console.log(`Connecting to Langflow server at: ${LANGFLOW_SERVER_ADDRESS} `);_60console.log(`Flow ID: ${FLOW_ID}`);_60console.log(`Email: ${email}`);_60_60// Get the flow instance_60const flow = client.flow(FLOW_ID);_60_60// Run the flow with the email as input_60console.log('\nSending request to agent...');_60const response = await flow.run(email, {_60session_id: email // Use email as session ID for context_60});_60_60console.log('\n=== Response from Langflow ===');_60console.log('Session ID:', response.sessionId);_60_60// Extract URLs from the chat message_60const chatMessage = response.chatOutputText();_60console.log('\n=== URLs from Chat Message ===');_60const messageUrls = chatMessage.match(/https?:\/\/[^\s"')\]]+/g) || [];_60const cleanMessageUrls = [...new Set(messageUrls)].map(url => url.trim());_60console.log('URLs from message:');_60cleanMessageUrls.slice(0, 3).forEach(url => console.log(url));_60_60} catch (error) {_60console.error('Error running flow:', error);_60_60// Provide error messages_60if (error instanceof Error) {_60if (error.message.includes('fetch')) {_60console.error('\nMake sure your Langflow server is running and accessible at:', LANGFLOW_SERVER_ADDRESS);_60}_60if (error.message.includes('401') || error.message.includes('403')) {_60console.error('\nCheck your API key configuration');_60}_60if (error.message.includes('404')) {_60console.error('\nCheck your Flow ID - make sure it exists and is correct');_60}_60}_60}_60}_60_60// Run the function_60console.log('Starting Langflow Agent...\n');_60runAgentFlow().catch(console.error); -
Save and run the script to send the request and test the flow. Your application receives three URLs for recommended used items based on a customer's previous orders in your local CSV, all without changing any code.
Response
The following is an example of a response returned from this tutorial's flow. Due to the nature of LLMs and variations in your inputs, your response might be different.
_15Starting Langflow Agent..._15_15Connecting to Langflow server at: http://localhost:7860_15Flow ID: local-db-search_15Email: isabella.rodriguez@example.com_15_15Sending request to agent..._15_15=== Response from Langflow ===_15Session ID: isabella.rodriguez@example.com_15_15URLs found:_15https://www.facebook.com/marketplace/258164108225783/electronics/_15https://www.facebook.com/marketplace/458332108944152/furniture/_15https://www.facebook.com/marketplace/613732137493719/kitchen-cabinets/ -
To quickly check traffic to your flow, open the Playground. New sessions appear named after the user's email address. Keeping sessions distinct helps the agent maintain context. For more on session IDs, see Session ID.
Next steps
For more information on building or extending this tutorial, see the following: