""" Simple LangChain agent demonstrating Human‑in‑the‑Loop middleware. The chain: 1. User prompt is passed to a PromptTemplate. 2. The template is processed by an LLM (OpenAI). 3. The output passes through the HIL middleware which prints the assistant’s answer and asks the user to confirm or modify it before returning. Run with: python agent.py Make sure you have OPENAI_API_KEY set in your environment. """ import os from langchain.prompts import PromptTemplate from langchain.schema import RunnableSequence from langchain_openai import ChatOpenAI from langchain.middleware.hil import HumanInTheLoopMiddleware api_key = os.getenv("OPENAI_API_KEY") if not api_key: raise RuntimeError("OPENAI_API_KEY environment variable is required.") llm = OpenAI(api_key=api_key, temperature=0.7) prompt_template = PromptTemplate( input_variables=["question"], template="You are a helpful assistant. Answer the following question clearly and concisely: {question}" ) chain = RunnableSequence([prompt_template, llm]) hil_chain = HumanInTheLoopMiddleware(chain) if __name__ == "__main__": while True: try: user_input = input("\nUser: ") if user_input.lower() in {"exit", "quit", "q"}: print("Goodbye!") break result = hil_chain.invoke({"question": user_input}) print(f"\nAssistant (confirmed): {result}\n") except KeyboardInterrupt: print("\nInterrupted. Exiting.") break