All files / frameworks langchain.ts

80% Statements 20/25
61.11% Branches 11/18
66.66% Functions 6/9
80% Lines 20/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 1461x 1x 1x 1x       1x 1x   1x                                                                                       1x                         9x 9x 9x   9x               9x       9x                           1x 1x 1x                                                 1x 1x 8x                                      
import { ComposioToolSet as BaseComposioToolSet } from "../sdk/base.toolset";
import { jsonSchemaToModel } from "../utils/shared";
import { DynamicStructuredTool } from "@langchain/core/tools";
import { COMPOSIO_BASE_URL } from "../sdk/client/core/OpenAPI";
import type { Optional, Dict, Sequence } from "../sdk/types";
import {ActionsControllerV2ListActionsResponse, ActionsListResponseDTO } from "../sdk/client";
import { WorkspaceConfig } from "../env/config";
import { Workspace } from "../env";
import logger from "../utils/logger";
 
export class LangchainToolSet extends BaseComposioToolSet {
    /**
     * Composio toolset for Langchain framework.
     *
     * Example:
     * ```typescript
     * import * as dotenv from "dotenv";
     * import { App, ComposioToolSet } from "composio_langchain";
     * import { AgentExecutor, create_openai_functions_agent } from "langchain/agents";
     * import { ChatOpenAI } from "langchain_openai";
     * import { hub } from "langchain";
     *
     * // Load environment variables from .env
     * dotenv.config();
     *
     * // Pull relevant agent model.
     * const prompt = hub.pull("hwchase17/openai-functions-agent");
     *
     * // Initialize tools.
     * const openai_client = new ChatOpenAI({ apiKey: process.env.OPENAI_API_KEY });
     * const composio_toolset = new ComposioToolSet();
     *
     * // Get All the tools
     * const tools = composio_toolset.get_tools({ apps: [App.GITHUB] });
     *
     * // Define task
     * const task = "Star a repo composiohq/composio on GitHub";
     *
     * // Define agent
     * const agent = create_openai_functions_agent(openai_client, tools, prompt);
     * const agent_executor = new AgentExecutor({ agent, tools, verbose: true });
     *
     * // Execute using agent_executor
     * agent_executor.invoke({ input: task });
     * ```
     */
    constructor(
        config: {
            apiKey?: Optional<string>,
            baseUrl?: Optional<string>,
            entityId?: string,
            workspaceConfig?: WorkspaceConfig
        }
    ) {
        super(
            config.apiKey || null,
            config.baseUrl || COMPOSIO_BASE_URL,
            "langchain",
            config.entityId || "default",
            config.workspaceConfig || Workspace.Host()
        );
    }
 
    private _wrapTool(
        schema: Dict<any>,
        entityId: Optional<string> = null
    ): DynamicStructuredTool {
        const app = schema["appName"];
        const action = schema["name"];
        const description = schema["description"];
 
        const func = async (...kwargs: any[]): Promise<any> => {
            return JSON.stringify(await this.executeAction(
                action,
                kwargs[0],
                entityId || this.entityId
            ));
        };
 
        const parameters = jsonSchemaToModel(schema["parameters"]);
 
        // @TODO: Add escriiption an othjer stuff here
 
        return new DynamicStructuredTool({
            name: action,
            description,
            schema: parameters,
            func: func
        });
    }
 
    async getActions(
        filters: {
            actions?: Optional<Sequence<string>>
        } = {},
        entityId?: Optional<string>
    ): Promise<Sequence<DynamicStructuredTool>> {
        const actions = await this.getActionsSchema(filters as any, entityId);
        return actions!.map((tool: NonNullable<ActionsListResponseDTO["items"]>[0]) =>
            this._wrapTool(
                tool,
                entityId || this.entityId
            )
        ) as any;
    }
 
    /**
     * @deprecated Use getActions instead.
     */
    async get_actions(filters: {
        actions?: Optional<Sequence<string>>
    } = {}, entityId?: Optional<string>): Promise<Sequence<DynamicStructuredTool>> {
        logger.warn("get_actions is deprecated, use getActions instead");
        return this.getActions(filters, entityId);
    }
 
    async getTools(
        filters: {
            apps: Sequence<string>;
            tags?: Optional<Array<string>>;
            useCase?: Optional<string>;
        },
        entityId: Optional<string> = null
    ): Promise<Sequence<DynamicStructuredTool>> {
        const tools = await this.getToolsSchema(filters, entityId);
        return tools.map((tool: NonNullable<ActionsControllerV2ListActionsResponse["items"]>[0]) =>
            this._wrapTool(
                tool,
                entityId || this.entityId
            )
        );
    }
 
    /**
     * @deprecated Use getTools instead.
     */
    async get_tools(filters: {
        apps: Sequence<string>;
        tags?: Optional<Array<string>>;
        useCase?: Optional<string>;
    }, entityId?: Optional<string>): Promise<Sequence<DynamicStructuredTool>> {
        logger.warn("get_tools is deprecated, use getTools instead");
        return this.getTools(filters, entityId);
    }
}