File size: 17,545 Bytes
ec1b07b 639d21f ec1b07b e790df8 1081c8c 00aced7 adf9d94 2f4d8f8 63550ea f06be5d 230d96d 67a608a 2c6f8d9 ce7387d 2577b44 fb9e704 cdc9e59 d50da91 cdc9e59 ff22768 b0cfa9f dfa6823 67a608a fb9e704 4c6d89e 27f2401 86f2a58 230d96d df58f18 230d96d 3bd69bd 5028b6b 7ddb52b 67a608a 7bc23ab 948a6f4 a09b432 ed46760 dfa6823 b5bf432 dfa6823 ff22768 dfa6823 f605354 14796a1 faf3b0b 14796a1 e790df8 14796a1 e790df8 14796a1 e790df8 14796a1 384ab5d a09b432 f535abe 845c4a7 a09b432 845c4a7 a09b432 845c4a7 617431a 8fb5f82 cafe2aa a09b432 617431a a09b432 dfa6823 a09b432 845c4a7 148f2b3 a09b432 234b682 a09b432 f535abe 148f2b3 a09b432 148f2b3 a09b432 148f2b3 ad1b760 8fb5f82 a09b432 dfa6823 a09b432 148f2b3 a09b432 234b682 04f335f 13950d2 04f335f 13950d2 fb9e704 04f335f 13950d2 04f335f 13950d2 04f335f 3923707 315329c 99cc5cd f535abe 845c4a7 315329c 3923707 f535abe 315329c 3923707 315329c 5a8d469 315329c dfa6823 99cc5cd 315329c 7da0809 eea8c7f 617431a b5bf432 f535abe 8439f94 4175faa dfa6823 2577b44 8439f94 617431a 9e82ac9 f535abe eea8c7f 2d85129 4175faa faf3b0b 2577b44 eea8c7f 8439f94 9e82ac9 f535abe 6bf14de 3981c3e 4175faa 9e82ac9 2577b44 1c7a0a7 7f78cfc 9e82ac9 f535abe 35828ac 3981c3e 4175faa 9e82ac9 2577b44 35828ac 9e82ac9 a09b432 b5bf432 f535abe 148f2b3 4175faa 9e82ac9 2577b44 9e82ac9 234b682 3923707 13950d2 f535abe 3923707 51689e7 e896d93 2577b44 3923707 b95f33c f605354 f535abe 617431a 51689e7 f605354 2577b44 617431a a412583 b40cc33 f535abe ea40888 4453360 bec1a98 f605354 2577b44 4453360 ed46760 b05f917 a412583 13950d2 35b7834 13950d2 b5bf432 ea40888 b05f917 4453360 7da0809 35828ac 0b498b7 617431a b95f33c a09b432 234b682 f605354 a412583 f155629 faf3b0b ab1c2b7 ed46760 04f335f 13950d2 12790bc fa21952 948a6f4 750bbf8 fb9e704 750bbf8 1312508 fb9e704 1312508 c0e1900 |
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 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 |
# References:
# https://docs.crewai.com/introduction
# https://ai.google.dev/gemini-api/docs
import os
import pandas as pd
from crewai import Agent, Crew, Process, Task
from crewai.tools import tool
from google import genai
from google.genai import types
from openinference.instrumentation.crewai import CrewAIInstrumentor
from phoenix.otel import register
from util import read_file
## LLMs
MANAGER_MODEL = "gpt-4.5-preview"
AGENT_MODEL = "gpt-4.1-mini"
FINAL_ANSWER_MODEL = "gemini-2.5-pro-preview-03-25"
WEB_SEARCH_MODEL = "gemini-2.5-flash-preview-04-17"
IMAGE_ANALYSIS_MODEL = "gemini-2.5-flash-preview-04-17"
AUDIO_ANALYSIS_MODEL = "gemini-2.5-flash-preview-04-17"
VIDEO_ANALYSIS_MODEL = "gemini-2.5-flash-preview-04-17"
YOUTUBE_ANALYSIS_MODEL = "gemini-2.5-flash-preview-04-17"
DOCUMENT_ANALYSIS_MODEL = "gemini-2.5-flash-preview-04-17"
CODE_GENERATION_MODEL = "gemini-2.5-flash-preview-04-17"
CODE_EXECUTION_MODEL = "gemini-2.5-flash-preview-04-17"
# LLM evaluation
PHOENIX_API_KEY = os.environ["PHOENIX_API_KEY"]
os.environ["PHOENIX_CLIENT_HEADERS"] = f"api_key={PHOENIX_API_KEY}"
os.environ["PHOENIX_COLLECTOR_ENDPOINT"] = "https://app.phoenix.arize.com"
tracer_provider = register(
auto_instrument=True,
project_name="gaia"
)
#CrewAIInstrumentor().instrument(tracer_provider=tracer_provider)
def run_crew(question, file_path):
# Tools
@tool("Web Search Tool")
def web_search_tool(question: str) -> str:
"""Given a question only, search the web to answer the question.
Args:
question (str): Question to answer
Returns:
str: Answer to the question
Raises:
RuntimeError: If processing fails"""
try:
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
response = client.models.generate_content(
model=WEB_SEARCH_MODEL,
contents=question,
config=types.GenerateContentConfig(
tools=[types.Tool(google_search=types.GoogleSearchRetrieval())]
)
)
return response.text
except Exception as e:
raise RuntimeError(f"Processing failed: {str(e)}")
@tool("Image Analysis Tool")
def image_analysis_tool(question: str, file_path: str) -> str:
"""Given a question and image file, analyze the image to answer the question.
Args:
question (str): Question about an image file
file_path (str): The image file path
Returns:
str: Answer to the question about the image file
Raises:
RuntimeError: If processing fails"""
try:
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
file = client.files.upload(file=file_path)
response = client.models.generate_content(
model=IMAGE_ANALYSIS_MODEL,
contents=[file, question]
)
return response.text
except Exception as e:
raise RuntimeError(f"Processing failed: {str(e)}")
@tool("Audio Analysis Tool")
def audio_analysis_tool(question: str, file_path: str) -> str:
"""Given a question and audio file, analyze the audio to answer the question.
Args:
question (str): Question about an audio file
file_path (str): The audio file path
Returns:
str: Answer to the question about the audio file
Raises:
RuntimeError: If processing fails"""
try:
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
file = client.files.upload(file=file_path)
response = client.models.generate_content(
model=AUDIO_ANALYSIS_MODEL,
contents=[file, question]
)
return response.text
except Exception as e:
raise RuntimeError(f"Processing failed: {str(e)}")
@tool("Video Analysis Tool")
def video_analysis_tool(question: str, file_path: str) -> str:
"""Given a question and video file, analyze the video to answer the question.
Args:
question (str): Question about a video file
file_path (str): The video file path
Returns:
str: Answer to the question about the video file
Raises:
RuntimeError: If processing fails"""
try:
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
file = client.files.upload(file=file_path)
response = client.models.generate_content(
model=VIDEO_ANALYSIS_MODEL,
contents=[file, question]
)
return response.text
except Exception as e:
raise RuntimeError(f"Processing failed: {str(e)}")
@tool("Document Analysis Tool")
def document_analysis_tool(question: str, file_path: str) -> str:
"""Given a question and document file, analyze the document to answer the question.
Args:
question (str): Question about a document file
file_path (str): The document file path
Returns:
str: Answer to the question about the document file
Raises:
RuntimeError: If processing fails"""
try:
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
file = client.files.upload(file=file_path)
response = client.models.generate_content(
model=DOCUMENT_ANALYSIS_MODEL,
contents=[file, question]
)
return response.text
except Exception as e:
raise RuntimeError(f"Processing failed: {str(e)}")
@tool("YouTube Analysis Tool")
def youtube_analysis_tool(question: str, url: str) -> str:
"""Given a question and YouTube URL, analyze the video to answer the question.
Args:
question (str): Question about a YouTube video
url (str): The YouTube video URL
Returns:
str: Answer to the question about the YouTube video
Raises:
RuntimeError: If processing fails"""
try:
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
return client.models.generate_content(
model=YOUTUBE_ANALYSIS_MODEL,
contents=types.Content(
parts=[types.Part(file_data=types.FileData(file_uri=url)),
types.Part(text=question)]
)
)
except Exception as e:
raise RuntimeError(f"Processing failed: {str(e)}")
@tool("Code Generation Tool")
def code_generation_tool(question: str, file_path: str) -> str:
"""Given a question and data file, generate and execute code to answer the question.
Args:
question (str): Question to answer
file_path (str): The data file path
Returns:
str: Answer to the question
Raises:
RuntimeError: If processing fails"""
try:
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
file_data = read_file(file_path)
response = client.models.generate_content(
model=CODE_GENERATION_MODEL,
contents=[f"{question}\n{file_data}"],
config=types.GenerateContentConfig(
tools=[types.Tool(code_execution=types.ToolCodeExecution)]
),
)
for part in response.candidates[0].content.parts:
if part.code_execution_result is not None:
return part.code_execution_result.output
except Exception as e:
raise RuntimeError(f"Processing failed: {str(e)}")
@tool("Code Execution Tool")
def code_execution_tool(question: str, file_path: str) -> str:
"""Given a question and Python file, execute the file to answer the question.
Args:
question (str): Question to answer
file_path (str): The Python file path
Returns:
str: Answer to the question
Raises:
RuntimeError: If processing fails"""
try:
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
file = client.files.upload(file=file_path)
response = client.models.generate_content(
model=CODE_EXECUTION_MODEL,
contents=[file, question],
config=types.GenerateContentConfig(
tools=[types.Tool(code_execution=types.ToolCodeExecution)]
),
)
for part in response.candidates[0].content.parts:
if part.code_execution_result is not None:
return part.code_execution_result.output
except Exception as e:
raise RuntimeError(f"Processing failed: {str(e)}")
# Agents
web_search_agent = Agent(
role="Web Search Agent",
goal="Given a question only, search the web and answer the question: {question}",
backstory="As an expert web search assistant, you search the web to answer the question.",
allow_delegation=False,
llm=AGENT_MODEL,
max_iter=2,
tools=[web_search_tool],
verbose=True
)
image_analysis_agent = Agent(
role="Image Analysis Agent",
goal="Given a question and image file, analyze the image and answer the question: {question}",
backstory="As an expert image analysis assistant, you analyze the image to answer the question.",
allow_delegation=False,
llm=AGENT_MODEL,
max_iter=2,
tools=[image_analysis_tool],
verbose=True
)
audio_analysis_agent = Agent(
role="Audio Analysis Agent",
goal="Given a question and audio file, analyze the audio and answer the question: {question}",
backstory="As an expert audio analysis assistant, you analyze the audio to answer the question.",
allow_delegation=False,
llm=AGENT_MODEL,
max_iter=2,
tools=[audio_analysis_tool],
verbose=True
)
video_analysis_agent = Agent(
role="Video Analysis Agent",
goal="Given a question and video file, analyze the video and answer the question: {question}",
backstory="As an expert video analysis assistant, you analyze the video file to answer the question.",
allow_delegation=False,
llm=AGENT_MODEL,
max_iter=2,
tools=[video_analysis_tool],
verbose=True
)
youtube_analysis_agent = Agent(
role="YouTube Analysis Agent",
goal="Given a question and YouTube URL, analyze the video and answer the question: {question}",
backstory="As an expert YouTube analysis assistant, you analyze the video to answer the question.",
allow_delegation=False,
llm=AGENT_MODEL,
max_iter=2,
tools=[youtube_analysis_tool],
verbose=True
)
document_analysis_agent = Agent(
role="Document Analysis Agent",
goal="Given a question and document file, analyze the document and answer the question: {question}",
backstory="As an expert document analysis assistant, you analyze the document to answer the question.",
allow_delegation=False,
llm=AGENT_MODEL,
max_iter=2,
tools=[document_analysis_tool],
verbose=True
)
code_generation_agent = Agent(
role="Code Generation Agent",
goal="Given a question and data file, generate and execute code to answer the question: {question}",
backstory="As an expert Python code generation assistant, you generate and execute code to answer the question.",
allow_delegation=False,
llm=AGENT_MODEL,
max_iter=3,
tools=[code_generation_tool],
verbose=True
)
code_execution_agent = Agent(
role="Code Execution Agent",
goal="Given a question and Python file, execute the file to answer the question: {question}",
backstory="As an expert Python code execution assistant, you execute code to answer the question.",
allow_delegation=False,
llm=AGENT_MODEL,
max_iter=3,
tools=[code_execution_tool],
verbose=True
)
manager_agent = Agent(
role="Manager Agent",
goal="Answer the following question. If needed, delegate to one of your coworkers. Question: {question}",
backstory="As an expert manager assistant, you answer the question.",
allow_delegation=True,
llm=MANAGER_MODEL,
max_iter=5,
verbose=True
)
# Task
manager_task = Task(
agent=manager_agent,
description="Answer the following question. If needed, delegate to one of your coworkers:\n"
"- Web Search Agent requires a question only.\n"
"- Image Analysis Agent requires a question and **.png, .jpeg, .webp, .heic, or .heif image file**.\n"
"- Audio Analysis Agent requires a question and **.wav, .mp3, .aiff, .aac, .ogg, or .flac audio file**.\n"
"- Video Analysis Agent requires a question and **.mp4, .mpeg, .mov, .avi, .x-flv, .mpg, .webm, .wmv, or .3gpp video file**.\n"
"- Document Analysis Agent requires a question and **.docx, .pptx, .pdf, .txt, .html, css, .js, .md, .xml, or .rtf document file**.\n"
"- YouTube Analysis Agent requires a question and **YouTube URL**.\n"
"- Code Generation Agent requires a question and **.csv, .xls, .xlsx, .json, or .jsonl data file**.\n"
"- Code Execution Agent requires a question and **.py Python file**.\n"
"Question: {question}",
expected_output="The answer to the question."
)
# Crew
crew = Crew(
agents=[web_search_agent,
image_analysis_agent,
audio_analysis_agent,
video_analysis_agent,
youtube_analysis_agent,
document_analysis_agent,
code_generation_agent,
code_execution_agent],
manager_agent=manager_agent,
tasks=[manager_task],
verbose=True
)
# Process
if file_path:
question = f"{question} File path: {file_path}."
initial_answer = crew.kickoff(inputs={"question": question})
final_answer = get_final_answer(FINAL_ANSWER_MODEL, question, str(initial_answer))
print("###")
print(f"Question: {question}")
print(f"Initial answer: {initial_answer}")
print(f"Final answer: {final_answer}")
print("###")
return final_answer
def get_final_answer(model, question, answer):
prompt_template = """
You are an expert question answering assistant. Given a question and an initial answer, your task is to provide the final answer.
Your final answer must be a number and/or string OR as few words as possible OR a comma-separated list of numbers and/or strings.
If you are asked for a number, don't use comma to write your number neither use units such as USD, $, percent, or % unless specified otherwise.
If you are asked for a string, don't use articles, neither abbreviations (for example cities), and write the digits in plain text unless specified otherwise.
If you are asked for a comma-separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.
If the final answer is a number, use a number not a word.
If the final answer is a string, start with an uppercase character.
If the final answer is a comma-separated list of numbers, use a space character after each comma.
If the final answer is a comma-separated list of strings, use a space character after each comma and start with a lowercase character.
Do not add any content to the final answer that is not in the initial answer.
**Question:** """ + question + """
**Initial answer:** """ + answer + """
**Example 1:** What is the biggest city in California? Los Angeles
**Example 2:** How many 'r's are in strawberry? 3
**Example 3:** What is the opposite of black? White
**Example 4:** What are the first 5 numbers in the Fibonacci sequence? 0, 1, 1, 2, 3
**Example 5:** What is the opposite of bad, worse, worst? good, better, best
**Final answer:**
"""
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
response = client.models.generate_content(
model=model,
contents=[prompt_template]
)
return response.text |