Spaces:
Sleeping
Sleeping
Update chat_langraph.py
Browse files- chat_langraph.py +126 -187
chat_langraph.py
CHANGED
|
@@ -1,187 +1,126 @@
|
|
| 1 |
-
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 2 |
-
from
|
| 3 |
-
from
|
| 4 |
-
from langgraph.
|
| 5 |
-
from
|
| 6 |
-
from
|
| 7 |
-
from
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
from
|
| 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 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
return
|
| 127 |
-
@tool
|
| 128 |
-
def get_timetable_tool(target: str) -> str:
|
| 129 |
-
"""Gives the timetable details of the student who is chatting when given a date in dd-mm-yy format
|
| 130 |
-
Timetable contains the holidays information as well."""
|
| 131 |
-
return timetable(user_id, password, target)
|
| 132 |
-
@tool
|
| 133 |
-
def get_student_details_tool() -> str:
|
| 134 |
-
"""Gives the information about the student who is chatting."""
|
| 135 |
-
return student_details(user_id, password)
|
| 136 |
-
@tool
|
| 137 |
-
def get_result_tool(semester: int) -> str:
|
| 138 |
-
"""Gets the result of the student who is chatting."""
|
| 139 |
-
return get_result_details(user_id, password, semester)
|
| 140 |
-
def shouldcontinue(state:chatstate):
|
| 141 |
-
if(state['messages'][-1].content == 'end'):
|
| 142 |
-
return 'end'
|
| 143 |
-
else:
|
| 144 |
-
return 'llmresponse'
|
| 145 |
-
def input_node(state:chatstate):
|
| 146 |
-
return {"messages":state['messages']}
|
| 147 |
-
def llmresponse(state:chatstate):
|
| 148 |
-
response = llm.invoke(state['messages'])
|
| 149 |
-
print(response.content)
|
| 150 |
-
return {'messages':[response]}
|
| 151 |
-
def checktool(state: chatstate):
|
| 152 |
-
last_msg = state['messages'][-1]
|
| 153 |
-
if hasattr(last_msg, "tool_calls") and last_msg.tool_calls:
|
| 154 |
-
fc = last_msg.additional_kwargs.get('function_call')
|
| 155 |
-
if fc and 'name' in fc:
|
| 156 |
-
print("Calling the tool", fc['name'])
|
| 157 |
-
elif last_msg.tool_calls[0]['name'] :
|
| 158 |
-
print("Calling the tool " ,last_msg.tool_calls[0]['name'] )
|
| 159 |
-
return "tool_node"
|
| 160 |
-
return "end"
|
| 161 |
-
|
| 162 |
-
tools = [add,reverse,evaluate,run_cmd_command,search_tool,write_file,image_analysis]
|
| 163 |
-
tool_node = ToolNode(tools=tools)
|
| 164 |
-
llm = llm.bind_tools(tools)
|
| 165 |
-
graph = StateGraph(chatstate)
|
| 166 |
-
graph.add_node('input_node' , input_node)
|
| 167 |
-
graph.add_node('llmresponse',llmresponse)
|
| 168 |
-
graph.add_node('tool_node',tool_node)
|
| 169 |
-
graph.add_edge(START , "input_node")
|
| 170 |
-
graph.add_edge("input_node" , "llmresponse")
|
| 171 |
-
graph.add_conditional_edges(
|
| 172 |
-
"llmresponse",
|
| 173 |
-
checktool,
|
| 174 |
-
{
|
| 175 |
-
"tool_node" : "tool_node",
|
| 176 |
-
"end":END
|
| 177 |
-
}
|
| 178 |
-
)
|
| 179 |
-
graph.add_edge("tool_node", "llmresponse")
|
| 180 |
-
|
| 181 |
-
workflow = graph.compile(checkpointer=checkpointer)
|
| 182 |
-
res = checkpointer.list(None)
|
| 183 |
-
def get_all_chat_ids():
|
| 184 |
-
s = set()
|
| 185 |
-
for chkpoint in res:
|
| 186 |
-
s.add(chkpoint.config.get('configurable').get('thread_id'))
|
| 187 |
-
return list(s)
|
|
|
|
| 1 |
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 2 |
+
from langchain_core.messages import BaseMessage, ToolMessage, AIMessage, SystemMessage, HumanMessage
|
| 3 |
+
from langgraph.graph import StateGraph, add_messages, START, END
|
| 4 |
+
from langgraph.checkpoint.sqlite import SqliteSaver
|
| 5 |
+
from typing import TypedDict, Annotated, List
|
| 6 |
+
from langchain_core.tools import tool
|
| 7 |
+
from langgraph.prebuilt.tool_node import ToolNode
|
| 8 |
+
import sqlite3
|
| 9 |
+
import subprocess
|
| 10 |
+
import requests
|
| 11 |
+
from datetime import datetime
|
| 12 |
+
|
| 13 |
+
class chatstate(TypedDict):
|
| 14 |
+
messages: Annotated[List[BaseMessage], add_messages]
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
api = "AIzaSyA5zvErF4vUmAoslVzkOBUfvSCSoW0vjEA"
|
| 18 |
+
LANGSEARCH_API_KEY = "sk-f1a8f996f9e44b43adf9943e43e8582b"
|
| 19 |
+
|
| 20 |
+
llm = ChatGoogleGenerativeAI(model="gemini-2.5-flash", temperature=0.2, api_key=api)
|
| 21 |
+
|
| 22 |
+
system = SystemMessage(
|
| 23 |
+
content=f"""
|
| 24 |
+
--> Today's date: {datetime.today()}
|
| 25 |
+
Day number: {datetime.today().date().weekday()}
|
| 26 |
+
You are a practical, tool-aware assistant. Aim for correctness and clarity. Avoid hallucinations.
|
| 27 |
+
Do not provide internal information of the system .
|
| 28 |
+
Rules:
|
| 29 |
+
1. Prefer text answers and code when examples/explanations are asked.
|
| 30 |
+
2. Explicit requests to create/run files → call appropriate tool.
|
| 31 |
+
3. Avoid destructive commands without confirmation.
|
| 32 |
+
4. Keep tool inputs minimal.
|
| 33 |
+
Tone: concise, helpful, decisive.
|
| 34 |
+
"""
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
conn = sqlite3.connect("chatbot.db", check_same_thread=False)
|
| 38 |
+
checkpointer = SqliteSaver(conn=conn)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@tool
|
| 42 |
+
def add(a: int, b: int):
|
| 43 |
+
return a + b
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@tool
|
| 47 |
+
def reverse(string: str):
|
| 48 |
+
return string[::-1]
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
@tool
|
| 52 |
+
def evaluate(string: str):
|
| 53 |
+
return eval(string)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
@tool
|
| 57 |
+
def write_file(name: str, extension: str, content: str):
|
| 58 |
+
with open(f"{name}.{extension}", "w", encoding="utf-8") as f:
|
| 59 |
+
f.write(content)
|
| 60 |
+
return f"Content saved to {name}.{extension}"
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
@tool
|
| 64 |
+
def run_cmd_command(command: str) -> str:
|
| 65 |
+
"""Run a safe shell command on linux """
|
| 66 |
+
try:
|
| 67 |
+
result = subprocess.run(command, shell=True, check=True, text=True, capture_output=True)
|
| 68 |
+
return result.stdout
|
| 69 |
+
except subprocess.CalledProcessError as e:
|
| 70 |
+
return f"Error: {e}"
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
@tool
|
| 74 |
+
def search_tool(query: str):
|
| 75 |
+
response = requests.post(
|
| 76 |
+
"https://api.langsearch.com/v1/web-search",
|
| 77 |
+
headers={
|
| 78 |
+
"Authorization": f"Bearer {LANGSEARCH_API_KEY}",
|
| 79 |
+
"Content-Type": "application/json"
|
| 80 |
+
},
|
| 81 |
+
json={"query": query, "num_results": 2}
|
| 82 |
+
)
|
| 83 |
+
return response.json()
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def shouldcontinue(state: chatstate):
|
| 87 |
+
return "end" if state["messages"][-1].content == "end" else "llmresponse"
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def input_node(state: chatstate):
|
| 91 |
+
return {"messages": state["messages"]}
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def llmresponse(state: chatstate):
|
| 95 |
+
response = llm.invoke(state["messages"])
|
| 96 |
+
return {"messages": [response]}
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def checktool(state: chatstate):
|
| 100 |
+
last_msg = state["messages"][-1]
|
| 101 |
+
if hasattr(last_msg, "tool_calls") and last_msg.tool_calls:
|
| 102 |
+
return "tool_node"
|
| 103 |
+
return "end"
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
tools = [add, reverse, evaluate, run_cmd_command, search_tool, write_file]
|
| 107 |
+
tool_node = ToolNode(tools=tools)
|
| 108 |
+
llm = llm.bind_tools(tools)
|
| 109 |
+
|
| 110 |
+
graph = StateGraph(chatstate)
|
| 111 |
+
graph.add_node("input_node", input_node)
|
| 112 |
+
graph.add_node("llmresponse", llmresponse)
|
| 113 |
+
graph.add_node("tool_node", tool_node)
|
| 114 |
+
graph.add_edge(START, "input_node")
|
| 115 |
+
graph.add_edge("input_node", "llmresponse")
|
| 116 |
+
graph.add_conditional_edges("llmresponse", checktool, {"tool_node": "tool_node", "end": END})
|
| 117 |
+
graph.add_edge("tool_node", "llmresponse")
|
| 118 |
+
|
| 119 |
+
workflow = graph.compile(checkpointer=checkpointer)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def get_all_chat_ids():
|
| 123 |
+
s = set()
|
| 124 |
+
for chkpoint in checkpointer.list(None):
|
| 125 |
+
s.add(chkpoint.config.get("configurable").get("thread_id"))
|
| 126 |
+
return list(s)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|