https://linen.dev logo
How to pass an user_id to composio langchain tools...
# 🖥│support-forum
b
Hey all im using composio langchain provider and i wanna pass the userid to the composio tools
Copy code
py
from composio import Composio
from openai import OpenAI
from app.config.settings import settings
from composio_langchain import LangchainProvider

import logging

logger = logging.getLogger(__name__)

class ComposioService:
    def __init__(self):
        self.composio = Composio(provider=LangchainProvider(),api_key="")
        # self.openai = OpenAI(api_key=settings.OPENAI_API_KEY)

    def get_notion_tools(self,user_id: str):
        """
        Returns Composio-managed Notion tools for a specific user.
        """
        return self.composio.tools.get(user_id=user_id, toolkits=["NOTION"])

composio_service = ComposioService()
Copy code
py
    ],
    "creative": [
        image_tool.generate_image,
    ],
    "weather": [
        weather_tool.get_weather,
    ],
     "notion": [
        *composio_service.get_notion_tools(user_id="688bc1c38769a8edbc71954a")
    ],
}

# Map categories to their required integrations
CATEGORY_INTEGRATION_REQUIREMENTS = {
    "mail": "gmail",
    "calendar": "google_calendar",
    "google_docs": "google_docs",
    # "productivity", "goal_tracking", "documents", "search", "memory", "development", "creative", "weather" don't require integrations
}

# Define tools that should always be accessible to the agent directly
ALWAYS_AVAILABLE_TOOLS = [
    search_tool.web_search_tool,
    search_tool.deep_research_tool,
    webpage_tool.fetch_webpages,
    file_tools.query_file,
]
rn im hardcoding the user_id in the tool registry and user_id i get from the request
c
You can get the list of connected accounts using
composio.connected_accounts.list()
and use the
user_id
from the payload. You can pass filter as parameters to the function like toolkit_slugs, limit, etc. Let me know if this resolves the query.
b
you can see the below code i shared, i have my own registry in this where i have registered tools
Copy code
"notion": [
        *composio_service.get_notion_tools(user_id="688bc1c38769a8edbc71954a")
    ],
