olaf-bu commited on
Commit
b08c23b
·
1 Parent(s): a383f96

ready for first run

Browse files
Files changed (5) hide show
  1. agent.py +61 -0
  2. app.py +113 -96
  3. model.py +119 -0
  4. requirements.txt +14 -2
  5. tools.py +112 -0
agent.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from logging import getLogger
2
+ from typing import Any, List, Optional
3
+
4
+ from smolagents import CodeAgent
5
+
6
+
7
+ logger = getLogger(__name__)
8
+
9
+
10
+ class Agent:
11
+ """
12
+ Agent class that wraps a CodeAgent and provides a callable interface for answering questions.
13
+
14
+ Args:
15
+ model (Any): The language model to use.
16
+ tools (Optional[List[Any]]): List of tools to provide to the agent.
17
+ prompt (Optional[str]): Custom prompt template for the agent.
18
+ """
19
+
20
+ def __init__(self, model: Any,
21
+ tools: Optional[List[Any]] = None,
22
+ prompt: Optional[str] = None,
23
+ ):
24
+ logger.info('Initializing Agent')
25
+ self.model = model
26
+ self.tools = tools
27
+ self.imports = ['pandas', 'numpy', 'os', 'requests',
28
+ 'tempfile', 'datetime', 'json', 'time', 're',
29
+ 'openpyxl', 'pathlib', 'sys',
30
+ ]
31
+ self.agent = CodeAgent(
32
+ model=self.model,
33
+ tools=self.tools,
34
+ add_base_tools=True,
35
+ additional_authorized_imports=self.imports,
36
+ )
37
+
38
+ if prompt is None:
39
+ logger.info('reading default system prompt')
40
+ with open('system_prompt2.txt') as prompt_file:
41
+ prompt = prompt_file.read()
42
+
43
+ self.prompt = prompt
44
+ logger.info('Agent initialized')
45
+
46
+ def __call__(self, question: str, file_path: Optional[str] = None) -> str:
47
+ """
48
+ Run the agent to answer a question, optionally using a file as context.
49
+
50
+ Args:
51
+ question (str): The question to answer.
52
+ file_path (Optional[str]): Path to a file to use as context (if any).
53
+
54
+ Returns:
55
+ str: The agent's answer as a string.
56
+ """
57
+ logger.debug('question is [%s]', question)
58
+ answer = self.agent.run(self.prompt.format(question=question, context=file_path))
59
+ looger.debug('got answer [%s]', answer)
60
+ answer = str(answer).strip("'").strip('"').strip()
61
+ return answer
app.py CHANGED
@@ -1,140 +1,159 @@
 
1
  import os
 
 
 
2
  import gradio as gr
3
- import requests
4
- import inspect
5
  import pandas as pd
 
 
 
 
 
6
 
7
  # (Keep Constants as is)
8
  # --- Constants ---
9
- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
 
 
 
 
 
10
 
11
- # --- Basic Agent Definition ---
12
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
13
- class BasicAgent:
14
- def __init__(self):
15
- print("BasicAgent initialized.")
16
- def __call__(self, question: str) -> str:
17
- print(f"Agent received question (first 50 chars): {question[:50]}...")
18
- fixed_answer = "This is a default answer."
19
- print(f"Agent returning fixed answer: {fixed_answer}")
20
- return fixed_answer
21
-
22
- def run_and_submit_all( profile: gr.OAuthProfile | None):
23
  """
24
- Fetches all questions, runs the BasicAgent on them, submits all answers,
25
- and displays the results.
 
 
 
 
 
26
  """
27
  # --- Determine HF Space Runtime URL and Repo URL ---
28
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
29
 
30
  if profile:
31
- username= f"{profile.username}"
32
- print(f"User logged in: {username}")
33
  else:
34
- print("User not logged in.")
35
- return "Please Login to Hugging Face with the button.", None
36
 
37
  api_url = DEFAULT_API_URL
38
- questions_url = f"{api_url}/questions"
39
- submit_url = f"{api_url}/submit"
 
