Update app.py
Browse files
app.py
CHANGED
|
@@ -34,7 +34,6 @@ def transcribe_audio_from_task_id(task_id: str) -> str:
|
|
| 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 |
|
|
@@ -63,4 +62,115 @@ def transcribe_audio_from_task_id(task_id: str) -> str:
|
|
| 63 |
class LangChainAgent:
|
| 64 |
def __init__(self, groq_api_key: str, tavily_api_key: str):
|
| 65 |
print("Initializing LangChainAgent...")
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
audio_response.raise_for_status()
|
| 35 |
|
| 36 |
# Step 2: Prepare the file for the Groq API
|
|
|
|
| 37 |
audio_bytes = BytesIO(audio_response.content)
|
| 38 |
audio_bytes.name = f"{task_id}.mp3" # Give the file-like object a name
|
| 39 |
|
|
|
|
| 62 |
class LangChainAgent:
|
| 63 |
def __init__(self, groq_api_key: str, tavily_api_key: str):
|
| 64 |
print("Initializing LangChainAgent...")
|
| 65 |
+
|
| 66 |
+
# THIS IS THE CORRECTED LINE
|
| 67 |
+
self.llm = ChatGroq(model_name="llama3-70b-8192", groq_api_key=groq_api_key, temperature=0.0)
|
| 68 |
+
|
| 69 |
+
# Define all available tools
|
| 70 |
+
audio_tool = Tool(
|
| 71 |
+
name="audio_transcriber",
|
| 72 |
+
func=transcribe_audio_from_task_id,
|
| 73 |
+
description="Use this tool to transcribe an audio file. The input must be the task_id of the question.",
|
| 74 |
+
)
|
| 75 |
+
self.tools = [
|
| 76 |
+
TavilySearchResults(max_results=3, tavily_api_key=tavily_api_key, name="web_search"),
|
| 77 |
+
audio_tool,
|
| 78 |
+
]
|
| 79 |
+
|
| 80 |
+
# Define the strict system prompt
|
| 81 |
+
prompt = ChatPromptTemplate.from_messages([
|
| 82 |
+
("system", (
|
| 83 |
+
"You are a powerful problem-solving agent. Your goal is to answer the user's question accurately. "
|
| 84 |
+
"You have access to the following tools: a web search tool and an audio transcription tool.\n"
|
| 85 |
+
"RULES:\n"
|
| 86 |
+
"- Carefully analyze the user's question to determine if a tool is needed.\n"
|
| 87 |
+
"- For questions requiring current information or facts, use the 'web_search' tool.\n"
|
| 88 |
+
"- For questions that mention an audio file (.mp3, recording, voice memo, etc.), use the 'audio_transcriber' tool with the provided 'task_id'.\n"
|
| 89 |
+
"- Once you have all the necessary information, you MUST provide ONLY THE FINAL ANSWER to the user's question. Do not include any extra conversation, explanations, apologies, or introductory phrases."
|
| 90 |
+
)),
|
| 91 |
+
("human", "Question: {input}\nTask ID: {task_id}"),
|
| 92 |
+
("placeholder", "{agent_scratchpad}"),
|
| 93 |
+
])
|
| 94 |
+
|
| 95 |
+
agent = create_tool_calling_agent(self.llm, self.tools, prompt)
|
| 96 |
+
self.agent_executor = AgentExecutor(agent=agent, tools=self.tools, verbose=True, handle_parsing_errors=True)
|
| 97 |
+
print("LangChainAgent initialized.")
|
| 98 |
+
|
| 99 |
+
def __call__(self, question: str, task_id: str) -> str:
|
| 100 |
+
print(f"Agent received question (ID: {task_id}): {question[:50]}...")
|
| 101 |
+
try:
|
| 102 |
+
response = self.agent_executor.invoke({"input": question, "task_id": task_id})
|
| 103 |
+
answer = response.get("output", "Agent failed to produce an answer.")
|
| 104 |
+
except Exception as e:
|
| 105 |
+
answer = f"Agent execution failed with an error: {e}"
|
| 106 |
+
print(f"Agent generated answer: {answer}")
|
| 107 |
+
return answer
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
# --- Main Application Logic ---
|
| 111 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 112 |
+
space_id = os.getenv("SPACE_ID")
|
| 113 |
+
if not profile:
|
| 114 |
+
return "Please Login to Hugging Face with the button.", None
|
| 115 |
+
username = profile.username
|
| 116 |
+
print(f"User logged in: {username}")
|
| 117 |
+
|
| 118 |
+
try:
|
| 119 |
+
groq_api_key = os.getenv("GROQ_API_KEY")
|
| 120 |
+
tavily_api_key = os.getenv("TAVILY_API_KEY")
|
| 121 |
+
if not all([groq_api_key, tavily_api_key]):
|
| 122 |
+
raise ValueError("An API key secret (GROQ or TAVILY) is missing.")
|
| 123 |
+
agent = LangChainAgent(groq_api_key=groq_api_key, tavily_api_key=tavily_api_key)
|
| 124 |
+
except Exception as e:
|
| 125 |
+
return f"Error initializing agent: {e}", None
|
| 126 |
+
|
| 127 |
+
questions_url = f"{DEFAULT_API_URL}/questions"
|
| 128 |
+
print(f"Fetching questions from: {questions_url}")
|
| 129 |
+
try:
|
| 130 |
+
response = requests.get(questions_url, timeout=20)
|
| 131 |
+
response.raise_for_status()
|
| 132 |
+
questions_data = response.json()
|
| 133 |
+
except Exception as e:
|
| 134 |
+
return f"Error fetching questions: {e}", None
|
| 135 |
+
|
| 136 |
+
results_log, answers_payload = [], []
|
| 137 |
+
for item in questions_data:
|
| 138 |
+
task_id, question_text = item.get("task_id"), item.get("question")
|
| 139 |
+
if not task_id or not question_text: continue
|
| 140 |
+
submitted_answer = agent(question=question_text, task_id=task_id)
|
| 141 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 142 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 143 |
+
|
| 144 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 145 |
+
submission_data = {"username": username, "agent_code": agent_code, "answers": answers_payload}
|
| 146 |
+
submit_url = f"{DEFAULT_API_URL}/submit"
|
| 147 |
+
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 148 |
+
try:
|
| 149 |
+
response = requests.post(submit_url, json=submission_data, timeout=90) # Increased timeout
|
| 150 |
+
response.raise_for_status()
|
| 151 |
+
result_data = response.json()
|
| 152 |
+
final_status = (f"Submission Successful!\nUser: {result_data.get('username')}\n"
|
| 153 |
+
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 154 |
+
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 155 |
+
f"Message: {result_data.get('message', 'No message received.')}")
|
| 156 |
+
return final_status, pd.DataFrame(results_log)
|
| 157 |
+
except Exception as e:
|
| 158 |
+
return f"Submission Failed: {e}", pd.DataFrame(results_log)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
# --- Gradio Interface ---
|
| 162 |
+
with gr.Blocks() as demo:
|
| 163 |
+
gr.Markdown("# Advanced Agent Evaluation Runner (Search + Groq Audio)")
|
| 164 |
+
gr.Markdown("This agent can search the web with Tavily and transcribe audio with Groq's Whisper.")
|
| 165 |
+
gr.LoginButton()
|
| 166 |
+
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 167 |
+
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 168 |
+
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 169 |
+
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
|
| 170 |
+
|
| 171 |
+
if __name__ == "__main__":
|
| 172 |
+
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 173 |
+
for key in ["GROQ_API_KEY", "TAVILY_API_KEY"]:
|
| 174 |
+
print(f"✅ {key} secret is set." if os.getenv(key) else f"⚠️ WARNING: {key} secret is not set.")
|
| 175 |
+
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 176 |
+
demo.launch(debug=True, share=False)
|