Connect applications to agents

Estimated reading: 7 minutes 200 views

This tutorial shows you how to connect a JavaScript application to a Robility flow agent.

With an agent, 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. Create a Robility flow API key
b. Install the Robility flow JavaScript client
c. Create an OpenAI API key

This tutorial uses OpenAI LLM. If you want to use a different provider, you need a valid credential for that provider.

Create an agent flow

The following steps modify the Simple Agent template to connect a Directory component and a Web Search component 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 Robility flow, click New Flow, and then select the Simple Agent template. 
2. Remove the URL and Calculator tools and then add Directory and Web Search components to your flow. 
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 and save it in a customer_orders folder on your local machine.

4. In the Directory and Web Search components’ header menus, enable Tool Mode so you can use the components with an agent. 
5. Connect the Directory and Web Search components’ Toolset ports 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 ProviderModel 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 john.smith@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 components perform_search tool to find links to related items.

Add a Prompt Template Component to the flow

In this example, the application sends a customer’s email address to the Robility flow 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 Template component to your flow between the Chat Input and Agent components. 
2. In the Prompt Template 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 Template 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 component is connected to the Prompt Template component’s email input port. Then, the Prompt Template component’s output is connected to the Agent component’s System Message input port. The Directory and Web Search components are connected to the Agent component’s Tools port. Finally, the Agent component’s output 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.

1. To construct a JavaScript application to connect to your flow, gather the following information:

a. ROBILITY FLOW _SERVER_ADDRESS: Your Robility flow 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
b. 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
c. ROBILITY FLOW _API_KEY: A valid Robility flow API key.

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.

import { Robility flow Client } from “@datastax/Robility flow -client”;

const ROBILITY FLOW _SERVER_ADDRESS = ‘ROBILITY FLOW _SERVER_ADDRESS’;

const FLOW_ID = ‘FLOW_ID’;

const ROBILITY FLOW _API_KEY = ‘ROBILITY FLOW _API_KEY’;

const email = “isabella.rodriguez@example.com”;

async function runAgentFlow(): Promise<void> {

    try {

        // Initialize the Robility flow  client

        const client = new Robility flow Client({

            baseUrl: ROBILITY FLOW _SERVER_ADDRESS,

            apiKey: ROBILITY FLOW _API_KEY

        });

        console.log(`Connecting to Robility flow  server at: ${ROBILITY FLOW _SERVER_ADDRESS} `);

        console.log(`Flow ID: ${FLOW_ID}`);

        console.log(`Email: ${email}`);

        // Get the flow instance

        const flow = client.flow(FLOW_ID);

        // Run the flow with the email as input

        console.log(‘\nSending request to agent…’);

        const response = await flow.run(email, {

            session_id: email // Use email as session ID for context

        });

        console.log(‘\n=== Response from Robility flow  ===’);

        console.log(‘Session ID:’, response.sessionId);

        // Extract URLs from the chat message

        const chatMessage = response.chatOutputText();

        console.log(‘\n=== URLs from Chat Message ===’);

        const messageUrls = chatMessage.match(/https?:\/\/[^\s”‘)\]]+/g) || [];

        const cleanMessageUrls = […new Set(messageUrls)].map(url => url.trim());

        console.log(‘URLs from message:’);

        cleanMessageUrls.slice(0, 3).forEach(url => console.log(url));

    } catch (error) {

        console.error(‘Error running flow:’, error);

        // Provide error messages

        if (error instanceof Error) {

            if (error.message.includes(‘fetch’)) {

                console.error(‘\nMake sure your Robility flow  server is running and accessible at:’, ROBILITY FLOW _SERVER_ADDRESS);

            }

            if (error.message.includes(‘401’) || error.message.includes(‘403’)) {

                console.error(‘\nCheck your API key configuration’);

            }

            if (error.message.includes(‘404’)) {

                console.error(‘\nCheck your Flow ID – make sure it exists and is correct’);

            }

        }

    }

}

// Run the function

console.log(‘Starting Robility flow  Agent…\n’);

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 items based on a customer’s previous orders in your local CSV, all without changing any code.

4. To quickly check traffic to your flow, open the Playground. New sessions are 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:

Model Context Protocol (MCP) servers

Share this Doc

Connect applications to agents

Or copy link

CONTENTS