Gulzat's picture
Update app.py
f6be06c verified
raw
history blame
4.83 kB
# ───────────────────────────── app.py ─────────────────────────────────────
# NOTE: just push this one file to your HF Space repo. The bootstrap section
# installs the needed packages inside the container at first launch.
# ╭──────────────────────── 0. Bootstrap helper ─────────────────────────────╮
import importlib, subprocess, sys, os, datetime
from typing import List
def ensure(pkg: str, ver: str | None = None):
"""Import a package or pip-install it into the current env, then import."""
try:
return importlib.import_module(pkg)
except ModuleNotFoundError:
target = f"{pkg}=={ver}" if ver else pkg
print(f"[bootstrap] installing {target} …", flush=True)
subprocess.check_call([sys.executable, "-m", "pip", "install", target])
return importlib.import_module(pkg)
# minimal deps: pytz + *monolithic* langchain (0.1.x) + openai
pytz = ensure("pytz")
langchain = ensure("langchain", "0.1.16") # stable, includes tool decorator
openai_pkg = ensure("openai") # backend used by ChatOpenAI
# ╰───────────────────────────────────────────────────────────────────────────╯
# ╭──────────────────────── 1. Imports after install ────────────────────────╮
from langchain.tools import tool, Tool
from langchain.chat_models import ChatOpenAI
from langchain.agents import create_openai_functions_agent, AgentExecutor
# ╰───────────────────────────────────────────────────────────────────────────╯
# ╭──────────────────────── 2. Tool definitions ─────────────────────────────╮
@tool
def my_custom_tool(arg1: str, arg2: int) -> str:
"""A placeholder tool you can extend later.
Args:
arg1: any string
arg2: any integer
"""
return f"Received arg1='{arg1}', arg2={arg2}. Build your magic here!"
@tool
def get_current_time_in_timezone(timezone: str) -> str:
"""Return the current local time in the given IANA timezone."""
try:
tz = pytz.timezone(timezone)
return datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
except Exception as e:
return f"Error: {e}"
# ╰───────────────────────────────────────────────────────────────────────────╯
# ╭──────────────────────── 3. Build agent once ─────────────────────────────╮
tools: List[Tool] = [
Tool.from_function(my_custom_tool, name="my_custom_tool"),
Tool.from_function(get_current_time_in_timezone, name="get_current_time_in_timezone"),
]
llm = ChatOpenAI( # uses env var OPENAI_API_KEY
model = "gpt-3.5-turbo",
temperature = 0,
)
agent = create_openai_functions_agent(llm, tools)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=False)
# ╰───────────────────────────────────────────────────────────────────────────╯
# ╭──────────────────────── 4. CLI test loop (optional) ─────────────────────╮
if __name__ == "__main__":
if not os.getenv("OPENAI_API_KEY"):
print("⚠️ Please set OPENAI_API_KEY as an env-var (HF Space → Secrets).")
print("🔮 Agent ready. Type a question or 'q' to quit.")
while True:
user = input("🗣 ")
if user.lower().strip() in {"q", "quit", "exit"}:
break
result = agent_executor.invoke({"input": user})
print("🤖", result["output"])
# ╰───────────────────────────────────────────────────────────────────────────╯