i have hardcoded the user_id as of now
but this isn't called from route
c
Yes, just to clarify, you are looking to fetch the
user_id
dynamically?
b
yes,
c
Yes, you can use the above suggested function
.list()
or
.get()
connected account to dynamically fetch the
use_id
. Let me know if it works for you.
b
it is asking in the runtime user_id how do i pass, these are langchain tool used by langgraph which get's build when application loads
why isn't composio langchain tools are not getting the user_id from the runnable config ?
why do we need to pass them when we are extracting the tools
c
user_id
is defined to associate a connected account to your API calls, when you are trying to use APIs(get tools, etc) you'll need to specify the connected account which is done using
user_id
and it is mandatory. I've attached an image for your reference. https://cdn.discordapp.com/attachments/1404122105343246347/1405554703990784001/Screenshot_2025-08-14_at_19.41.24.png?ex=689f4053&is=689deed3&hm=0e07336a9db815bd4b0b881b9622c1d1bb03fb894870e5b817c66229d96b1d0b&
b
yeah ik that but when we create a langchain tool we get the user id from the runable config, i have used the langgraph where graph is build during the application startup
but how do you pass user_id during the application start
c
You don't need to pass it at the application start, as I suggested, you have to pass it as a function parameter, you can get it using the the suggested. Please provide more context in case if this does not help with your query.
b
you can’t pass the user_id cause you get user_id from session
a
hey @Bismuth, you can pass the userId by using a
before_execute
, checkout the guide [here](https://docs.composio.dev/docs/modifiers/before-execution#before-execution-modifiers) here's a snip for ref, you can set the userId like this:
Copy code
@before_execute(tools=["GMAIL_SEND_EMAIL"])
def before_execute_modifier(
    tool: str,
    toolkit: str,
    params: ToolExecuteParams,
) -> ToolExecuteParams:
    params["user_id"] = "<user_id>"
    return params
Lmk if this helps.
b
is user_id passed from runnable config? i mean i don’t need to pass that
cause runnable config of langchain tool already has a user_id within there
a
checking this
b
i want the tool to take the user_id from langchain runableconfig itself
a
This isn't currently supported, but we'll look into whether this feature can be added. Thanks for bringing it up. In the meantime, using
before_execute
should help with your use case.
b
Copy code
py

TOOLS_BY_CATEGORY = {
    "mail": [
        *mail_tool.tools,
    ],
    "productivity": [
        *todo_tool.tools,
        *reminder_tool.tools,
    ],
    "calendar": [
        *calendar_tool.tools,
    ],
    "goal_tracking": [
        *goal_tool.tools,
    ],
    "google_docs": [
        *google_docs_tool.tools,
    ],
    "documents": [
        document_tool.generate_document,
        file_tools.query_file,
    ],
    "search": [
        search_tool.web_search_tool,
        search_tool.deep_research_tool,
        webpage_tool.fetch_webpages,
    ],
    "memory": [
        *memory_tools.tools,
    ],
    "development": [
        code_exec_tool.execute_code,
        flowchart_tool.create_flowchart,
    ],
    "creative": [
        image_tool.generate_image,
    ],
    "weather": [
        weather_tool.get_weather,
    ],
     "notion": [
        *composio_service.get_notion_tools(user_id="688bc1c38769a8edbc71954a")
    ],
     "google_sheet": [
        *composio_service.get_google_sheet_tools(user_id="688bc1c38769a8edbc71954a")
    ],
     "twitter": [
        *composio_service.get_x_tools(user_id="688bc1c38769a8edbc71954a")
    ],
}

# Map categories to their required integrations
CATEGORY_INTEGRATION_REQUIREMENTS = {
    "mail": "gmail",
    "calendar": "google_calendar",
    "google_docs": "google_docs",
  

} 

# Define tools that should always be accessible to the agent directly
ALWAYS_AVAILABLE_TOOLS = [
    search_tool.web_search_tool,
    search_tool.deep_research_tool,
    webpage_tool.fetch_webpages,
    file_tools.query_file,
]

tools = [
    tool
    for category_tools in TOOLS_BY_CATEGORY.values()
    for tool in category_tools
    if tool not in ALWAYS_AVAILABLE_TOOLS  
]

tool_names = [tool.name for tool in tools]
here i have registered the tools that were made my me but now i wanna use composio but these tools i have registered from the composio need user_id which i can't get when first application is build using langgraph
before_execute doesn't work because i can't pass user_id in the runtime
@abhishekpatil4 where are the tools of the composio, like if i wanna see the
create_twitter_post
tool
Copy code
py
@schema_modifier(toolkits=["NOTION"])
def inject_user_id(schema, context):
    """
    Dynamically inject user_id from RunnableConfig into Composio tools at runtime.
    """
    runnable_config = context.get("config")  
    print("this is schema modifier runnable config",runnable_config)
    print("this is schema modifier context",context)
    if runnable_config:
        metadata = runnable_config.get("metadata", {})
        user_id = metadata.get("user_id")
        if user_id:
            schema["args"]["user_id"] = user_id
        schema["description"] = f"if user_id is not provided use this {user_id}"
    return schema
is this correct way of passing?
@udaysidagana @abhishekpatil4 idk if im doing something wrong in schema modifer cause i hard coded the user_id in the description to use the provided user_id explicitly so that i don't need to pass user_id here
Copy code
py
    def get_notion_tools(self, user_id: str):
        # self.composio.tools._get()
        # self.composio.tools.get_raw_composio_tools()
        return self.composio.tools.get(user_id=user_id, toolkits=["NOTION"],modifiers=[inject_user_id])
but it seems like schema modifer isn't being called or connected when tools are called
a
that is closed source
No, the schema changes made are only for tools-related purposes, so the agent can see and pass the right arguments where the user_id part is something that cannot be handled by the agent/LLM.
b
when i use langchain provider it wraps all tool(i was checking langchain provider source code) with langchain
structuredtool
but isn't there any way i can use the runnable config in modifier or before_execute
let's say im using a langgraph and all the tools which are made by me are added in the graph during initial app start, when user want's to execute some tool langgraph decide itself which tool to call
but the problem with composio langgraph provider is i can't pass the user_id in here. In the graph i have passed the meta_data which has a user_id but since tools are handled by the composio itself i can't pass the user_id during the runtime
a
@Bismuth Are you available for a quick call to discuss this?
b
sure
a
b
a
thanks
b
we fixed it on our side, changing the langchain provider code
d
We fixed this by extending the composio-langchain library. We had to add new parameter like below in
_wrap_action
method
Copy code
python
        # Add RunnableConfig param with a collision-safe name
        parameters.append(
            Parameter(
                "__runnable_config__",
                kind=Parameter.KEYWORD_ONLY,
                default=None,
                annotation=RunnableConfig,
            )
        )
and one sneaky workaround, below is required bcz langchain identifies parameter of RunnableConfig type using annotations.
Copy code
python
        # Create __annotations__ only for __runnable_config__
        action_func.__annotations__ = {"__runnable_config__": RunnableConfig}
after doing this, we can get RunnableConfig in
before_execute
modifier like this
Copy code
python
@before_execute()
def before_execute_notion(
    tool,
    toolkit,
    params: ToolExecuteParams
):
    arguments = params.get("arguments", {})
    config = arguments.pop("__runnable_config__")
a
Awesome!
b
how do we get the list of available tools?
Copy code
py
from composio_client import Composio

client = Composio(
    api_key="My API Key",
)
tools = client.tools.list()
print(tools.current_page)
this isn't working
nvm
got the solution
Copy code
py
    def get_tools(self, tool_kit: str):
        tools = self.composio.tools.get(
            user_id="",
            toolkits=[tool_kit],
        )
        tools_name = [tool.name for tool in tools]
        @before_execute(tools=tools_name)
        def before_execute_tools(
            _,
            __,
            params: ToolExecuteParams,
        ):
            arguments = params.get("arguments", {})
            if not arguments:
                return params
            config = arguments.pop("__runnable_config__", None)
            if config is None:
                return params
            metadata = config.get("metadata", {}) if isinstance(config, dict) else {}
            if not metadata:
                return params
            user_id = metadata.get("user_id")
            if user_id is None:
                return params
            params["user_id"] = user_id
            return params

        return self.composio.tools.get(
            user_id="",
            toolkits=["NOTION"],
            modifiers=[before_execute_tools],
        )
@abhishekpatil4 is there a way we can get the user access token and refresh token if we are using composio auth config for gmail?
composio handles the authentication but i want user
refresh_token
and
access_token
for the mail
c
You get it in the connection details
b
how can i check the connection details?
@abhishekpatil4 ?
c
Will improve that bit in docs. But you can access via composio.connectedAccounts.get()
b
also is there a way we can get the which tool is being called and reasoning text as well?
a
You can know what tool was called in logs with args, but not the reasoning — this should be handled at the agentic side.
b
can i not send stream using after_execute?
a
The function binded to
after_execute
runs synchronously after a tool execution completes, so not sure about that. If you want a function to run after every tool execution configure it this way
@after_execute(tools=[], toolkits=[])
b
hey, can we have the exclude_tools parameter in the
composio.get
method email has tons of tools which i directly get from the toolkit but i wanna exlcude few tools, it would be helpful if we have a exclude_tools parameter as well, if team is busy on something i would love to give a PR
a
I would recommend filtering on your end since this use case isn't common. Also, using specific tools instead of all tools improves LLM accuracy in tool selection.