Files
brojs-task-69a86305c46fd26f…/agent.py
T
2026-05-28 10:09:28 +00:00

46 lines
1.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
Simple LangChain agent demonstrating HumanintheLoop 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 assistants 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