Skip to main content

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

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.

  1. In Langflow, click New Flow, and then select the Simple agent template.

  2. Remove the URL and Calculator tools, and then drag the Directory and Web search components into your workspace.

  3. 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 find email 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 a customer_orders folder on your local machine.

  4. In the component header menu for the Directory and Web search components, enable Tool Mode so you can use the components with an agent.

  5. For both tool components, connect the Toolset port to the Agent component's Tools port.

  6. 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.

  7. 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's perform_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.

  1. To include the email address as a value in your flow, add a Prompt component to your flow between the Chat Input and Agent.

  2. 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 the customer_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.

    An agent component connected to web search and directory components

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.

  1. 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 is 127.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.
  2. 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 the const email = "isabella.rodriguez@example.com" to search for a value in your dataset.


    _60
    import { LangflowClient } from "@datastax/langflow-client";
    _60
    _60
    const LANGFLOW_SERVER_ADDRESS = 'LANGFLOW_SERVER_ADDRESS';
    _60
    const FLOW_ID = 'FLOW_ID';
    _60
    const LANGFLOW_API_KEY = 'LANGFLOW_API_KEY';
    _60
    const email = "isabella.rodriguez@example.com";
    _60
    _60
    async function runAgentFlow(): Promise<void> {
    _60
    try {
    _60
    // Initialize the Langflow client
    _60
    const client = new LangflowClient({
    _60
    baseUrl: LANGFLOW_SERVER_ADDRESS,
    _60
    apiKey: LANGFLOW_API_KEY
    _60
    });
    _60
    _60
    console.log(`Connecting to Langflow server at: ${LANGFLOW_SERVER_ADDRESS} `);
    _60
    console.log(`Flow ID: ${FLOW_ID}`);
    _60
    console.log(`Email: ${email}`);
    _60
    _60
    // Get the flow instance
    _60
    const flow = client.flow(FLOW_ID);
    _60
    _60
    // Run the flow with the email as input
    _60
    console.log('\nSending request to agent...');
    _60
    const response = await flow.run(email, {
    _60
    session_id: email // Use email as session ID for context
    _60
    });
    _60
    _60
    console.log('\n=== Response from Langflow ===');
    _60
    console.log('Session ID:', response.sessionId);
    _60
    _60
    // Extract URLs from the chat message
    _60
    const chatMessage = response.chatOutputText();
    _60
    console.log('\n=== URLs from Chat Message ===');
    _60
    const messageUrls = chatMessage.match(/https?:\/\/[^\s"')\]]+/g) || [];
    _60
    const cleanMessageUrls = [...new Set(messageUrls)].map(url => url.trim());
    _60
    console.log('URLs from message:');
    _60
    cleanMessageUrls.slice(0, 3).forEach(url => console.log(url));
    _60
    _60
    } catch (error) {
    _60
    console.error('Error running flow:', error);
    _60
    _60
    // Provide error messages
    _60
    if (error instanceof Error) {
    _60
    if (error.message.includes('fetch')) {
    _60
    console.error('\nMake sure your Langflow server is running and accessible at:', LANGFLOW_SERVER_ADDRESS);
    _60
    }
    _60
    if (error.message.includes('401') || error.message.includes('403')) {
    _60
    console.error('\nCheck your API key configuration');
    _60
    }
    _60
    if (error.message.includes('404')) {
    _60
    console.error('\nCheck your Flow ID - make sure it exists and is correct');
    _60
    }
    _60
    }
    _60
    }
    _60
    }
    _60
    _60
    // Run the function
    _60
    console.log('Starting Langflow Agent...\n');
    _60
    runAgentFlow().catch(console.error);

  3. 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.


    _15
    Starting Langflow Agent...
    _15
    _15
    Connecting to Langflow server at: http://localhost:7860
    _15
    Flow ID: local-db-search
    _15
    Email: isabella.rodriguez@example.com
    _15
    _15
    Sending request to agent...
    _15
    _15
    === Response from Langflow ===
    _15
    Session ID: isabella.rodriguez@example.com
    _15
    _15
    URLs found:
    _15
    https://www.facebook.com/marketplace/258164108225783/electronics/
    _15
    https://www.facebook.com/marketplace/458332108944152/furniture/
    _15
    https://www.facebook.com/marketplace/613732137493719/kitchen-cabinets/

  4. 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:

Search