-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic_chatbot.py
More file actions
78 lines (55 loc) · 1.99 KB
/
Copy pathbasic_chatbot.py
File metadata and controls
78 lines (55 loc) · 1.99 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
# -*- coding: utf-8 -*-
"""Basic Chatbot
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1Y9cRwEx2q6bognGRknrfhiLZmULd-XN0
Chatbot with LangGraph
https://www.youtube.com/watch?v=gqvFmK7LpDo
"""
!pip install langgraph langsmith
!pip install langchain langchain_anthropic langchain_community
from google.colab import userdata
anthropic_api_key=userdata.get('ANTHROPIC_API_KEY')
langsmith=userdata.get('LANGSMITH_API_KEY')
print(langsmith)
import os
os.environ["LANGCHAIN_API_KEY"] = langsmith
os.environ["LANGCHAIN_TRACING_V2"]="true"
os.environ["LANGCHAIN_PROJECT"]="CourseLanggraph"
from langchain_anthropic import ChatAnthropic
llm=ChatAnthropic(anthropic_api_key=anthropic_api_key,model_name="claude-3-5-sonnet-latest")
llm
"""Start Building Chatbot Using Langgraph"""
from typing import Annotated
from typing_extensions import TypedDict
from langgraph.graph import StateGraph,START,END
from langgraph.graph.message import add_messages
class State(TypedDict):
# Messages have the type "list". The `add_messages` function
# in the annotation defines how this state key should be updated
# (in this case, it appends messages to the list, rather than overwriting them)
messages:Annotated[list,add_messages]
graph_builder=StateGraph(State)
graph_builder
def chatbot(state:State):
return {"messages":llm.invoke(state['messages'])}
graph_builder.add_node("chatbot",chatbot)
graph_builder
graph_builder.add_edge(START,"chatbot")
graph_builder.add_edge("chatbot",END)
graph=graph_builder.compile()
from IPython.display import Image, display
try:
display(Image(graph.get_graph().draw_mermaid_png()))
except Exception:
pass
while True:
user_input=input("User: ")
if user_input.lower() in ["quit","q"]:
print("Good Bye")
break
for event in graph.stream({'messages':("user",user_input)}):
print(event.values())
for value in event.values():
print(value['messages'])
print("Assistant:",value["messages"].content)