Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

next
py 97 lines 2.65 KB
Raw
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")