40
 
41
  # 1. Instantiate Agent ( modify this part to create your agent)
42
  try:
43
- agent = BasicAgent()
44
  except Exception as e:
45
- print(f"Error instantiating agent: {e}")
46
- return f"Error initializing agent: {e}", None
47
- # In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
48
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
49
  print(agent_code)
50
 
51
  # 2. Fetch Questions
52
- print(f"Fetching questions from: {questions_url}")
53
  try:
54
  response = requests.get(questions_url, timeout=15)
55
  response.raise_for_status()
56
  questions_data = response.json()
57
  if not questions_data:
58
- print("Fetched questions list is empty.")
59
- return "Fetched questions list is empty or invalid format.", None
60
- print(f"Fetched {len(questions_data)} questions.")
61
  except requests.exceptions.RequestException as e:
62
- print(f"Error fetching questions: {e}")
63
- return f"Error fetching questions: {e}", None
64
  except requests.exceptions.JSONDecodeError as e:
65
- print(f"Error decoding JSON response from questions endpoint: {e}")
66
- print(f"Response text: {response.text[:500]}")
67
- return f"Error decoding server response for questions: {e}", None
68
  except Exception as e:
69
- print(f"An unexpected error occurred fetching questions: {e}")
70
- return f"An unexpected error occurred fetching questions: {e}", None
71
 
72
  # 3. Run your Agent
73
  results_log = []
74
  answers_payload = []
75
- print(f"Running agent on {len(questions_data)} questions...")
76
  for item in questions_data:
77
- task_id = item.get("task_id")
78
- question_text = item.get("question")
79
  if not task_id or question_text is None:
80
- print(f"Skipping item with missing task_id or question: {item}")
81
  continue
82
  try:
83
  submitted_answer = agent(question_text)
84
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
85
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
 
 
 
 
86
  except Exception as e:
87
- print(f"Error running agent on task {task_id}: {e}")
88
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
 
89
 
90
  if not answers_payload:
91
- print("Agent did not produce any answers to submit.")
92
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
93
-
94
- # 4. Prepare Submission
95
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
96
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
 
 
 
97
  print(status_update)
98
 
99
  # 5. Submit
100
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
101
  try:
102
  response = requests.post(submit_url, json=submission_data, timeout=60)
103
  response.raise_for_status()
104
  result_data = response.json()
105
  final_status = (
106
- f"Submission Successful!\n"
107
- f"User: {result_data.get('username')}\n"
108
- f"Overall Score: {result_data.get('score', 'N/A')}% "
109
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
110
- f"Message: {result_data.get('message', 'No message received.')}"
111
  )
112
- print("Submission successful.")
113
  results_df = pd.DataFrame(results_log)
114
  return final_status, results_df
115
  except requests.exceptions.HTTPError as e:
116
- error_detail = f"Server responded with status {e.response.status_code}."
117
  try:
118
  error_json = e.response.json()
119
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
120
  except requests.exceptions.JSONDecodeError:
121
- error_detail += f" Response: {e.response.text[:500]}"
122
- status_message = f"Submission Failed: {error_detail}"
123
  print(status_message)
124
  results_df = pd.DataFrame(results_log)
125
  return status_message, results_df
126
  except requests.exceptions.Timeout:
127
- status_message = "Submission Failed: The request timed out."
128
  print(status_message)
129
  results_df = pd.DataFrame(results_log)
130
  return status_message, results_df
131
  except requests.exceptions.RequestException as e:
132
- status_message = f"Submission Failed: Network error - {e}"
133
  print(status_message)
134
  results_df = pd.DataFrame(results_log)
135
  return status_message, results_df
136
  except Exception as e:
137
- status_message = f"An unexpected error occurred during submission: {e}"
138
  print(status_message)
139
  results_df = pd.DataFrame(results_log)
140
  return status_message, results_df
@@ -142,55 +161,53 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
142
 
143
  # --- Build Gradio Interface using Blocks ---
