Spaces:
Sleeping
Sleeping
Update agent_lang.py
Browse files- agent_lang.py +31 -0
agent_lang.py
CHANGED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from langgraph.graph import StateGraph, END
|
| 3 |
+
from langchain_core.runnables import Runnable
|
| 4 |
+
from langchain_core.messages import HumanMessage
|
| 5 |
+
from langchain_core.runnables import RunnableLambda
|
| 6 |
+
from langchain_openai import ChatOpenAI
|
| 7 |
+
|
| 8 |
+
class LangGraphAgent:
|
| 9 |
+
def __init__(self):
|
| 10 |
+
print("LangGraphAgent initialized.")
|
| 11 |
+
|
| 12 |
+
open_key = os.environ.get("OPEN_AI_KEY")
|
| 13 |
+
|
| 14 |
+
# Define a simple LangGraph that uses OpenAI to answer questions
|
| 15 |
+
self.llm = ChatOpenAI(model="gpt-4.1", temperature=0, api_key=open_key))
|
| 16 |
+
|
| 17 |
+
def answer_fn(state):
|
| 18 |
+
question = state["question"]
|
| 19 |
+
print(f"[LangGraphAgent] Received: {question[:50]}...")
|
| 20 |
+
response = self.llm.invoke([HumanMessage(content=question)])
|
| 21 |
+
return {"answer": response.content}
|
| 22 |
+
|
| 23 |
+
builder = StateGraph(state={"question": str, "answer": str})
|
| 24 |
+
builder.add_node("answer_question", RunnableLambda(answer_fn))
|
| 25 |
+
builder.set_entry_point("answer_question")
|
| 26 |
+
builder.set_finish_point("answer_question")
|
| 27 |
+
self.graph = builder.compile()
|
| 28 |
+
|
| 29 |
+
def __call__(self, question: str) -> str:
|
| 30 |
+
output = self.graph.invoke({"question": question})
|
| 31 |
+
return output["answer"]
|