krinya's picture
Enhance agent configuration and tool management with validation and improved error handling
c7abf8d
Raw
History Blame Contribute Delete
1.76 kB
"""
Basis agent node that creates the initial agent with the system prompt.
Need to use the prompt from the prompts/system_prompt.py file
"""
import os
from typing import Dict, Any
from langchain_core.messages import SystemMessage
from langgraph.graph import MessagesState
from langchain.chat_models import init_chat_model
from dotenv import load_dotenv
from ..prompts.system_prompt import SYSTEM_PROMPT
from .tools_node import get_all_tools
# Load environment variables
load_dotenv()
def agent_node(state: MessagesState) -> Dict[str, Any]:
"""
Agent node using LangChain's built-in init_chat_model with env configuration.
Args:
state: MessagesState containing the conversation history
Returns:
Dict containing the updated messages
"""
# Get model configuration from environment variables
model_name = os.getenv("MODEL_NAME", "gpt-5-mini")
model_provider = os.getenv("MODEL_PROVIDER", "openai")
# Use LangChain's built-in init_chat_model with env config
model = init_chat_model(
model=model_name,
model_provider=model_provider,
api_key=os.getenv("OPENAI_API_KEY")
)
# Get tools and bind them using built-in method
tools = get_all_tools()
model_with_tools = model.bind_tools(tools)
# Get current messages
messages = state["messages"]
# Add system prompt if not present using built-in message handling
if not messages or not isinstance(messages[0], SystemMessage):
system_message = SystemMessage(content=SYSTEM_PROMPT)
messages = [system_message] + messages
# Generate response using built-in invoke
response = model_with_tools.invoke(messages)
return {"messages": [response]}