""" LangChain Agent with Gemini - Conversational + Actions Uses your existing tools and memory. """ import os import sys from typing import Dict, Any, List, Optional sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from langchain_google_genai import ChatGoogleGenerativeAI from langchain.tools import Tool from langchain.agents import AgentExecutor, create_react_agent from langchain.memory import ConversationBufferMemory from langchain.prompts import PromptTemplate from langchain_core.messages import AIMessage, HumanMessage # Your existing tools (wrapped for LangChain) from agent.tools import ( run_qa_checks, calculate_lift, calculate_slue, calculate_cant, calculate_twist, check_radius_for_speed, get_standard_limit, load_standards, parse_station_base, parse_geometry_report, get_alignment_names, compute_displacements, get_nr_limits ) def get_retriever(): """Optional RAG retriever from ChromaDB.""" try: from langchain_community.embeddings import HuggingFaceEmbeddings from langchain_chroma import Chroma chroma_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "knowledge", "chroma_db") if not os.path.exists(chroma_path): return None embedding_model = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2") vectorstore = Chroma( collection_name="track_design_knowledge", persist_directory=chroma_path, embedding_function=embedding_model ) return vectorstore.as_retriever(search_kwargs={"k": 3}) except Exception: return None def create_langchain_agent(session_state=None): """Create a LangChain agent with Gemini LLM and memory.""" # 1. LLM – Gemini api_key = os.environ.get("GEMINI_API_KEY") if not api_key: raise ValueError("GEMINI_API_KEY not found in environment variables.") llm = ChatGoogleGenerativeAI( model="gemini-3.6-flash-lite", google_api_key=api_key, temperature=0.2, convert_system_message_to_human=True, ) # 2. Tools (wrap your functions) tools = [ Tool( name="run_qa_checks", func=lambda track_no: run_qa_checks(track_no), description="Run Network Rail QA compliance checks on a track. Input: track number (int)" ), Tool( name="calculate_lift", func=lambda args: calculate_lift(args[0], args[1]) if isinstance(args, list) else calculate_lift(args.get("existing_level"), args.get("proposed_level")), description="Calculate lift/lower in mm from existing and proposed levels. Input: two floats (existing_level, proposed_level)" ), Tool( name="calculate_slue", func=lambda args: calculate_slue(args[0], args[1]) if isinstance(args, list) else calculate_slue(args.get("existing_offset"), args.get("proposed_offset")), description="Calculate slue/slew in mm from existing and proposed offsets. Input: two floats" ), Tool( name="calculate_cant", func=lambda args: calculate_cant(args[0], args[1]) if isinstance(args, list) else calculate_cant(args.get("left_level"), args.get("right_level")), description="Calculate cant/superelevation in mm from left and right rail levels. Input: two floats" ), Tool( name="calculate_twist", func=lambda args: calculate_twist(args[0], args[1], args[2]) if isinstance(args, list) else calculate_twist(args.get("level1"), args.get("level2"), args.get("distance_m")), description="Calculate twist in mm/m from two levels and distance. Input: level1, level2, distance_m" ), Tool( name="check_radius_for_speed", func=lambda args: check_radius_for_speed(args[0], args[1], args[2] if len(args)>2 else 110, args[3] if len(args)>3 else 0) if isinstance(args, list) else check_radius_for_speed(args.get("radius_m"), args.get("speed_mph"), args.get("max_cant_def_mm", 110), args.get("applied_cant_mm", 0)), description="Check if radius is sufficient for speed. Input: radius_m, speed_mph, max_cant_def_mm (optional), applied_cant_mm (optional)" ), Tool( name="get_standard_limit", func=lambda param: get_standard_limit(param), description="Get a limit value from Network Rail standards. Input: parameter name (e.g., 'lift', 'slue', 'min_radius')" ), Tool( name="load_standards", func=lambda: load_standards(), description="Load all Network Rail standards" ), Tool( name="get_nr_limits", func=lambda: get_nr_limits(), description="Get default Network Rail limits" ), Tool( name="compute_displacements", func=lambda args: compute_displacements(args[0], args[1], args[2]) if isinstance(args, list) else compute_displacements(args.get("track_data"), args.get("track_no"), args.get("chainages")), description="Compute track displacements (lift, slue, etc.). Input: track_data dict, track_no int, chainages list" ), ] # Add RAG tool if retriever available retriever = get_retriever() if retriever: rag_tool = Tool( name="search_standards", func=lambda q: "\n".join([doc.page_content for doc in retriever.get_relevant_documents(q)]), description="Search Network Rail standards and SOPs for information. Input: your question" ) tools.append(rag_tool) # 3. Memory memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True) # 4. Prompt Template (ReAct style) prompt = PromptTemplate.from_template(""" You are a Track Design Engineering Assistant with expertise in UK railway standards. You have access to the following tools: {tools} Use the following format: Question: the input question you must answer Thought: you should always think about what to do Action: the action to take, should be one of [{tool_names}] Action Input: the input to the action Observation: the result of the action ... (this Thought/Action/Action Input/Observation can repeat N times) Thought: I now know the final answer Final Answer: the final answer to the original input question Previous conversation: {chat_history} Question: {input} Thought: {agent_scratchpad} """) # Create agent agent = create_react_agent(llm, tools, prompt) # Agent executor agent_executor = AgentExecutor( agent=agent, tools=tools, memory=memory, verbose=True, handle_parsing_errors=True, max_iterations=5 ) return agent_executor