forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjoke_agent.py
More file actions
90 lines (73 loc) · 2.22 KB
/
Copy pathjoke_agent.py
File metadata and controls
90 lines (73 loc) · 2.22 KB
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
"""Test Joker Agent"""
from typing import Any, cast
from langchain_openai import ChatOpenAI
from langgraph.graph import StateGraph, END
from langgraph.graph import MessagesState
from langgraph.checkpoint.memory import MemorySaver
from langchain_core.runnables import RunnableConfig
from langchain_core.messages import SystemMessage, ToolMessage
from copilotkit.langchain import copilotkit_customize_config, copilotkit_exit
class JokeAgentState(MessagesState):
"""Joke Agent State"""
joke: str
async def joke_node(state: JokeAgentState, config: RunnableConfig):
"""
Make a joke.
"""
config = copilotkit_customize_config(
config,
emit_messages=True,
emit_intermediate_state=[
{
"state_key": "joke",
"tool": "make_joke",
"tool_argument": "the_joke"
},
]
)
system_message = "You make funny jokes."
joke_tool = {
'name': 'make_joke',
'description': """Make a funny joke.""",
'parameters': {
'type': 'object',
'properties': {
'the_joke': {
'description': """The joke""",
'type': 'string',
}
},
'required': ['the_joke']
}
}
joke_model = ChatOpenAI(model="gpt-4o").bind_tools(
[joke_tool],
parallel_tool_calls=False,
tool_choice="make_joke"
)
response = await joke_model.ainvoke([
*state["messages"],
SystemMessage(
content=system_message
)
], config)
tool_calls = getattr(response, "tool_calls")
joke = tool_calls[0]["args"]["the_joke"]
await copilotkit_exit(config)
return {
"messages": [
response,
ToolMessage(
name=tool_calls[0]["name"],
content=joke,
tool_call_id=tool_calls[0]["id"]
)
],
"joke": joke,
}
workflow = StateGraph(JokeAgentState)
workflow.add_node("joke_node", cast(Any, joke_node))
workflow.set_entry_point("joke_node")
workflow.add_edge("joke_node", END)
memory = MemorySaver()
joke_graph = workflow.compile(checkpointer=memory)