144
  with gr.Blocks() as demo:
145
- gr.Markdown("# Basic Agent Evaluation Runner")
146
  gr.Markdown(
147
  """
148
  **Instructions:**
149
 
150
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
151
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
152
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
153
 
154
  ---
155
  **Disclaimers:**
156
- Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
157
- This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
 
 
 
158
  """
159
  )
160
 
161
  gr.LoginButton()
162
 
163
- run_button = gr.Button("Run Evaluation & Submit All Answers")
164
 
165
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
166
- # Removed max_rows=10 from DataFrame constructor
167
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
168
 
169
- run_button.click(
170
- fn=run_and_submit_all,
171
- outputs=[status_output, results_table]
172
- )
173
 
174
- if __name__ == "__main__":
175
- print("\n" + "-"*30 + " App Starting " + "-"*30)
176
  # Check for SPACE_HOST and SPACE_ID at startup for information
177
- space_host_startup = os.getenv("SPACE_HOST")
178
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
179
 
180
  if space_host_startup:
181
- print(f"✅ SPACE_HOST found: {space_host_startup}")
182
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
183
  else:
184
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
185
 
186
- if space_id_startup: # Print repo URLs if SPACE_ID is found
187
- print(f"✅ SPACE_ID found: {space_id_startup}")
188
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
189
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
190
  else:
191
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
192
 
193
- print("-"*(60 + len(" App Starting ")) + "\n")
194
 
195
- print("Launching Gradio Interface for Basic Agent Evaluation...")
196
- demo.launch(debug=True, share=False)
 
1
+ import inspect
2
  import os
3
+ import tempfile
4
+ from typing import Any, Optional, Tuple
5
+
6
  import gradio as gr
7
+ import logging
 
8
  import pandas as pd
9
+ import requests
10
+
11
+ from agent import Agent
12
+ from model import get_model
13
+ from tools import get_tools
14
 
15
  # (Keep Constants as is)
16
  # --- Constants ---
17
+ DEFAULT_API_URL = 'https://agents-course-unit4-scoring.hf.space'
18
+
19
+ logging.basicConfig(level=logging.INFO,
20
+ format='%(levelname)s - %(name)s - %(asctime)s - %(message)s',
21
+ datefmt='%Y-%m-%d %H:%M:%S')
22
+ logger = logging.getLogger(__name__)
23
 
 
24
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
25
+
26
+ def run_and_submit_all(profile: Optional[gr.OAuthProfile]):
 
 
 
 
 
 
 
 
27
  """
28
+ Fetches all questions, runs the Agent on them, submits all answers, and displays the results.
29
+
30
+ Args:
31
+ profile (Optional[gr.OAuthProfile]): The OAuth profile of the user.
32
+
33
+ Returns:
34
+ Tuple[str, Optional[pd.DataFrame]]: Status message and DataFrame of results.
35
  """
36
  # --- Determine HF Space Runtime URL and Repo URL ---
37
+ space_id = os.getenv('SPACE_ID') # Get the SPACE_ID for sending link to the code
38
 
39
  if profile:
40
+ username = f'{profile.username}'
41
+ print(f'User logged in: {username}')
42
  else:
43
+ print('User not logged in.')
44
+ return 'Please Login to Hugging Face with the button.', None
45
 
46
  api_url = DEFAULT_API_URL
47
+ questions_url = f'{api_url}/questions'
48
+ submit_url = f'{api_url}/submit'
49
+ files_url = f'{api_url}/files'
50
 
51
  # 1. Instantiate Agent ( modify this part to create your agent)
52
  try:
53
+ agent = Agent(model=get_model('OpenAIServerModel', 'gpt-4.1-mini'), tools=get_tools())
54
  except Exception as e:
55
+ print(f'Error instantiating agent: {e}')
56
+ return f'Error initializing agent: {e}', None
57
+ # In the case of an app running as a hugging Face space, this link points toward your codebase (usefull for others so please keep it public)
58
+ agent_code = f'https://huggingface.co/spaces/{space_id}/tree/main'
59
  print(agent_code)
