Function Tooling

How to convert an api controller endpoint to a tool

This guide shows you how to turn any controllable API endpoint into a DynamicStructuredTool in LangchainJS, expanding your AI agent's ability to navigate to a specific page URL.

import { RunnableConfig } from "@langchain/core/runnables";
import { DynamicStructuredTool } from "@langchain/core/tools";
import { CallbackManagerForToolRun } from "@langchain/core/callbacks/manager";
import { z } from "zod";

const BASE_URL = "https://.ai"

export const ZInput = z.object({
    url: z.string(),
})

export const implementation = (baseUrl:string) => {
    return async (
        input : z.infer<typeof ZInput>, 
        runnerManger?:CallbackManagerForToolRun, 
        config?:RunnableConfig
    ) => {
        // Pass sessionID through metadata
        const sessionID = config && config.metadata ? config.metadata.sessionID : ""
        if(!sessionID || sessionID === ""){
            return "Failed because Session ID not provided"
        }
        
        try{
            const response = await axios.post(
                `${BASE_URL}/page/goToPage`, 
                input,
                {
                    headers: {
                        "Authorization": "<TOKEN_HERE>"
                        "Content-Type": "application/json"
                    },
                }
            )
            
            return `Navigated to ${input.url} page successfully`
        } catch(error:unknown){
            if(isAxiosError(error)){ 
                return `Failed to go to page because: ${error.data.message}`
            }
            
            return `Failed to go to page because: ${result.error ? result.error.message : "unknown reason"}`
        }
    }
}

// Create a DynamicStructuredTool
export const goToPageTool = new DynamicStructuredTool({
    name: "goToPage",
    description: "Navigates to a specific page url",
    schema: ZInput,
    func: implementation(BASE_URL),
})

// Usage
(async () => {
    // Make sure to create the session first before invoking
    const toolResponse = await goToPageTool.invoke({
        url: "https://google.com"
    },{
        metadata: {
            sessionID: "<SESSIOND_ID_HERE>"
        }
    })
    console.log(toolResponse)
})()

Last updated