Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
feat: python langgraph provider
angrybaybladee603111c993b
diff --git a/python/noxfile.py b/python/noxfile.pyindex cd11d4eec..2d9851558 100644--- a/python/noxfile.py+++ b/python/noxfile.py@@ -20,6 +20,7 @@ type_stubs = ["semver","fastapi","langchain",+ "langgraph","openai-agents","langchain-openai","google-cloud-aiplatform",diff --git a/python/providers/langgraph/README.md b/python/providers/langgraph/README.mdnew file mode 100644index 000000000..8dd22917f--- /dev/null+++ b/python/providers/langgraph/README.md@@ -0,0 +1,119 @@+## 🦜🕸️ Using Composio With LangGraph++Integrate Composio with LangGraph Agentic workflows & enable them to interact seamlessly with external apps, enhancing their functionality and reach.++### Goal++- **Star a repository on GitHub** using natural language commands through a LangGraph Agent.++### Installation and Setup++Ensure you have the necessary packages installed and connect your GitHub account to allow your agents to utilize GitHub functionalities.++```bash+# Install Composio LangGraph package+pip install composio-langgraph++# Connect your GitHub account+composio-cli add github++# View available applications you can connect with+composio-cli show-apps+```++### Usage Steps++#### 1. Import Base Packages++Prepare your environment by initializing necessary imports from LangGraph & LangChain for setting up your agent.++```python+from typing import Literal++from langchain_openai import ChatOpenAI+from langgraph.graph import MessagesState, StateGraph+from langgraph.prebuilt import ToolNode+```++#### 2. Fetch GitHub LangGraph Tools via Composio++Access GitHub tools provided by Composio for LangGraph, initialize a `ToolNode` with necessary tools obtaned from `ComposioToolSet`.++```python+from composio_langgraph import Action, ComposioToolSet++# Initialize the toolset for GitHub+composio_toolset = ComposioToolSet()+tools = composio_toolset.get_actions(+ actions=[+ Action.GITHUB_ACTIVITY_STAR_REPO_FOR_AUTHENTICATED_USER,+ Action.GITHUB_USERS_GET_AUTHENTICATED,+ ])+tool_node = ToolNode(tools)+```++#### 3. Prepare the model++Initialize the LLM class and bind obtained tools to the model.++```python+model = ChatOpenAI(temperature=0, streaming=True)+model_with_tools = model.bind_tools(functions)+```+#### 4. Define the Graph Nodes++LangGraph expects you to define different nodes of the agentic workflow as separate functions. Here we define a node for calling the LLM model.++```python+def call_model(state: MessagesState):+ messages = state["messages"]+ response = model_with_tools.invoke(messages)+ return {"messages": [response]}+```+#### 5. Define the Graph Nodes and Edges++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.++```python+def should_continue(state: MessagesState) -> Literal["tools", "__end__"]:+ messages = state["messages"]+ last_message = messages[-1]+ if last_message.tool_calls:+ return "tools"+ return "__end__"+++workflow = StateGraph(MessagesState)++# Define the two nodes we will cycle between+workflow.add_node("agent", call_model)+workflow.add_node("tools", tool_node)++workflow.add_edge("__start__", "agent")+workflow.add_conditional_edges(+ "agent",+ should_continue,+)+workflow.add_edge("tools", "agent")++app = workflow.compile()+```+#### 6. Invoke & Check Response++After the compilation of workflow, we invoke the LLM with a task, and stream the response.++```python+for chunk in app.stream(+ {+ "messages": [+ (+ "human",+ # "Star the Github Repository composiohq/composio",+ "Get my information.",+ )+ ]+ },+ stream_mode="values",+):+ chunk["messages"][-1].pretty_print()+```diff --git a/python/providers/langgraph/composio_langgraph/__init__.py b/python/providers/langgraph/composio_langgraph/__init__.pynew file mode 100644index 000000000..3086e31a9--- /dev/null+++ b/python/providers/langgraph/composio_langgraph/__init__.py@@ -0,0 +1,3 @@+from .provider import LanggraphProvider++__all__ = ("LanggraphProvider",)diff --git a/python/providers/langgraph/composio_langgraph/provider.py b/python/providers/langgraph/composio_langgraph/provider.pynew file mode 100644index 000000000..34daac1e9--- /dev/null+++ b/python/providers/langgraph/composio_langgraph/provider.py@@ -0,0 +1,93 @@+"""ComposioLangChain class definition"""++import types+import typing as t+from inspect import Signature++import pydantic+from langchain_core.tools import StructuredTool as BaseStructuredTool++from composio.core.provider import AgenticProvider, AgenticProviderExecuteFn+from composio.types import Tool+from composio.utils.pydantic import parse_pydantic_error+from composio.utils.shared import (+ get_signature_format_from_schema_params,+ json_schema_to_model,+)+++class StructuredTool(BaseStructuredTool):+ def run(self, *args, **kwargs):+ try:+ return super().run(*args, **kwargs)+ except pydantic.ValidationError as e:+ return {"successful": False, "error": parse_pydantic_error(e), "data": None}+++class LanggraphProvider(+ AgenticProvider[StructuredTool, t.List[StructuredTool]],+ name="langgraph",+):+ """+ Composio toolset for Langchain framework.+ """++ def _wrap_action(+ self,+ tool: str,+ description: str,+ schema_params: t.Dict,+ execute_tool: AgenticProviderExecuteFn,+ ):+ def function(**kwargs: t.Any) -> t.Dict:+ """Wrapper function for composio action."""+ return execute_tool(tool, kwargs)++ action_func = types.FunctionType(+ function.__code__,+ globals=globals(),+ name=tool,+ closure=function.__closure__,+ )+ action_func.__signature__ = Signature( # type: ignore+ parameters=get_signature_format_from_schema_params(+ schema_params=schema_params+ )+ )+ action_func.__doc__ = description+ return action_func++ def wrap_tool(+ self, tool: Tool, execute_tool: AgenticProviderExecuteFn+ ) -> StructuredTool:+ """Wraps composio tool as Langchain StructuredTool object."""+ return t.cast(+ StructuredTool,+ StructuredTool.from_function(+ name=tool.slug,+ description=tool.description,+ args_schema=json_schema_to_model(+ json_schema=tool.input_parameters,+ skip_default=True, # make configurable+ ),+ return_schema=True,+ func=self._wrap_action(+ tool=tool.slug,+ description=tool.description,+ schema_params=tool.input_parameters,+ execute_tool=execute_tool,+ ),+ handle_tool_error=True,+ handle_validation_error=True,+ ),+ )++ def wrap_tools(+ self,+ tools: t.Sequence[Tool],+ execute_tool: AgenticProviderExecuteFn,+ ) -> t.List[StructuredTool]:+ """+ Get composio tools wrapped as Langchain StructuredTool objects.+ """+ return [self.wrap_tool(tool=tool, execute_tool=execute_tool) for tool in tools]diff --git a/python/providers/langgraph/composio_langgraph/py.typed b/python/providers/langgraph/composio_langgraph/py.typednew file mode 100644index 000000000..e69de29bbdiff --git a/python/providers/langgraph/langgraph_demo.py b/python/providers/langgraph/langgraph_demo.pynew file mode 100644index 000000000..a13ea3b8e--- /dev/null+++ b/python/providers/langgraph/langgraph_demo.py@@ -0,0 +1,97 @@+import json+import operator+from typing import Annotated, Sequence, TypedDict++from composio_langgraph import LanggraphProvider+from langchain_core.messages import BaseMessage, FunctionMessage, HumanMessage+from langchain_core.utils.function_calling import convert_to_openai_function+from langchain_openai import ChatOpenAI+from langgraph.graph import END, StateGraph++from composio import Composio++composio = Composio(provider=LanggraphProvider())+tools = composio.tools.get(+ user_id="default",+ tools=[+ "GITHUB_STAR_A_REPOSITORY_FOR_THE_AUTHENTICATED_USER",+ "GITHUB_GET_THE_AUTHENTICATED_USER",+ ],+)+functions = [convert_to_openai_function(t) for t in tools]+model = ChatOpenAI(temperature=0, streaming=True).bind_functions(functions)+++def function_1(state):+ messages = state["messages"]+ response = model.invoke(messages)+ return {"messages": [response]}+++def function_2(state):+ messages = state["messages"]+ last_message = messages[-1]++ parsed_function_call = last_message.additional_kwargs["function_call"]++ # Find the correct tool to use from the provided list of tools.+ tool_to_use = None+ for t in tools:+ if t.name == parsed_function_call["name"]:+ tool_to_use = t+ break++ if tool_to_use is None:+ raise ValueError(f"Tool with name {parsed_function_call['name']} not found.")++ response = tool_to_use.invoke(json.loads(parsed_function_call["arguments"]))++ function_message = FunctionMessage(+ content=str(response), name=parsed_function_call["name"]+ )++ return {"messages": [function_message]}+++def where_to_go(state):+ messages = state["messages"]+ last_message = messages[-1]++ if "function_call" in last_message.additional_kwargs:+ return "continue"+ return "end"+++class AgentState(TypedDict):+ messages: Annotated[Sequence[BaseMessage], operator.add]+++workflow = StateGraph(AgentState)+workflow.add_node("agent", function_1)+workflow.add_node("tool", function_2)+workflow.add_conditional_edges(+ "agent",+ where_to_go,+ {+ # If return is "continue" then we call the tool node.+ "continue": "tool",+ # Otherwise we finish. END is a special node marking+ # that the graph should finish.+ "end": END,+ },+)+workflow.add_edge("tool", "agent")+workflow.set_entry_point("agent")++app = workflow.compile()+inputs = {+ "messages": [+ HumanMessage(content="Star a repo composiohq/composio on GitHub"),+ ]+}+for output in app.stream(inputs): # type: ignore+ for key, value in output.items():+ print(f"Output from node '{key}':")+ print("---")+ print(value)+ print("\n---\n")diff --git a/python/providers/langgraph/langgraph_demo_toolnode.py b/python/providers/langgraph/langgraph_demo_toolnode.pynew file mode 100644index 000000000..ff2d513f4--- /dev/null+++ b/python/providers/langgraph/langgraph_demo_toolnode.py@@ -0,0 +1,62 @@+from typing import Literal++from composio_langgraph import LanggraphProvider+from langchain_openai import ChatOpenAI+from langgraph.graph import MessagesState, StateGraph+from langgraph.prebuilt import ToolNode++from composio import Composio++composio = Composio(provider=LanggraphProvider())+tools = composio.tools.get(+ user_id="default",+ tools=[+ "GITHUB_STAR_A_REPOSITORY_FOR_THE_AUTHENTICATED_USER",+ "GITHUB_GET_THE_AUTHENTICATED_USER",+ ],+)+tool_node = ToolNode(tools)+model_with_tools = ChatOpenAI(temperature=0, streaming=True).bind_tools(tools)+++def should_continue(state: MessagesState) -> Literal["tools", "__end__"]:+ messages = state["messages"]+ last_message = messages[-1]+ if last_message.tool_calls: # type: ignore+ return "tools"+ return "__end__"+++def call_model(state: MessagesState):+ messages = state["messages"]+ response = model_with_tools.invoke(messages)+ return {"messages": [response]}+++workflow = StateGraph(MessagesState)++# Define the two nodes we will cycle between+workflow.add_node("agent", call_model)+workflow.add_node("tools", tool_node)++workflow.add_edge("__start__", "agent")+workflow.add_conditional_edges(+ "agent",+ should_continue,+)+workflow.add_edge("tools", "agent")++app = workflow.compile()++for chunk in app.stream(+ {+ "messages": [+ ( # type: ignore+ "human",+ "Star the Github Repository composiohq/composio",+ )+ ]+ },+ stream_mode="values",+):+ chunk["messages"][-1].pretty_print()diff --git a/python/providers/langgraph/pyproject.toml b/python/providers/langgraph/pyproject.tomlnew file mode 100644index 000000000..6ec15d7c7--- /dev/null+++ b/python/providers/langgraph/pyproject.toml@@ -0,0 +1,20 @@+[project]+name = "composio-langgraph"+version = "1.0.0-rc6"+description = "Use Composio to get array of tools with LangGraph Agent Workflows."+readme = "README.md"+requires-python = ">=3.9,<4"+authors = [+ { name = "Composio", email = "[email protected]" }+]+classifiers = [+ "Programming Language :: Python :: 3",+ "License :: OSI Approved :: Apache Software License",+ "Operating System :: OS Independent",+]+dependencies = [+ "langgraph",+]++[project.urls]+Homepage = "https://github.com/ComposioHQ/composio"diff --git a/python/providers/langgraph/setup.py b/python/providers/langgraph/setup.pynew file mode 100644index 000000000..b181ff172--- /dev/null+++ b/python/providers/langgraph/setup.py@@ -0,0 +1,26 @@+"""+Setup configuration for Composio LangGraph plugin+"""++from pathlib import Path++from setuptools import setup++setup(+ name="composio_langgraph",+ version="1.0.0-rc6",+ author="composio",+ author_email="[email protected]",+ description="Use Composio to get array of tools with LangGraph Agent Workflows",+ long_description=(Path(__file__).parent / "README.md").read_text(encoding="utf-8"),+ long_description_content_type="text/markdown",+ url="https://github.com/ComposioHQ/composio",+ classifiers=[+ "Programming Language :: Python :: 3",+ "License :: OSI Approved :: Apache Software License",+ "Operating System :: OS Independent",+ ],+ python_requires=">=3.9,<4",+ install_requires=["langgraph"],+ include_package_data=True,+)