Update app.py
Browse files
app.py
CHANGED
|
@@ -2,191 +2,65 @@ import os
|
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
| 4 |
import pandas as pd
|
| 5 |
-
from
|
| 6 |
|
| 7 |
-
# ---
|
|
|
|
| 8 |
from langchain_groq import ChatGroq
|
| 9 |
from langchain.agents import AgentExecutor, create_tool_calling_agent
|
| 10 |
from langchain_community.tools.tavily_search import TavilySearchResults
|
| 11 |
from langchain_core.prompts import ChatPromptTemplate
|
|
|
|
| 12 |
|
| 13 |
|
| 14 |
# --- Constants ---
|
| 15 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 16 |
|
| 17 |
|
| 18 |
-
# ---
|
| 19 |
-
|
| 20 |
-
class LangChainAgent:
|
| 21 |
-
def __init__(self, groq_api_key, tavily_api_key):
|
| 22 |
-
"""
|
| 23 |
-
Initializes the agent with an LLM and a set of tools.
|
| 24 |
-
"""
|
| 25 |
-
print("Initializing LangChainAgent...")
|
| 26 |
-
|
| 27 |
-
# 1. Initialize the LLM
|
| 28 |
-
# We use ChatGroq, the LangChain integration for Groq's API.
|
| 29 |
-
self.llm = ChatGroq(
|
| 30 |
-
model_name="llama3-70b-8192",
|
| 31 |
-
groq_api_key=groq_api_key,
|
| 32 |
-
temperature=0.0
|
| 33 |
-
)
|
| 34 |
-
|
| 35 |
-
# 2. Define the tools the agent can use
|
| 36 |
-
# For now, we'll just give it a web search tool.
|
| 37 |
-
self.tools = [
|
| 38 |
-
TavilySearchResults(max_results=3, tavily_api_key=tavily_api_key)
|
| 39 |
-
]
|
| 40 |
-
|
| 41 |
-
# 3. Create the Agent Prompt
|
| 42 |
-
# This tells the agent how to behave and how to use the tools.
|
| 43 |
-
prompt = ChatPromptTemplate.from_messages(
|
| 44 |
-
[
|
| 45 |
-
("system", "You are a helpful assistant. You have access to a web search tool. Respond with the final answer to the user's question."),
|
| 46 |
-
("placeholder", "{chat_history}"),
|
| 47 |
-
("human", "{input}"),
|
| 48 |
-
("placeholder", "{agent_scratchpad}"),
|
| 49 |
-
]
|
| 50 |
-
)
|
| 51 |
-
|
| 52 |
-
# 4. Create the Agent itself
|
| 53 |
-
agent = create_tool_calling_agent(self.llm, self.tools, prompt)
|
| 54 |
-
|
| 55 |
-
# 5. Create the Agent Executor
|
| 56 |
-
# This is the runtime that will actually execute the agent's logic.
|
| 57 |
-
self.agent_executor = AgentExecutor(
|
| 58 |
-
agent=agent,
|
| 59 |
-
tools=self.tools,
|
| 60 |
-
verbose=True # Set to True to see the agent's thought process
|
| 61 |
-
)
|
| 62 |
-
print("LangChainAgent initialized.")
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
def __call__(self, question: str) -> str:
|
| 66 |
-
"""
|
| 67 |
-
This method is called to answer a question.
|
| 68 |
-
It invokes the agent executor.
|
| 69 |
-
"""
|
| 70 |
-
print(f"LangChainAgent received question (first 50 chars): {question[:50]}...")
|
| 71 |
-
|
| 72 |
-
# We need to handle the case where the agent makes a mistake
|
| 73 |
-
try:
|
| 74 |
-
response = self.agent_executor.invoke({"input": question})
|
| 75 |
-
answer = response.get("output", "No answer found.")
|
| 76 |
-
except Exception as e:
|
| 77 |
-
print(f"An error occurred in the agent executor: {e}")
|
| 78 |
-
answer = f"Agent failed with an error: {e}"
|
| 79 |
-
|
| 80 |
-
print(f"LangChainAgent generated answer: {answer}")
|
| 81 |
-
return answer
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 85 |
"""
|
| 86 |
-
|
| 87 |
-
and
|
|
|
|
|
|
|
| 88 |
"""
|
| 89 |
-
|
| 90 |
-
space_id = os.getenv("SPACE_ID")
|
| 91 |
-
if profile:
|
| 92 |
-
username = f"{profile.username}"
|
| 93 |
-
print(f"User logged in: {username}")
|
| 94 |
-
else:
|
| 95 |
-
print("User not logged in.")
|
| 96 |
-
return "Please Login to Hugging Face with the button.", None
|
| 97 |
-
|
| 98 |
-
api_url = DEFAULT_API_URL
|
| 99 |
-
questions_url = f"{api_url}/questions"
|
| 100 |
-
submit_url = f"{api_url}/submit"
|
| 101 |
-
|
| 102 |
-
# 1. Instantiate Agent (using the new LangChainAgent)
|
| 103 |
try:
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
# 3. Run your Agent (same as before)
|
| 126 |
-
results_log = []
|
| 127 |
-
answers_payload = []
|
| 128 |
-
for item in questions_data:
|
| 129 |
-
task_id = item.get("task_id")
|
| 130 |
-
question_text = item.get("question")
|
| 131 |
-
if not task_id or question_text is None:
|
| 132 |
-
continue
|
| 133 |
-
submitted_answer = agent(question_text)
|
| 134 |
-
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 135 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 136 |
-
|
| 137 |
-
# 4. Prepare Submission (same as before)
|
| 138 |
-
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 139 |
-
|
| 140 |
-
# 5. Submit (same as before)
|
| 141 |
-
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 142 |
-
try:
|
| 143 |
-
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 144 |
-
response.raise_for_status()
|
| 145 |
-
result_data = response.json()
|
| 146 |
-
final_status = (
|
| 147 |
-
f"Submission Successful!\n"
|
| 148 |
-
f"User: {result_data.get('username')}\n"
|
| 149 |
-
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 150 |
-
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 151 |
-
f"Message: {result_data.get('message', 'No message received.')}"
|
| 152 |
)
|
| 153 |
-
|
| 154 |
-
|
|
|
|
|
|
|
|
|
|
| 155 |
except Exception as e:
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
return
|
| 159 |
|
| 160 |
-
# --- Build Gradio Interface (Mostly the same) ---
|
| 161 |
-
with gr.Blocks() as demo:
|
| 162 |
-
gr.Markdown("# LangChain Agent Evaluation Runner")
|
| 163 |
-
gr.Markdown(
|
| 164 |
-
"""
|
| 165 |
-
**Instructions:**
|
| 166 |
-
1. Make sure you have set `GROQ_API_KEY` and `TAVILY_API_KEY` in your Space's secrets.
|
| 167 |
-
2. Log in below. This is required for submission.
|
| 168 |
-
3. Click 'Run Evaluation' to start the agent. You can see its thought process in the application logs!
|
| 169 |
-
"""
|
| 170 |
-
)
|
| 171 |
-
gr.LoginButton()
|
| 172 |
-
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 173 |
-
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 174 |
-
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 175 |
-
run_button.click(
|
| 176 |
-
fn=run_and_submit_all,
|
| 177 |
-
outputs=[status_output, results_table]
|
| 178 |
-
)
|
| 179 |
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
else:
|
| 186 |
-
print("✅ GROQ_API_KEY secret is set.")
|
| 187 |
-
if not os.getenv("TAVILY_API_KEY"):
|
| 188 |
-
print("⚠️ WARNING: TAVILY_API_KEY secret not set.")
|
| 189 |
-
else:
|
| 190 |
-
print("✅ TAVILY_API_KEY secret is set.")
|
| 191 |
-
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 192 |
-
demo.launch(debug=True, share=False)
|
|
|
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
| 4 |
import pandas as pd
|
| 5 |
+
from io import BytesIO
|
| 6 |
|
| 7 |
+
# --- LangChain & Groq Imports ---
|
| 8 |
+
from groq import Groq
|
| 9 |
from langchain_groq import ChatGroq
|
| 10 |
from langchain.agents import AgentExecutor, create_tool_calling_agent
|
| 11 |
from langchain_community.tools.tavily_search import TavilySearchResults
|
| 12 |
from langchain_core.prompts import ChatPromptTemplate
|
| 13 |
+
from langchain.tools import Tool
|
| 14 |
|
| 15 |
|
| 16 |
# --- Constants ---
|
| 17 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 18 |
|
| 19 |
|
| 20 |
+
# --- Custom Tool Definition using Groq ---
|
| 21 |
+
def transcribe_audio_from_task_id(task_id: str) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
"""
|
| 23 |
+
Downloads an audio file for a given task_id from the scoring server,
|
| 24 |
+
transcribes it using the GROQ API with Whisper, and returns the text.
|
| 25 |
+
Use this tool ONLY when a question explicitly mentions an audio file or recording.
|
| 26 |
+
The task_id MUST be provided as the input.
|
| 27 |
"""
|
| 28 |
+
print(f"Tool 'transcribe_audio_from_task_id' (using Groq) called with task_id: {task_id}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
try:
|
| 30 |
+
# Step 1: Download the file
|
| 31 |
+
file_url = f"{DEFAULT_API_URL}/files/{task_id}"
|
| 32 |
+
print(f"Downloading audio file from: {file_url}")
|
| 33 |
+
audio_response = requests.get(file_url)
|
| 34 |
+
audio_response.raise_for_status()
|
| 35 |
+
|
| 36 |
+
# Step 2: Prepare the file for the Groq API
|
| 37 |
+
# The API expects a file-like object with a name.
|
| 38 |
+
audio_bytes = BytesIO(audio_response.content)
|
| 39 |
+
audio_bytes.name = f"{task_id}.mp3" # Give the file-like object a name
|
| 40 |
+
|
| 41 |
+
# Step 3: Initialize the Groq client and transcribe
|
| 42 |
+
print("Initializing Groq client for transcription...")
|
| 43 |
+
client = Groq(api_key=os.getenv("GROQ_API_KEY"))
|
| 44 |
+
|
| 45 |
+
print("Transcribing audio with Groq's Whisper...")
|
| 46 |
+
transcription = client.audio.transcriptions.create(
|
| 47 |
+
file=audio_bytes,
|
| 48 |
+
model="whisper-large-v3",
|
| 49 |
+
response_format="text",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
)
|
| 51 |
+
|
| 52 |
+
transcribed_text = str(transcription)
|
| 53 |
+
print(f"Transcription successful. Result: {transcribed_text}")
|
| 54 |
+
return transcribed_text
|
| 55 |
+
|
| 56 |
except Exception as e:
|
| 57 |
+
error_message = f"Error in Groq audio transcription tool: {e}"
|
| 58 |
+
print(error_message)
|
| 59 |
+
return error_message
|
| 60 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
|
| 62 |
+
# --- Agent Definition ---
|
| 63 |
+
class LangChainAgent:
|
| 64 |
+
def __init__(self, groq_api_key: str, tavily_api_key: str):
|
| 65 |
+
print("Initializing LangChainAgent...")
|
| 66 |
+
self.llm = ChatGroq(model_name="llama3-70b-8192", groq_api_key=groq
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|