60
 
61
  # 2. Fetch Questions
62
+ print(f'Fetching questions from: {questions_url}')
63
  try:
64
  response = requests.get(questions_url, timeout=15)
65
  response.raise_for_status()
66
  questions_data = response.json()
67
  if not questions_data:
68
+ print('Fetched questions list is empty.')
69
+ return 'Fetched questions list is empty or invalid format.', None
70
+ print(f'Fetched {len(questions_data)} questions.')
71
  except requests.exceptions.RequestException as e:
72
+ print(f'Error fetching questions: {e}')
73
+ return f'Error fetching questions: {e}', None
74
  except requests.exceptions.JSONDecodeError as e:
75
+ print(f'Error decoding JSON response from questions endpoint: {e}')
76
+ print(f'Response text: {response.text[:500]}')
77
+ return f'Error decoding server response for questions: {e}', None
78
  except Exception as e:
79
+ print(f'An unexpected error occurred fetching questions: {e}')
80
+ return f'An unexpected error occurred fetching questions: {e}', None
81
 
82
  # 3. Run your Agent
83
  results_log = []
84
  answers_payload = []
85
+ print(f'Running agent on {len(questions_data)} questions...')
86
  for item in questions_data:
87
+ task_id = item.get('task_id')
88
+ question_text = item.get('question')
89
  if not task_id or question_text is None:
90
+ print(f'Skipping item with missing task_id or question: {item}')
91
  continue
92
  try:
93
  submitted_answer = agent(question_text)
94
+ answers_payload.append({'task_id': task_id,
95
+ 'submitted_answer': submitted_answer}
96
+ )
97
+ results_log.append({'Task ID': task_id,
98
+ 'Question': question_text,
99
+ 'Submitted Answer': submitted_answer})
100
  except Exception as e:
101
+ print(f'Error running agent on task {task_id}: {e}')
102
+ results_log.append({'Task ID': task_id,
103
+ 'Question': question_text,
104
+ 'Submitted Answer': f'AGENT ERROR: {e}'})
105
 
106
  if not answers_payload:
107
+ print('Agent did not produce any answers to submit.')
108
+ return 'Agent did not produce any answers to submit.', pd.DataFrame(results_log)
109
+
110
+ # 4. Prepare Submission
111
+ submission_data = {'username': username.strip(),
112
+ 'agent_code': agent_code,
113
+ 'answers': answers_payload
114
+ }
115
+ status_update = f'Agent finished. Submitting {len(answers_payload)} answers for user "{username}"...'
116
  print(status_update)
117
 
118
  # 5. Submit
119
+ print(f'Submitting {len(answers_payload)} answers to: {submit_url}')
120
  try:
121
  response = requests.post(submit_url, json=submission_data, timeout=60)
122
  response.raise_for_status()
123
  result_data = response.json()
124
  final_status = (
125
+ f'Submission Successful!\n'
126
+ f'User: {result_data.get("username")}\n'
127
+ f'Overall Score: {result_data.get("score", "N/A")}% '
128
+ f'({result_data.get("correct_count", "?")}/{result_data.get("total_attempted", "?")} correct)\n'
129
+ f'Message: {result_data.get("message", "No message received.")}'
130
  )
131
+ print('Submission successful.')
132
  results_df = pd.DataFrame(results_log)
133
  return final_status, results_df
134
  except requests.exceptions.HTTPError as e:
135
+ error_detail = f'Server responded with status {e.response.status_code}.'
136
  try:
137
  error_json = e.response.json()
138
+ error_detail += f' Detail: {error_json.get('detail', e.response.text)}'
139
  except requests.exceptions.JSONDecodeError:
140
+ error_detail += f' Response: {e.response.text[:500]}'
141
+ status_message = f'Submission Failed: {error_detail}'
142
  print(status_message)
143
  results_df = pd.DataFrame(results_log)
144
  return status_message, results_df
