File size: 10,365 Bytes
27eb7af a66797c 27eb7af a66797c 27eb7af |
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 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 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 |
import json, re
import operator
from itertools import chain
from pathlib import Path
from dotenv import load_dotenv
from datetime import datetime
from typing import List, Dict, Any, TypedDict, Annotated, Optional
from langgraph.graph import StateGraph, END
from langchain_core.messages import AnyMessage, SystemMessage, ToolMessage, HumanMessage, AIMessage
from langchain_core.language_models import BaseLanguageModel
from langchain_core.tools import BaseTool
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
_ = load_dotenv()
class ToolCallLog(TypedDict):
"""
A TypedDict representing a log entry for a tool call.
Attributes:
timestamp (str): The timestamp of when the tool call was made.
tool_call_id (str): The unique identifier for the tool call.
name (str): The name of the tool that was called.
args (Any): The arguments passed to the tool.
content (str): The content or result of the tool call.
"""
timestamp: str
tool_call_id: str
name: str
args: Any
content: str
class AgentState(TypedDict):
"""
A TypedDict representing the state of an agent.
Attributes:
messages (Annotated[List[AnyMessage], operator.add]): A list of messages
representing the conversation history. The operator.add annotation
indicates that new messages should be appended to this list.
"""
messages: Annotated[List[AnyMessage], operator.add]
class ChatAgent:
"""
A class representing an agent that processes requests and executes tools based on
language model responses.
Attributes:
model (BaseLanguageModel): The language model used for processing.
tools (Dict[str, BaseTool]): A dictionary of available tools.
checkpointer (Any): Manages and persists the agent's state.
system_prompt (str): The system instructions for the agent.
workflow (StateGraph): The compiled workflow for the agent's processing.
log_tools (bool): Whether to log tool calls.
log_path (Path): Path to save tool call logs.
"""
def __init__(
self,
model: BaseLanguageModel,
tools: List[BaseTool],
checkpointer: Any = None,
prompts: Dict[str, str] = {},
log_tools: bool = True,
log_dir: Optional[str] = "logs",
):
"""
Initialize the Agent.
Args:
model (BaseLanguageModel): The language model to use.
tools (List[BaseTool]): A list of available tools.
checkpointer (Any, optional): State persistence manager. Defaults to None.
prompts (Dict[str, str], optional): System instructions. Defaults to {}.
log_tools (bool, optional): Whether to log tool calls. Defaults to True.
log_dir (str, optional): Directory to save logs. Defaults to 'logs'.
"""
self.prompts = prompts
self.log_tools = log_tools
self.checkpointer = checkpointer
if self.log_tools:
self.log_path = Path(log_dir or "logs")
self.log_path.mkdir(exist_ok=True)
# Define the agent workflow
workflow = StateGraph(AgentState)
workflow.add_node("process", self.process_request)
workflow.add_node("execute", self.execute_tools)
workflow.add_node("summarize", self.summarize_message)
workflow.add_conditional_edges(
"process", self.has_tool_calls, {True: "execute", False: END}
)
workflow.add_edge("execute", "process")
workflow.set_entry_point("process")
self.workflow = workflow.compile(checkpointer=self.checkpointer)
self.tools = {t.name: t for t in tools}
self.model = model.bind_tools(tools)
def process_request(self, state: AgentState) -> Dict[str, List[AnyMessage]]:
"""
Process the request using the language model.
Args:
state (AgentState): The current state of the agent.
Returns:
Dict[str, List[AnyMessage]]: A dictionary containing the model's response.
"""
messages = state["messages"]
# print('process_request input', state)
if self.prompts:
messages = [SystemMessage(content=self.prompts["MEDICAL_ASSISTANT"])] + messages
response = self.model.invoke(messages)
# print('process_request output', response)
return {"messages": [response]}
def has_tool_calls(self, state: AgentState) -> bool:
"""
Check if the response contains any tool calls.
Args:
state (AgentState): The current state of the agent.
Returns:
bool: True if tool calls exist, False otherwise.
"""
response = state["messages"][-1]
return len(response.tool_calls) > 0
def execute_tools(self, state: AgentState) -> Dict[str, List[ToolMessage]]:
"""
Execute tool calls from the model's response.
Args:
state (AgentState): The current state of the agent.
Returns:
Dict[str, List[ToolMessage]]: A dictionary containing tool execution results.
"""
tool_calls = state["messages"][-1].tool_calls
results = []
for call in tool_calls:
# print(f"Executing tool: {call}")
if call["name"] not in self.tools:
print("\n....invalid tool....")
result = "invalid tool, please retry"
else:
result = self.tools[call["name"]].invoke(call["args"])
results.append(
ToolMessage(
tool_call_id=call["id"],
name=call["name"],
args=call["args"],
content=str(result),
)
)
self._save_tool_calls(results)
print("Returning to model processing!")
return {"messages": results}
def summarize_message(self, thread_id: str):
"""
Summarize the previous messages using the language model.
Args:
state (AgentState): The current state of the agent.
Returns:
Dict[str, List[AnyMessage]]: A dictionary containing the model's response.
"""
# history = list(self.workflow.get_state_history({"configurable": {"thread_id": thread_id}}))
history = self.workflow.get_state({"configurable": {"thread_id": thread_id}})
# all_messages = list(
# chain.from_iterable(
# snap.values.get("messages", []) for snap in reversed(history)
# )
# )
all_messages = history.values["messages"]
# print(all_messages)
chat_messages = [
{
"type": "Tool message",
"tool_name": m.name,
"content": m.content
}
for m in all_messages
if isinstance(m, ToolMessage)
]
summarize_prompt = ChatPromptTemplate.from_messages([
("system", self.prompts["SUMMARIZE_SYSTEM_PROMPT"]),
("human", self.prompts["SUMMARIZE_USER_PROMPT"])
])
llm_chain = summarize_prompt | self.model | StrOutputParser()
llm_output = llm_chain.invoke({"chat_messages": chat_messages})
cleaned_output = re.sub(r"```(?:json)?", "", llm_output, flags=re.IGNORECASE).strip()
return json.loads(cleaned_output)
# print(result_json)
# return result_json
def _save_tool_calls(self, tool_calls: List[ToolMessage]) -> None:
"""
Save tool calls to a JSON file with timestamp-based naming.
Args:
tool_calls (List[ToolMessage]): List of tool calls to save.
"""
if not self.log_tools:
return
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = self.log_path / f"tool_calls_{timestamp}.json"
logs: List[ToolCallLog] = []
for call in tool_calls:
log_entry = {
"tool_call_id": call.tool_call_id,
"name": call.name,
"args": call.args,
"content": call.content,
"timestamp": datetime.now().isoformat(),
}
logs.append(log_entry)
with open(filename, "w") as f:
json.dump(logs, f, indent=4)
def normalise_messages(self, raw: List[Any]) -> List[Dict[str, Any]]:
"""Turn mixed LangGraph snapshots into a uniform list of dicts."""
out: List[Dict[str, Any]] = []
for m in raw:
# ββ LangChain message objects ββββββββββββββββββββββββββββββ
if isinstance(m, HumanMessage):
out.append({"role": "human", "content": m.content})
elif isinstance(m, AIMessage):
out.append({"role": "ai", "content": m.content})
elif isinstance(m, ToolMessage):
out.append(
{
"role": "tool",
"name": m.name, # e.g. "chest_xray_classifier"
"content": m.content,
}
)
elif isinstance(m, SystemMessage):
out.append({"role": "system", "content": m.content})
# ββ Bare dicts coming from the client / snapshots ββββββββββ
elif isinstance(m, dict):
role = m.get("role")
payload = m.get("content")
# content might be a list of blocks (e.g. [{"type":"text","text":"hello"}])
if isinstance(payload, list):
# keep the raw structure or flatten text blocks:
text_only = " ".join(
blk["text"] for blk in payload if blk.get("type") == "text"
)
payload = text_only if text_only else payload
out.append({"role": role, "content": payload})
# ββ Fallback: stringify anything unknown ββββββββββββββββββ
else:
out.append({"role": "unknown", "content": str(m)})
return out
|