File size: 1,594 Bytes
8417a25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
from __future__ import annotations

"""A light-weight module that exposes the BasicAgent class and DEFAULT_API_URL constant.

Importing from this file is safe in CLI/unit-test contexts because it has **no** side
effects such as instantiating a Gradio Blocks UI or requiring the optional OAuth
dependencies of Gradio.
"""

import logging

from langchain_core.messages import HumanMessage

from langraph_agent import build_graph

# Keep the public API identical to `app.py` so existing imports can be switched
# from `from app import BasicAgent, DEFAULT_API_URL` to
# `from basic_agent import BasicAgent, DEFAULT_API_URL` without further changes.
DEFAULT_API_URL: str = "https://agents-course-unit4-scoring.hf.space"


class BasicAgent:  # pylint: disable=too-few-public-methods
    """A minimal wrapper around the LangGraph agent used in this repo."""

    def __init__(self) -> None:
        # Building the graph can be an expensive operation; log it explicitly so
        # users have feedback when the constructor blocks for a moment.
        logging.debug("[BasicAgent] Building LangGraph …")
        self.agent = build_graph()
        logging.debug("[BasicAgent] LangGraph ready.")

    async def aquery(self, question: str) -> str:
        """Asynchronously ask the agent a question and return the raw answer text."""
        messages = [HumanMessage(content=question)]
        response = await self.agent.ainvoke({"messages": messages})
        if isinstance(response, dict) and response.get("messages"):
            return response["messages"][-1].content
        return str(response)