145
  except requests.exceptions.Timeout:
146
+ status_message = 'Submission Failed: The request timed out.'
147
  print(status_message)
148
  results_df = pd.DataFrame(results_log)
149
  return status_message, results_df
150
  except requests.exceptions.RequestException as e:
151
+ status_message = f'Submission Failed: Network error - {e}'
152
  print(status_message)
153
  results_df = pd.DataFrame(results_log)
154
  return status_message, results_df
155
  except Exception as e:
156
+ status_message = f'An unexpected error occurred during submission: {e}'
157
  print(status_message)
158
  results_df = pd.DataFrame(results_log)
159
  return status_message, results_df
 
161
 
162
  # --- Build Gradio Interface using Blocks ---
163
  with gr.Blocks() as demo:
164
+ gr.Markdown('# Basic Agent Evaluation Runner')
165
  gr.Markdown(
166
  """
167
  **Instructions:**
168
 
169
+ 1. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
170
+ 2. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
 
171
 
172
  ---
173
  **Disclaimers:**
174
+ Once clicking on the "submit button, it can take quite some time (this is the time for the agent to go through all the questions).
175
+
176
+ This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution.
177
+ For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or
178
+ even to answer the questions in async.
179
  """
180
  )
181
 
182
  gr.LoginButton()
183
 
184
+ run_button = gr.Button('Run Evaluation & Submit All Answers')
185
 
186
+ status_output = gr.Textbox(label='Run Status / Submission Result', lines=5, interactive=False)
187
+ results_table = gr.DataFrame(label='Questions and Agent Answers', wrap=True)
 
188
 
189
+ run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
 
 
 
190
 
191
+ if __name__ == '__main__':
192
+ print('\n' + '-'*30 + ' App Starting ' + '-'*30)
193
  # Check for SPACE_HOST and SPACE_ID at startup for information
194
+ space_host_startup = os.getenv('SPACE_HOST')
195
+ space_id_startup = os.getenv('SPACE_ID')
196
 
197
  if space_host_startup:
198
+ print(f'✅ SPACE_HOST found: {space_host_startup}')
199
+ print(f' Runtime URL should be: https://{space_host_startup}.hf.space')
200
  else:
201
+ print('ℹ️ SPACE_HOST environment variable not found (running locally?).')
202
 
203
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
204
+ print(f'✅ SPACE_ID found: {space_id_startup}')
205
+ print(f' Repo URL: https://huggingface.co/spaces/{space_id_startup}')
206
+ print(f' Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main')
207
  else:
208
+ print('ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.')
209
 
210
+ print('-'*(60 + len(' App Starting ')) + '\n')
211
 
