Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
Mirrored from https://github.com/Camo67/composio.git
Synced Nov 22, 23:15 UTC
feat: python langgraph provider
angrybayblade committed
Jul 1, 2025 at 14:04 UTC
e603111c993b3396389f3c2c110ab7c6700deacf
9 files changed
+421
python/noxfile.py
+1
@@ -20,6 +20,7 @@ type_stubs = [
20
"semver",
21
"fastapi",
22
"langchain",
23
+ "langgraph",
24
"openai-agents",
25
"langchain-openai",
26
"google-cloud-aiplatform",
python/providers/langgraph/README.md
new
+119
@@ -0,0 +1,119 @@
1
+## 🦜🕸️ Using Composio With LangGraph
2
+
3
+Integrate Composio with LangGraph Agentic workflows & enable them to interact seamlessly with external apps, enhancing their functionality and reach.
4
+
5
+### Goal
6
+
7
+- **Star a repository on GitHub** using natural language commands through a LangGraph Agent.
8
+
9
+### Installation and Setup
10
+
11
+Ensure you have the necessary packages installed and connect your GitHub account to allow your agents to utilize GitHub functionalities.
12
+
13
+```bash
14
+# Install Composio LangGraph package
15
+pip install composio-langgraph
16
+
17
+# Connect your GitHub account
18
+composio-cli add github
19
+
20
+# View available applications you can connect with
21
+composio-cli show-apps
22
+```
23
+
24
+### Usage Steps
25
+
26
+#### 1. Import Base Packages
27
+
28
+Prepare your environment by initializing necessary imports from LangGraph & LangChain for setting up your agent.
29
+
30
+```python
31
+from typing import Literal
32
+
33
+from langchain_openai import ChatOpenAI
34
+from langgraph.graph import MessagesState, StateGraph
35
+from langgraph.prebuilt import ToolNode
36
+```
37
+
38
+#### 2. Fetch GitHub LangGraph Tools via Composio
39
+
40
+Access GitHub tools provided by Composio for LangGraph, initialize a `ToolNode` with necessary tools obtaned from `ComposioToolSet`.
41
+
42
+```python
43
+from composio_langgraph import Action, ComposioToolSet
44
+
45
+# Initialize the toolset for GitHub
46
+composio_toolset = ComposioToolSet()
47
+tools = composio_toolset.get_actions(
48
+ actions=[
49
+ Action.GITHUB_ACTIVITY_STAR_REPO_FOR_AUTHENTICATED_USER,
50
+ Action.GITHUB_USERS_GET_AUTHENTICATED,
51
+ ])
52
+tool_node = ToolNode(tools)
53
+```
54
+
55
+#### 3. Prepare the model
56
+
57
+Initialize the LLM class and bind obtained tools to the model.
58
+
59
+```python
60
+model = ChatOpenAI(temperature=0, streaming=True)
61
+model_with_tools = model.bind_tools(functions)
62
+```
63
+#### 4. Define the Graph Nodes
64
+
65
+LangGraph expects you to define different nodes of the agentic workflow as separate functions. Here we define a node for calling the LLM model.
66
+
67
+```python
68
+def call_model(state: MessagesState):
69
+ messages = state["messages"]
70
+ response = model_with_tools.invoke(messages)
71
+ return {"messages": [response]}
72
+```
73
+#### 5. Define the Graph Nodes and Edges
74
+
75
+To establish the agent's workflow, we begin by initializing the workflow with `agent` and `tools` node, followed by specifying the connecting edges between nodes, finally compiling the workflow. These edges can be straightforward or conditional, depending on the workflow requirements.
76
+
77
+```python
78
+def should_continue(state: MessagesState) -> Literal["tools", "__end__"]:
79
+ messages = state["messages"]
80
+ last_message = messages[-1]
81
+ if last_message.tool_calls:
82
+ return "tools"
83
+ return "__end__"
84
+
85
+
86
+workflow = StateGraph(MessagesState)
87
+
88
+# Define the two nodes we will cycle between
89
+workflow.add_node("agent", call_model)
90
+workflow.add_node("tools", tool_node)
91
+
92
+workflow.add_edge("__start__", "agent")
93
+workflow.add_conditional_edges(
94
+ "agent",
95
+ should_continue,
96
+)
97
+workflow.add_edge("tools", "agent")
98
+
99
+app = workflow.compile()
100
+```
101
+#### 6. Invoke & Check Response
102
+
103
+After the compilation of workflow, we invoke the LLM with a task, and stream the response.
104
+
105
+```python
106
+for chunk in app.stream(
107
+ {
108
+ "messages": [
109
+ (
110
+ "human",
111
+ # "Star the Github Repository composiohq/composio",
112
+ "Get my information.",
113
+ )
114
+ ]
115
+ },
116
+ stream_mode="values",
117
+):
118
+ chunk["messages"][-1].pretty_print()
119
+```
python/providers/langgraph/composio_langgraph/__init__.py
new
+3
@@ -0,0 +1,3 @@
1
+from .provider import LanggraphProvider
2
+
3
+__all__ = ("LanggraphProvider",)
python/providers/langgraph/composio_langgraph/provider.py
new
+93
@@ -0,0 +1,93 @@
1
+"""ComposioLangChain class definition"""
2
+
3
+import types
4
+import typing as t
5
+from inspect import Signature
6
+
7
+import pydantic
8
+from langchain_core.tools import StructuredTool as BaseStructuredTool
9
+
10
+from composio.core.provider import AgenticProvider, AgenticProviderExecuteFn
11
+from composio.types import Tool
12
+from composio.utils.pydantic import parse_pydantic_error
13
+from composio.utils.shared import (
14
+ get_signature_format_from_schema_params,
15
+ json_schema_to_model,
16
+)
17
+
18
+
19
+class StructuredTool(BaseStructuredTool):
20
+ def run(self, *args, **kwargs):
21
+ try:
22
+ return super().run(*args, **kwargs)
23
+ except pydantic.ValidationError as e:
24
+ return {"successful": False, "error": parse_pydantic_error(e), "data": None}
25
+
26
+
27
+class LanggraphProvider(
28
+ AgenticProvider[StructuredTool, t.List[StructuredTool]],
29
+ name="langgraph",
30
+):
31
+ """
32
+ Composio toolset for Langchain framework.
33
+ """
34
+
35
+ def _wrap_action(
36
+ self,
37
+ tool: str,
38
+ description: str,
39
+ schema_params: t.Dict,
40
+ execute_tool: AgenticProviderExecuteFn,
41
+ ):
42
+ def function(**kwargs: t.Any) -> t.Dict:
43
+ """Wrapper function for composio action."""
44
+ return execute_tool(tool, kwargs)
45
+
46
+ action_func = types.FunctionType(
47
+ function.__code__,
48
+ globals=globals(),
49
+ name=tool,
50
+ closure=function.__closure__,
51
+ )
52
+ action_func.__signature__ = Signature( # type: ignore
53
+ parameters=get_signature_format_from_schema_params(
54
+ schema_params=schema_params
55
+ )
56
+ )
57
+ action_func.__doc__ = description
58
+ return action_func
59
+
60
+ def wrap_tool(
61
+ self, tool: Tool, execute_tool: AgenticProviderExecuteFn
62
+ ) -> StructuredTool:
63
+ """Wraps composio tool as Langchain StructuredTool object."""
64
+ return t.cast(
65
+ StructuredTool,
66
+ StructuredTool.from_function(
67
+ name=tool.slug,
68
+ description=tool.description,
69
+ args_schema=json_schema_to_model(
70
+ json_schema=tool.input_parameters,
71
+ skip_default=True, # make configurable
72
+ ),
73
+ return_schema=True,
74
+ func=self._wrap_action(
75
+ tool=tool.slug,
76
+ description=tool.description,
77
+ schema_params=tool.input_parameters,
78
+ execute_tool=execute_tool,
79
+ ),
80
+ handle_tool_error=True,
81
+ handle_validation_error=True,
82
+ ),
83
+ )
84
+
85
+ def wrap_tools(
86
+ self,
87
+ tools: t.Sequence[Tool],
88
+ execute_tool: AgenticProviderExecuteFn,
89
+ ) -> t.List[StructuredTool]:
90
+ """
91
+ Get composio tools wrapped as Langchain StructuredTool objects.
92
+ """
93
+ return [self.wrap_tool(tool=tool, execute_tool=execute_tool) for tool in tools]
python/providers/langgraph/composio_langgraph/py.typed
python/providers/langgraph/langgraph_demo.py
new
+97
@@ -0,0 +1,97 @@
1
+import json
2
+import operator
3
+from typing import Annotated, Sequence, TypedDict
4
+
5
+from composio_langgraph import LanggraphProvider
6
+from langchain_core.messages import BaseMessage, FunctionMessage, HumanMessage
7
+from langchain_core.utils.function_calling import convert_to_openai_function
8
+from langchain_openai import ChatOpenAI
9
+from langgraph.graph import END, StateGraph
10
+
11
+from composio import Composio
12
+
13
+composio = Composio(provider=LanggraphProvider())
14
+tools = composio.tools.get(
15
+ user_id="default",
16
+ tools=[
17
+ "GITHUB_STAR_A_REPOSITORY_FOR_THE_AUTHENTICATED_USER",
18
+ "GITHUB_GET_THE_AUTHENTICATED_USER",
19
+ ],
20
+)
21
+functions = [convert_to_openai_function(t) for t in tools]
22
+model = ChatOpenAI(temperature=0, streaming=True).bind_functions(functions)
23
+
24
+
25
+def function_1(state):
26
+ messages = state["messages"]
27
+ response = model.invoke(messages)
28
+ return {"messages": [response]}
29
+
30
+
31
+def function_2(state):
32
+ messages = state["messages"]
33
+ last_message = messages[-1]
34
+
35
+ parsed_function_call = last_message.additional_kwargs["function_call"]
36
+
37
+ # Find the correct tool to use from the provided list of tools.
38
+ tool_to_use = None
39
+ for t in tools:
40
+ if t.name == parsed_function_call["name"]:
41
+ tool_to_use = t
42
+ break
43
+
44
+ if tool_to_use is None:
45
+ raise ValueError(f"Tool with name {parsed_function_call['name']} not found.")
46
+
47
+ response = tool_to_use.invoke(json.loads(parsed_function_call["arguments"]))
48
+
49
+ function_message = FunctionMessage(
50
+ content=str(response), name=parsed_function_call["name"]
51
+ )
52
+
53
+ return {"messages": [function_message]}
54
+
55
+
56
+def where_to_go(state):
57
+ messages = state["messages"]
58
+ last_message = messages[-1]
59
+
60
+ if "function_call" in last_message.additional_kwargs:
61
+ return "continue"
62
+ return "end"
63
+
64
+
65
+class AgentState(TypedDict):
66
+ messages: Annotated[Sequence[BaseMessage], operator.add]
67
+
68
+
69
+workflow = StateGraph(AgentState)
70
+workflow.add_node("agent", function_1)
71
+workflow.add_node("tool", function_2)
72
+workflow.add_conditional_edges(
73
+ "agent",
74
+ where_to_go,
75
+ {
76
+ # If return is "continue" then we call the tool node.
77
+ "continue": "tool",
78
+ # Otherwise we finish. END is a special node marking
79
+ # that the graph should finish.
80
+ "end": END,
81
+ },
82
+)
83
+workflow.add_edge("tool", "agent")
84
+workflow.set_entry_point("agent")
85
+
86
+app = workflow.compile()
87
+inputs = {
88
+ "messages": [
89
+ HumanMessage(content="Star a repo composiohq/composio on GitHub"),
90
+ ]
91
+}
92
+for output in app.stream(inputs): # type: ignore
93
+ for key, value in output.items():
94
+ print(f"Output from node '{key}':")
95
+ print("---")
96
+ print(value)
97
+ print("\n---\n")
python/providers/langgraph/langgraph_demo_toolnode.py
new
+62
@@ -0,0 +1,62 @@
1
+from typing import Literal
2
+
3
+from composio_langgraph import LanggraphProvider
4
+from langchain_openai import ChatOpenAI
5
+from langgraph.graph import MessagesState, StateGraph
6
+from langgraph.prebuilt import ToolNode
7
+
8
+from composio import Composio
9
+
10
+composio = Composio(provider=LanggraphProvider())
11
+tools = composio.tools.get(
12
+ user_id="default",
13
+ tools=[
14
+ "GITHUB_STAR_A_REPOSITORY_FOR_THE_AUTHENTICATED_USER",
15
+ "GITHUB_GET_THE_AUTHENTICATED_USER",
16
+ ],
17
+)
18
+tool_node = ToolNode(tools)
19
+model_with_tools = ChatOpenAI(temperature=0, streaming=True).bind_tools(tools)
20
+
21
+
22
+def should_continue(state: MessagesState) -> Literal["tools", "__end__"]:
23
+ messages = state["messages"]
24
+ last_message = messages[-1]
25
+ if last_message.tool_calls: # type: ignore
26
+ return "tools"
27
+ return "__end__"
28
+
29
+
30
+def call_model(state: MessagesState):
31
+ messages = state["messages"]
32
+ response = model_with_tools.invoke(messages)
33
+ return {"messages": [response]}
34
+
35
+
36
+workflow = StateGraph(MessagesState)
37
+
38
+# Define the two nodes we will cycle between
39
+workflow.add_node("agent", call_model)
40
+workflow.add_node("tools", tool_node)
41
+
42
+workflow.add_edge("__start__", "agent")
43
+workflow.add_conditional_edges(
44
+ "agent",
45
+ should_continue,
46
+)
47
+workflow.add_edge("tools", "agent")
48
+
49
+app = workflow.compile()
50
+
51
+for chunk in app.stream(
52
+ {
53
+ "messages": [
54
+ ( # type: ignore
55
+ "human",
56
+ "Star the Github Repository composiohq/composio",
57
+ )
58
+ ]
59
+ },
60
+ stream_mode="values",
61
+):
62
+ chunk["messages"][-1].pretty_print()
python/providers/langgraph/pyproject.toml
new
+20
@@ -0,0 +1,20 @@
1
+[project]
2
+name = "composio-langgraph"
3
+version = "1.0.0-rc6"
4
+description = "Use Composio to get array of tools with LangGraph Agent Workflows."
5
+readme = "README.md"
6
+requires-python = ">=3.9,<4"
7
+authors = [
8
+ { name = "Composio", email = "tech@composio.dev" }
9
+]
10
+classifiers = [
11
+ "Programming Language :: Python :: 3",
12
+ "License :: OSI Approved :: Apache Software License",
13
+ "Operating System :: OS Independent",
14
+]
15
+dependencies = [
16
+ "langgraph",
17
+]
18
+
19
+[project.urls]
20
+Homepage = "https://github.com/ComposioHQ/composio"
python/providers/langgraph/setup.py
new
+26
@@ -0,0 +1,26 @@
1
+"""
2
+Setup configuration for Composio LangGraph plugin
3
+"""
4
+
5
+from pathlib import Path
6
+
7
+from setuptools import setup
8
+
9
+setup(
10
+ name="composio_langgraph",
11
+ version="1.0.0-rc6",
12
+ author="composio",
13
+ author_email="tech@composio.dev",
14
+ description="Use Composio to get array of tools with LangGraph Agent Workflows",
15
+ long_description=(Path(__file__).parent / "README.md").read_text(encoding="utf-8"),
16
+ long_description_content_type="text/markdown",
17
+ url="https://github.com/ComposioHQ/composio",
18
+ classifiers=[
19
+ "Programming Language :: Python :: 3",
20
+ "License :: OSI Approved :: Apache Software License",
21
+ "Operating System :: OS Independent",
22
+ ],
23
+ python_requires=">=3.9,<4",
24
+ install_requires=["langgraph"],
25
+ include_package_data=True,
26
+)