Wen-ChuangChou commited on
Commit ·
cee706e
1
Parent(s): 6dedafb
Include the option of choosing Gemini LLMs
Browse files
app.py
CHANGED
|
@@ -3,6 +3,8 @@ import gradio as gr
|
|
| 3 |
import requests
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
|
|
|
|
|
|
| 6 |
from dotenv import load_dotenv
|
| 7 |
from smolagents import DuckDuckGoSearchTool, OpenAIServerModel, CodeAgent, Tool
|
| 8 |
from blablador import Models
|
|
@@ -18,18 +20,43 @@ load_dotenv()
|
|
| 18 |
|
| 19 |
class BasicAgent:
|
| 20 |
|
| 21 |
-
def __init__(self):
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
self.agent = CodeAgent(
|
| 34 |
tools=[DuckDuckGoSearchTool()],
|
| 35 |
model=answer_llm,
|
|
@@ -38,31 +65,113 @@ class BasicAgent:
|
|
| 38 |
# verbosity_level=LogLevel.ERROR,
|
| 39 |
)
|
| 40 |
|
| 41 |
-
def __call__(self,
|
|
|
|
|
|
|
|
|
|
| 42 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 43 |
|
| 44 |
-
SYSTEM_PROMPT = "You are a general AI assistant. I will ask you a question.
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
"
|
| 54 |
-
|
| 55 |
-
#
|
| 56 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
|
| 58 |
try:
|
| 59 |
answer = self.agent.run(full_prompt)
|
|
|
|
|
|
|
|
|
|
| 60 |
print(f"Agent returning answer: {answer}")
|
|
|
|
|
|
|
| 61 |
return answer
|
| 62 |
except Exception as e:
|
| 63 |
print(f"Error running agent: {e}")
|
| 64 |
return f"Error: {e}"
|
| 65 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 68 |
"""
|
|
@@ -86,7 +195,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 86 |
|
| 87 |
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 88 |
try:
|
| 89 |
-
agent = BasicAgent()
|
| 90 |
except Exception as e:
|
| 91 |
print(f"Error instantiating agent: {e}")
|
| 92 |
return f"Error initializing agent: {e}", None
|
|
@@ -130,8 +239,13 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 130 |
file_ext = None
|
| 131 |
file_url = None
|
| 132 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
try:
|
| 134 |
submitted_answer = agent(question_text)
|
|
|
|
| 135 |
answers_payload.append({
|
| 136 |
"task_id": task_id,
|
| 137 |
"submitted_answer": submitted_answer
|
|
|
|
| 3 |
import requests
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
| 6 |
+
import sys
|
| 7 |
+
import time
|
| 8 |
from dotenv import load_dotenv
|
| 9 |
from smolagents import DuckDuckGoSearchTool, OpenAIServerModel, CodeAgent, Tool
|
| 10 |
from blablador import Models
|
|
|
|
| 20 |
|
| 21 |
class BasicAgent:
|
| 22 |
|
| 23 |
+
def __init__(self, model_provider: str = "Blablador"):
|
| 24 |
+
self.model_provider = model_provider
|
| 25 |
+
|
| 26 |
+
if model_provider == "Blablador":
|
| 27 |
+
|
| 28 |
+
models = Models(
|
| 29 |
+
api_key=os.getenv("Blablador_API_KEY")).get_model_ids()
|
| 30 |
+
model_id_blablador = 5
|
| 31 |
+
model_name = " ".join(
|
| 32 |
+
models[model_id_blablador].split(" - ")[1].split()[:2])
|
| 33 |
+
print("The agent uses the following model:", model_name)
|
| 34 |
+
|
| 35 |
+
answer_llm = OpenAIServerModel(
|
| 36 |
+
model_id=models[model_id_blablador],
|
| 37 |
+
api_base="https://helmholtz-blablador.fz-juelich.de:8000/v1",
|
| 38 |
+
api_key=os.getenv("Blablador_API_KEY"),
|
| 39 |
+
flatten_messages_as_text=True,
|
| 40 |
+
temperature=0.2)
|
| 41 |
+
|
| 42 |
+
elif model_provider == "Gemini":
|
| 43 |
+
|
| 44 |
+
# model_name = "gemini-2.5-flash-preview-05-20"
|
| 45 |
+
model_name = "gemini-2.0-flash"
|
| 46 |
+
print("The agent uses the following model:", model_name)
|
| 47 |
+
|
| 48 |
+
answer_llm = OpenAIServerModel(
|
| 49 |
+
model_id=model_name,
|
| 50 |
+
api_base=
|
| 51 |
+
"https://generativelanguage.googleapis.com/v1beta/openai/",
|
| 52 |
+
api_key=os.getenv("Gemini_API_KEY2"),
|
| 53 |
+
temperature=0.2)
|
| 54 |
+
else:
|
| 55 |
+
print(
|
| 56 |
+
f"Error: Unsupported model provider '{model_provider}'. Only 'Blablador' and 'Gemini' are supported."
|
| 57 |
+
)
|
| 58 |
+
sys.exit(1)
|
| 59 |
+
|
| 60 |
self.agent = CodeAgent(
|
| 61 |
tools=[DuckDuckGoSearchTool()],
|
| 62 |
model=answer_llm,
|
|
|
|
| 65 |
# verbosity_level=LogLevel.ERROR,
|
| 66 |
)
|
| 67 |
|
| 68 |
+
def __call__(self,
|
| 69 |
+
question: str,
|
| 70 |
+
file_url: str = "",
|
| 71 |
+
file_ext: str = "") -> str:
|
| 72 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 73 |
|
| 74 |
+
SYSTEM_PROMPT = """You are a general AI assistant. I will ask you a question.
|
| 75 |
+
Report your thoughts, and finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER].
|
| 76 |
+
YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings.
|
| 77 |
+
If you are asked for a number, don't use comma to write your number
|
| 78 |
+
neither use units such as $ or percent sign unless specified otherwise.
|
| 79 |
+
If you are asked for a string, don't use articles, neither ABBREVIATIONS, (e.g. for cities),
|
| 80 |
+
and write the digits in plain text unless specified otherwise.
|
| 81 |
+
If you are asked for a comma separated list,
|
| 82 |
+
apply the above rules depending of whether the element to be put in the list is a number or a string.
|
| 83 |
+
"""
|
| 84 |
+
|
| 85 |
+
# Prepare additional_args for file handling
|
| 86 |
+
additional_args = {}
|
| 87 |
+
|
| 88 |
+
# Handle file if provided
|
| 89 |
+
if file_url:
|
| 90 |
+
# print(f"Downloading file from: {file_url}")
|
| 91 |
+
# file_content = self._download_file(file_url, file_ext)
|
| 92 |
+
|
| 93 |
+
# if file_content is not None:
|
| 94 |
+
# # Give the file a clear name based on its extension
|
| 95 |
+
# if file_ext.lower() == 'csv':
|
| 96 |
+
# # For CSV files, try to load as DataFrame
|
| 97 |
+
# try:
|
| 98 |
+
# import io
|
| 99 |
+
# if isinstance(file_content, str):
|
| 100 |
+
# df = pd.read_csv(io.StringIO(file_content))
|
| 101 |
+
# else:
|
| 102 |
+
# df = pd.read_csv(io.BytesIO(file_content))
|
| 103 |
+
# additional_args['dataframe'] = df
|
| 104 |
+
# additional_args['csv_file'] = file_content
|
| 105 |
+
# print(f"Loaded CSV file with shape: {df.shape}")
|
| 106 |
+
# except Exception as e:
|
| 107 |
+
# print(f"Could not parse CSV file: {e}")
|
| 108 |
+
# additional_args['file_content'] = file_content
|
| 109 |
+
|
| 110 |
+
# elif file_ext.lower() in ['json']:
|
| 111 |
+
# try:
|
| 112 |
+
# import json
|
| 113 |
+
# if isinstance(file_content, bytes):
|
| 114 |
+
# file_content = file_content.decode('utf-8')
|
| 115 |
+
# json_data = json.loads(file_content)
|
| 116 |
+
# additional_args['json_data'] = json_data
|
| 117 |
+
# additional_args['file_content'] = file_content
|
| 118 |
+
# print(f"Loaded JSON file")
|
| 119 |
+
# except Exception as e:
|
| 120 |
+
# print(f"Could not parse JSON file: {e}")
|
| 121 |
+
# additional_args['file_content'] = file_content
|
| 122 |
+
|
| 123 |
+
# else:
|
| 124 |
+
# # For other file types, just pass the content
|
| 125 |
+
# additional_args['file_content'] = file_content
|
| 126 |
+
# if file_ext:
|
| 127 |
+
# additional_args['file_extension'] = file_ext
|
| 128 |
+
# print(f"Loaded {file_ext} file")
|
| 129 |
+
|
| 130 |
+
# Update the prompt to mention the file
|
| 131 |
+
# full_prompt = f"{SYSTEM_PROMPT}\n\nQuestion: {question}\n\nNote: A {file_ext} file has been provided and is available for your analysis."
|
| 132 |
+
additional_args = f"{file_url}_{file_ext}"
|
| 133 |
+
full_prompt = f"{SYSTEM_PROMPT}\n\nQuestion: {question}\n\nNote: A {file_ext} file has been provided and is available for your analysis."
|
| 134 |
+
|
| 135 |
+
# else:
|
| 136 |
+
# full_prompt = f"{SYSTEM_PROMPT}\n\nQuestion: {question}\n\nNote: Could not retrieve the file from {file_url}."
|
| 137 |
+
else:
|
| 138 |
+
full_prompt = f"{SYSTEM_PROMPT}\n\nQuestion: {question}"
|
| 139 |
+
|
| 140 |
+
# # Combine system prompt with the user question
|
| 141 |
+
# full_prompt = f"{SYSTEM_PROMPT}\n\nQuestion: {question}"
|
| 142 |
|
| 143 |
try:
|
| 144 |
answer = self.agent.run(full_prompt)
|
| 145 |
+
# answer = self.agent.run(
|
| 146 |
+
# task=full_prompt,
|
| 147 |
+
# additional_args=additional_args if additional_args else None)
|
| 148 |
print(f"Agent returning answer: {answer}")
|
| 149 |
+
if self.model_provider == "Gemini":
|
| 150 |
+
time.sleep(10)
|
| 151 |
return answer
|
| 152 |
except Exception as e:
|
| 153 |
print(f"Error running agent: {e}")
|
| 154 |
return f"Error: {e}"
|
| 155 |
|
| 156 |
+
def _download_file(self, file_url: str, file_ext: str = "") -> str:
|
| 157 |
+
"""Download file content from URL and return as text or bytes"""
|
| 158 |
+
try:
|
| 159 |
+
response = requests.get(file_url, timeout=30)
|
| 160 |
+
response.raise_for_status()
|
| 161 |
+
|
| 162 |
+
# For text files, return as string
|
| 163 |
+
if file_ext.lower() in [
|
| 164 |
+
'txt', 'csv', 'json', 'md', 'py', 'js', 'html', 'xml'
|
| 165 |
+
]:
|
| 166 |
+
return response.text
|
| 167 |
+
else:
|
| 168 |
+
# For binary files, return the content as bytes
|
| 169 |
+
return response.content
|
| 170 |
+
|
| 171 |
+
except Exception as e:
|
| 172 |
+
print(f"Error downloading file from {file_url}: {e}")
|
| 173 |
+
return None
|
| 174 |
+
|
| 175 |
|
| 176 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 177 |
"""
|
|
|
|
| 195 |
|
| 196 |
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 197 |
try:
|
| 198 |
+
agent = BasicAgent("Blablador")
|
| 199 |
except Exception as e:
|
| 200 |
print(f"Error instantiating agent: {e}")
|
| 201 |
return f"Error initializing agent: {e}", None
|
|
|
|
| 239 |
file_ext = None
|
| 240 |
file_url = None
|
| 241 |
|
| 242 |
+
if file_name:
|
| 243 |
+
file_ext = file_name.split('.')[-1].lower()
|
| 244 |
+
file_url = f"{api_url}/files/{task_id}"
|
| 245 |
+
|
| 246 |
try:
|
| 247 |
submitted_answer = agent(question_text)
|
| 248 |
+
# submitted_answer = agent(question_text, file_url, file_ext)
|
| 249 |
answers_payload.append({
|
| 250 |
"task_id": task_id,
|
| 251 |
"submitted_answer": submitted_answer
|