212
+ print('Launching Gradio Interface for Basic Agent Evaluation...')
213
+ demo.launch(debug=True, share=False)
model.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import logging
3
+
4
+ from typing import Any, Callable
5
+
6
+ from smolagents import InferenceClientModel, LiteLLMModel, OpenAIServerModel
7
+ from smolagents import ApiModel as HfApiModel
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ def get_huggingface_api_model(model_id: str, **kwargs) -> HfApiModel:
13
+ """
14
+ Returns a Hugging Face API model instance.
15
+
16
+ Args:
17
+ model_id (str): The model identifier.
18
+ **kwargs: Additional keyword arguments for the model.
19
+
20
+ Returns:
21
+ HfApiModel: Hugging Face API model instance.
22
+ """
23
+ api_key = os.getenv('HUGGINGFACEHUB_API_TOKEN')
24
+ if not api_key:
25
+ logger.warning('HUGGINGFACEHUB_API_TOKEN not in environment')
26
+ api_key = os.getenv('HF_TOKEN')
27
+ if not api_key:
28
+ looger.error('no API Token for huggingface')
29
+ raise ValueError('neither HUGGINGFACEHUB_API_TOKEN nor HF_TOKEN is set')
30
+ logger.info('using env-var "HF_TOKEN" for Huggingface access')
31
+
32
+ return HfApiModel(model_id=model_id, token=api_key, **kwargs)
33
+
34
+
35
+ def get_inference_client_model(model_id: str, **kwargs) -> InferenceClientModel:
36
+ """
37
+ Returns an Inference Client model instance.
38
+
39
+ Args:
40
+ model_id (str): The model identifier.
41
+ **kwargs: Additional keyword arguments for the model.
42
+
43
+ Returns:
44
+ InferenceClientModel: Inference client model instance.
45
+ """
46
+ api_key = os.getenv('HUGGINGFACEHUB_API_TOKEN')
47
+ if not api_key:
48
+ logger.warning('HUGGINGFACEHUB_API_TOKEN not in environment')
49
+ api_key = os.getenv('HF_TOKEN')
50
+ if not api_key:
51
+ looger.error('no API Token for huggingface')
52
+ raise ValueError('neither HUGGINGFACEHUB_API_TOKEN nor HF_TOKEN is set')
53
+ logger.info('using env-var "HF_TOKEN" for Huggingface access')
54
+
55
+ return InferenceClientModel(model_id=model_id, token=api_key, **kwargs)
56
+
57
+
58
+ def get_openai_server_model(model_id: str, **kwargs) -> OpenAIServerModel:
59
+ """
60
+ Returns an OpenAI server model instance.
61
+
62
+ Args:
63
+ model_id (str): The model identifier.
64
+ **kwargs: Additional keyword arguments for the model.
65
+
66
+ Returns:
67
+ OpenAIServerModel: OpenAI server model instance.
68
+ """
69
+ api_key = os.getenv('OPENAI_API_KEY')
70
+ if not api_key:
71
+ looger.error('no API Token for openAI')
72
+ raise ValueError('OPENAI_API_KEY is not set')
73
+
74
+ api_base = os.getenv('OPENAI_API_BASE') # ?? should it silently default to https://api.openai.com/v1/ ?
75
+ if not api_base:
76
+ raise ValueError('OPENAI_API_BASE is not set')
77
+
78
+ return OpenAIServerModel(
79
+ model_id=model_id, api_key=api_key, api_base=api_base, **kwargs
80
+ )
81
+
82
+
83
+ def get_lite_llm_model(model_id: str, **kwargs) -> LiteLLMModel:
84
+ """
85
+ Returns a LiteLLM model instance.
86
+
87
+ Args:
88
+ model_id (str): The model identifier.
89
+ **kwargs: Additional keyword arguments for the model.
90
+
91
+ Returns:
92
+ LiteLLMModel: LiteLLM model instance.
93
+ """
94
+ return LiteLLMModel(model_id=model_id, **kwargs)
95
+
96
+
97
+ def get_model(model_type: str, model_id: str, **kwargs) -> Any:
98
+ """
99
+ Returns a model instance based on the specified type.
100
+
101
+ Args:
102
+ model_type (str): The type of the model (e.g., 'HfApiModel').
103
+ model_id (str): The model identifier.
104
+ **kwargs: Additional keyword arguments for the model.
105
+
106
+ Returns:
107
+ Any: Model instance of the specified type.
108
+ """
109
+ models = {'HfApiModel': get_huggingface_api_model,
110
+ 'InferenceClientModel': get_inference_client_model,
111
+ 'OpenAIServerModel': get_openai_server_model,
112
+ 'LiteLLMModel': get_lite_llm_model,
113
+ }
114
+
115
+ if model_type not in models:
116
+ raise ValueError(f'Unknown model type: {model_type}')
117
+
118
+ return models[model_type](model_id, **kwargs)
119
+
requirements.txt CHANGED
@@ -1,6 +1,18 @@
1
  gradio
 
2
  requests
3
- logging
4
  numpy
 
5
  pandas
6
- smolagents
 
 
 
 
 
 
 
 
 
 
 
 
1
  gradio
2
+ gradio[oauth]
3
  requests
 
4
  numpy
5
+ openpyxl
6
  pandas
