Spaces:
Sleeping
Sleeping
Create chat_langraph.py
Browse files- src/chat_langraph.py +126 -0
src/chat_langraph.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)
|