File size: 3,232 Bytes
8417a25 fe36046 8417a25 fe36046 8417a25 fe36046 8417a25 fe36046 8417a25 fe36046 8417a25 fe36046 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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
import os
import sys
import tempfile
import requests
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Add the current directory to Python path
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
# Import the new agent system
from new_langraph_agent import run_agent, cleanup
from src.tracing import get_langfuse_callback_handler
# Default API URL - Using the same URL as the original basic_agent.py
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
# Initialize Langfuse CallbackHandler for LangGraph/Langchain (tracing)
try:
langfuse_handler = get_langfuse_callback_handler()
print("✅ Langfuse handler initialized successfully")
except Exception as e:
print(f"Warning: Could not initialize Langfuse handler: {e}")
langfuse_handler = None
def fetch_random_question(api_base: str = DEFAULT_API_URL):
"""Return JSON of /random-question."""
resp = requests.get(f"{api_base}/random-question", timeout=30)
resp.raise_for_status()
return resp.json()
def maybe_download_file(task_id: str, api_base: str = DEFAULT_API_URL) -> str | None:
"""Try to download the file associated with a given task id. Returns local path or None."""
url = f"{api_base}/files/{task_id}"
try:
resp = requests.get(url, timeout=60)
if resp.status_code != 200:
print(f"No file associated with task {task_id} (status {resp.status_code}).")
return None
# Create temp file with same name from headers if available
filename = resp.headers.get("content-disposition", "").split("filename=")[-1].strip("\"") or f"{task_id}_attachment"
tmp_path = os.path.join(tempfile.gettempdir(), filename)
with open(tmp_path, "wb") as f:
f.write(resp.content)
print(f"Downloaded attachment to {tmp_path}")
return tmp_path
except requests.HTTPError as e:
print(f"Could not download file for task {task_id}: {e}")
except Exception as e:
print(f"Error downloading file: {e}")
return None
def main():
print("Random Agent Test - New LangGraph Architecture")
print("=" * 60)
try:
# Fetch random question
q = fetch_random_question()
task_id = str(q["task_id"])
question_text = q["question"]
print("\n=== Random Question ===")
print(f"Task ID : {task_id}")
print(f"Question: {question_text}")
# Attempt to get attachment if any
attachment_path = maybe_download_file(task_id)
if attachment_path:
question_text += f"\n\nAttachment available at: {attachment_path}"
# Run the new agent system
print("\n=== Running LangGraph Agent System ===")
result = run_agent(question_text)
print("\n=== Agent Answer ===")
print(result)
except Exception as e:
print(f"Error in main execution: {e}")
import traceback
traceback.print_exc()
finally:
# Cleanup
try:
cleanup()
print("\n✅ Agent cleanup completed")
except Exception as e:
print(f"⚠️ Cleanup warning: {e}")
if __name__ == "__main__":
main() |