7
+ pillow
8
+ pytesseract
9
+ requests
10
+ smolagents
11
+ smolagents[audio]
12
+ smolagents[openai]
13
+ smolagents[transformers]
14
+ transformers
15
+ wikipedia-api
16
+ youtube-transcript-api
17
+ openai-whisper
18
+ openai
tools.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from typing import List
3
+ import os
4
+
5
+ from smolagents import Tool, DuckDuckGoSearchTool, PythonInterpreterTool, VisitWebpageTool, WikipediaSearchTool
6
+
7
+ import whisper
8
+ from youtube_transcript_api import YouTubeTranscriptApi
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+
13
+ class ReadFileTool(Tool):
14
+ """
15
+ Tool to read a file and return its content.
16
+
17
+ Args:
18
+ file_path (str): Path to the file to read.
19
+
20
+ Returns:
21
+ str: Content of the file or error message.
22
+ """
23
+
24
+ name = 'read_file'
25
+ description = 'Reads a file and returns its content'
26
+ inputs = {
27
+ 'file_path': {'type': 'string', 'description': 'Path to the file to read'},
28
+ }
29
+ output_type = 'string'
30
+
31
+ def forward(self, file_path: str) -> str:
32
+ try:
33
+ with open(file_path, 'r') as file:
34
+ return file.read()
35
+ except Exception as e:
36
+ logger.error('error while reading attempt of %s: %s', file_path, e)
37
+ return f'Error reading file: {str(e)}'
38
+
39
+
40
+
41
+ class OpenAISpeechToTextTool(Tool):
42
+ """
43
+ Tool to convert speech to text using OpenAI's Whisper model.
44
+
45
+ Args:
46
+ audio_path (str): Path to the audio file.
47
+
48
+ Returns:
49
+ str: Transcribed text from the audio file.
50
+ """
51
+
52
+ name = 'transcribe_audio'
53
+ description = 'Transcribes audio to text and returns the text'
54
+ inputs = {
55
+ 'audio_path': {'type': 'string', 'description': 'Path to the audio file'},
56
+ }
57
+ output_type = 'string'
58
+
59
+ def forward(self, audio_path: str) -> str:
60
+ try:
61
+ model = whisper.load_model('small')
62
+
63
+ if not os.path.exists(audio_path):
64
+ return f'Error: Audio file not found at {audio_path}'
65
+
66
+ result = model.transcribe(audio_path)
67
+ return result['text']
68
+ except Exception as e:
69
+ return f'Error transcribing audio: {str(e)}'
70
+
71
+
72
+ class YouTubeTranscriptionTool(Tool):
73
+ """
74
+ Tool to fetch the transcript of a YouTube video given its URL.
75
+
76
+ Args:
77
+ video_url (str): YouTube video URL.
78
+
79
+ Returns:
80
+ str: Transcript of the video as a single string.
81
+ """
82
+
83
+ name = 'youtube_transcription'
84
+ description = 'Fetches the transcript of a YouTube video given its URL'
85
+ inputs = {
86
+ 'video_url': {'type': 'string', 'description': 'YouTube video URL'},
87
+ }
88
+ output_type = 'string'
89
+
90
+ def forward(self, video_url: str) -> str:
91
+ video_id = video_url.strip().split('v=')[-1]
92
+ transcript = YouTubeTranscriptApi.get_transcript(video_id)
93
+ return ' '.join([entry['text'] for entry in transcript])
94
+
95
+
96
+ def get_tools() -> List[Tool]:
97
+ """
98
+ Returns a list of available tools for the agent.
99
+
100
+ Returns:
101
+ List[Tool]: List of initialized tool instances.
102
+ """
103
+ tools = [
104
+ DuckDuckGoSearchTool(),
105
+ PythonInterpreterTool(),
106
+ WikipediaSearchTool(),
107
+ VisitWebpageTool(),
108
+ OpenAISpeechToTextTool(),
109
+ YouTubeTranscriptionTool(),
110
+ ReadFileTool(),
111
+ ]
112
+ return tools