Spaces:
Running
Running
RobertoBarrosoLuque
commited on
Commit
·
3a65210
1
Parent(s):
f4ca844
Add jsons
Browse files- data/fed_meetings_scraped_20250808_173732.json +0 -0
- data/fed_processed_meetings.json +0 -0
- src/app.py +140 -226
- src/modules/data_pipeline.py +58 -36
- src/modules/llm_completions.py +12 -7
data/fed_meetings_scraped_20250808_173732.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/fed_processed_meetings.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
src/app.py
CHANGED
|
@@ -10,27 +10,54 @@ from pathlib import Path
|
|
| 10 |
load_dotenv()
|
| 11 |
_FILE_PATH = Path(__file__).parents[1]
|
| 12 |
|
| 13 |
-
#
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
def simulate_llm_function_call(user_message: str, selected_model: str) -> Dict[str, Any]:
|
| 36 |
"""Simulate LLM function calls based on user intent"""
|
|
@@ -110,12 +137,12 @@ def format_response_with_reasoning(function_result: Dict[str, Any], model_name:
|
|
| 110 |
"""
|
| 111 |
return response
|
| 112 |
|
| 113 |
-
def
|
| 114 |
message: str,
|
| 115 |
history: list[tuple[str, str]],
|
| 116 |
api_key: str,
|
| 117 |
):
|
| 118 |
-
"""Enhanced response function with Fed AI Savant capabilities
|
| 119 |
|
| 120 |
if not message.strip():
|
| 121 |
yield "Please enter a question about Federal Reserve policy or FOMC meetings."
|
|
@@ -147,7 +174,7 @@ def get_fomc_meetings_sidebar():
|
|
| 147 |
"""Generate sidebar content with FOMC meeting details"""
|
| 148 |
sidebar_content = "## 📋 Recent FOMC Meetings\n\n"
|
| 149 |
|
| 150 |
-
for meeting in
|
| 151 |
sidebar_content += f"""
|
| 152 |
**{meeting['date']}**
|
| 153 |
*{meeting['title'][:50]}...*
|
|
@@ -224,7 +251,7 @@ MODEL_OPTIONS = [
|
|
| 224 |
def create_fomc_meetings_accordion():
|
| 225 |
"""Create searchable accordion for FOMC meetings"""
|
| 226 |
accordions = []
|
| 227 |
-
for meeting in
|
| 228 |
title = f"{meeting['date']} - Rate: {meeting['rate_decision']}"
|
| 229 |
content = f"""
|
| 230 |
**Meeting Title:** {meeting['title']}
|
|
@@ -246,7 +273,7 @@ with gr.Blocks(css=custom_css, title="Fed AI Savant", theme=gr.themes.Soft()) as
|
|
| 246 |
with gr.Row():
|
| 247 |
with gr.Column():
|
| 248 |
gr.Markdown("""
|
| 249 |
-
# 🏛️ Fed AI Savant
|
| 250 |
**Intelligent Analysis of Federal Reserve Policy and FOMC Meetings**
|
| 251 |
|
| 252 |
Ask questions about interest rate decisions, monetary policy changes, and economic analysis based on Federal Reserve meeting minutes.
|
|
@@ -254,16 +281,27 @@ with gr.Blocks(css=custom_css, title="Fed AI Savant", theme=gr.themes.Soft()) as
|
|
| 254 |
|
| 255 |
# Row 2: API Key Configuration
|
| 256 |
with gr.Row():
|
| 257 |
-
with gr.Column(scale=
|
| 258 |
-
gr.Markdown("###
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 259 |
api_key = gr.Textbox(
|
| 260 |
label="AI API Key",
|
| 261 |
type="password",
|
| 262 |
-
placeholder="
|
| 263 |
-
value=os.getenv("
|
| 264 |
-
info="💡 Your API key is required to analyze Fed policy using AI"
|
| 265 |
)
|
| 266 |
-
with gr.Column(scale=
|
| 267 |
gr.Markdown("### 📋 How to Use")
|
| 268 |
gr.Markdown("""
|
| 269 |
1. **Enter your AI API key** (OpenAI, Anthropic, etc.)
|
|
@@ -284,205 +322,97 @@ with gr.Blocks(css=custom_css, title="Fed AI Savant", theme=gr.themes.Soft()) as
|
|
| 284 |
lines=1
|
| 285 |
)
|
| 286 |
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
<
|
| 293 |
-
📅 2024-07-31 - Rate: 5.25-5.50%
|
| 294 |
-
</summary>
|
| 295 |
-
<div style="margin-top: 12px; padding-top: 12px; border-top: 1px solid #e5e7eb;">
|
| 296 |
-
<p><strong>Meeting:</strong> Minutes of the Federal Open Market Committee July 30-31, 2024</p>
|
| 297 |
-
<p><strong>Decision:</strong> 5.25-5.50%</p>
|
| 298 |
-
<p><strong>Summary:</strong> The Committee maintained the federal funds rate target range at 5.25-5.50%. Inflation has eased over the past year but remains elevated.</p>
|
| 299 |
-
</div>
|
| 300 |
-
</details>
|
| 301 |
-
|
| 302 |
-
<details style="border: 1px solid #e5e7eb; border-radius: 6px; padding: 12px; margin-bottom: 8px;">
|
| 303 |
-
<summary style="font-weight: 600; cursor: pointer; color: #1f2937;">
|
| 304 |
-
📅 2024-06-12 - Rate: 5.25-5.50%
|
| 305 |
-
</summary>
|
| 306 |
-
<div style="margin-top: 12px; padding-top: 12px; border-top: 1px solid #e5e7eb;">
|
| 307 |
-
<p><strong>Meeting:</strong> Minutes of the Federal Open Market Committee June 11-12, 2024</p>
|
| 308 |
-
<p><strong>Decision:</strong> 5.25-5.50%</p>
|
| 309 |
-
<p><strong>Summary:</strong> The Committee held rates steady as inflation showed signs of cooling but labor market remained robust.</p>
|
| 310 |
-
</div>
|
| 311 |
-
</details>
|
| 312 |
|
| 313 |
-
<
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
<p><strong>
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 325 |
|
| 326 |
-
# Row 4: Chat Interface
|
| 327 |
with gr.Row():
|
| 328 |
with gr.Column():
|
| 329 |
gr.Markdown("### 💬 Fed AI Assistant")
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
height=400,
|
| 344 |
-
show_label=False,
|
| 345 |
-
avatar_images=(None, None)
|
| 346 |
)
|
| 347 |
-
|
| 348 |
-
# Input row with text and audio button (larger text, smaller button)
|
| 349 |
-
with gr.Row():
|
| 350 |
-
with gr.Column(scale=10):
|
| 351 |
-
msg = gr.Textbox(
|
| 352 |
-
placeholder="Ask about Fed policy, rate decisions, or FOMC meetings...",
|
| 353 |
-
label="Your Question",
|
| 354 |
-
lines=2,
|
| 355 |
-
show_label=False
|
| 356 |
-
)
|
| 357 |
-
with gr.Column(scale=1):
|
| 358 |
-
# Audio components
|
| 359 |
-
audio_input = gr.Audio(
|
| 360 |
-
label="🎙️ Voice Input",
|
| 361 |
-
sources=["microphone"],
|
| 362 |
-
type="filepath",
|
| 363 |
-
visible=False
|
| 364 |
-
)
|
| 365 |
-
voice_btn = gr.Button("🎙️", variant="secondary", size="sm", min_width=40)
|
| 366 |
-
|
| 367 |
-
# Chat functionality
|
| 368 |
-
def user_message(message, history):
|
| 369 |
-
return "", history + [[message, None]]
|
| 370 |
|
| 371 |
-
def bot_response(history, api_key_val):
|
| 372 |
-
if history and history[-1][1] is None:
|
| 373 |
-
user_msg = history[-1][0]
|
| 374 |
-
bot_msg = ""
|
| 375 |
-
|
| 376 |
-
# Get the response generator with simplified parameters
|
| 377 |
-
response_gen = respond(user_msg, history[:-1], api_key_val)
|
| 378 |
-
|
| 379 |
-
for partial_response in response_gen:
|
| 380 |
-
bot_msg = partial_response
|
| 381 |
-
history[-1][1] = bot_msg
|
| 382 |
-
yield history
|
| 383 |
-
|
| 384 |
-
msg.submit(
|
| 385 |
-
user_message,
|
| 386 |
-
[msg, chatbot],
|
| 387 |
-
[msg, chatbot],
|
| 388 |
-
queue=False
|
| 389 |
-
).then(
|
| 390 |
-
bot_response,
|
| 391 |
-
[chatbot, api_key],
|
| 392 |
-
chatbot
|
| 393 |
-
)
|
| 394 |
-
|
| 395 |
-
# Voice functionality
|
| 396 |
-
def toggle_audio_input():
|
| 397 |
-
return gr.Audio(visible=True)
|
| 398 |
-
|
| 399 |
-
def handle_audio_input(audio_file):
|
| 400 |
-
if audio_file:
|
| 401 |
-
transcribed_text = process_audio_input(audio_file)
|
| 402 |
-
return transcribed_text, gr.Audio(visible=False)
|
| 403 |
-
return "", gr.Audio(visible=False)
|
| 404 |
-
|
| 405 |
-
def handle_tts(history):
|
| 406 |
-
if history and len(history) > 0 and history[-1][1]:
|
| 407 |
-
last_response = history[-1][1]
|
| 408 |
-
tts_message = text_to_speech(last_response)
|
| 409 |
-
return tts_message
|
| 410 |
-
return "No response to read aloud."
|
| 411 |
|
| 412 |
# Search functionality for FOMC meetings
|
| 413 |
def search_meetings(search_term):
|
| 414 |
"""Filter FOMC meetings based on search term"""
|
| 415 |
if not search_term.strip():
|
| 416 |
# Return all meetings if no search term
|
| 417 |
-
|
| 418 |
-
<div style="space-y: 8px;">
|
| 419 |
-
<details style="border: 1px solid #e5e7eb; border-radius: 6px; padding: 12px; margin-bottom: 8px;">
|
| 420 |
-
<summary style="font-weight: 600; cursor: pointer; color: #1f2937;">
|
| 421 |
-
📅 2024-07-31 - Rate: 5.25-5.50%
|
| 422 |
-
</summary>
|
| 423 |
-
<div style="margin-top: 12px; padding-top: 12px; border-top: 1px solid #e5e7eb;">
|
| 424 |
-
<p><strong>Meeting:</strong> Minutes of the Federal Open Market Committee July 30-31, 2024</p>
|
| 425 |
-
<p><strong>Decision:</strong> 5.25-5.50%</p>
|
| 426 |
-
<p><strong>Summary:</strong> The Committee maintained the federal funds rate target range at 5.25-5.50%. Inflation has eased over the past year but remains elevated.</p>
|
| 427 |
-
</div>
|
| 428 |
-
</details>
|
| 429 |
-
|
| 430 |
-
<details style="border: 1px solid #e5e7eb; border-radius: 6px; padding: 12px; margin-bottom: 8px;">
|
| 431 |
-
<summary style="font-weight: 600; cursor: pointer; color: #1f2937;">
|
| 432 |
-
📅 2024-06-12 - Rate: 5.25-5.50%
|
| 433 |
-
</summary>
|
| 434 |
-
<div style="margin-top: 12px; padding-top: 12px; border-top: 1px solid #e5e7eb;">
|
| 435 |
-
<p><strong>Meeting:</strong> Minutes of the Federal Open Market Committee June 11-12, 2024</p>
|
| 436 |
-
<p><strong>Decision:</strong> 5.25-5.50%</p>
|
| 437 |
-
<p><strong>Summary:</strong> The Committee held rates steady as inflation showed signs of cooling but labor market remained robust.</p>
|
| 438 |
-
</div>
|
| 439 |
-
</details>
|
| 440 |
-
|
| 441 |
-
<details style="border: 1px solid #e5e7eb; border-radius: 6px; padding: 12px; margin-bottom: 8px;">
|
| 442 |
-
<summary style="font-weight: 600; cursor: pointer; color: #1f2937;">
|
| 443 |
-
📅 2024-05-01 - Rate: 5.25-5.50%
|
| 444 |
-
</summary>
|
| 445 |
-
<div style="margin-top: 12px; padding-top: 12px; border-top: 1px solid #e5e7eb;">
|
| 446 |
-
<p><strong>Meeting:</strong> Minutes of the Federal Open Market Committee April 30-May 1, 2024</p>
|
| 447 |
-
<p><strong>Decision:</strong> 5.25-5.50%</p>
|
| 448 |
-
<p><strong>Summary:</strong> Officials maintained current rates while monitoring inflation progress and employment data.</p>
|
| 449 |
-
</div>
|
| 450 |
-
</details>
|
| 451 |
-
</div>
|
| 452 |
-
"""
|
| 453 |
else:
|
| 454 |
# Filter meetings based on search term
|
| 455 |
filtered_meetings = []
|
| 456 |
search_lower = search_term.lower()
|
| 457 |
|
| 458 |
-
for meeting in
|
| 459 |
-
# Search in date, title,
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 464 |
filtered_meetings.append(meeting)
|
| 465 |
|
| 466 |
if filtered_meetings:
|
| 467 |
-
|
| 468 |
-
for meeting in filtered_meetings:
|
| 469 |
-
html_content += f"""
|
| 470 |
-
<details style="border: 1px solid #e5e7eb; border-radius: 6px; padding: 12px; margin-bottom: 8px;">
|
| 471 |
-
<summary style="font-weight: 600; cursor: pointer; color: #1f2937;">
|
| 472 |
-
📅 {meeting['date']} - Rate: {meeting['rate_decision']}
|
| 473 |
-
</summary>
|
| 474 |
-
<div style="margin-top: 12px; padding-top: 12px; border-top: 1px solid #e5e7eb;">
|
| 475 |
-
<p><strong>Meeting:</strong> {meeting['title']}</p>
|
| 476 |
-
<p><strong>Decision:</strong> {meeting['rate_decision']}</p>
|
| 477 |
-
<p><strong>Summary:</strong> {meeting['summary']}</p>
|
| 478 |
-
</div>
|
| 479 |
-
</details>
|
| 480 |
-
"""
|
| 481 |
-
html_content += '</div>'
|
| 482 |
else:
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
return html_content
|
| 486 |
|
| 487 |
# Wire up search functionality
|
| 488 |
date_search.change(
|
|
@@ -491,23 +421,7 @@ with gr.Blocks(css=custom_css, title="Fed AI Savant", theme=gr.themes.Soft()) as
|
|
| 491 |
outputs=meetings_accordion
|
| 492 |
)
|
| 493 |
|
| 494 |
-
#
|
| 495 |
-
voice_btn.click(
|
| 496 |
-
toggle_audio_input,
|
| 497 |
-
outputs=audio_input
|
| 498 |
-
)
|
| 499 |
-
|
| 500 |
-
audio_input.change(
|
| 501 |
-
handle_audio_input,
|
| 502 |
-
inputs=audio_input,
|
| 503 |
-
outputs=[msg, audio_input]
|
| 504 |
-
)
|
| 505 |
-
|
| 506 |
-
# Wire up example question buttons
|
| 507 |
-
example1.click(lambda: "What was the rate decision in the last FOMC meeting?", outputs=msg)
|
| 508 |
-
example2.click(lambda: "Compare June 2024 vs July 2024 FOMC meetings", outputs=msg)
|
| 509 |
-
example3.click(lambda: "Tell me about inflation expectations", outputs=msg)
|
| 510 |
-
example4.click(lambda: "What factors influenced recent policy decisions?", outputs=msg)
|
| 511 |
|
| 512 |
if __name__ == "__main__":
|
| 513 |
demo.launch()
|
|
|
|
| 10 |
load_dotenv()
|
| 11 |
_FILE_PATH = Path(__file__).parents[1]
|
| 12 |
|
| 13 |
+
# Load processed FOMC meetings data
|
| 14 |
+
def load_processed_meetings():
|
| 15 |
+
"""Load processed FOMC meetings from JSON file"""
|
| 16 |
+
try:
|
| 17 |
+
processed_file = _FILE_PATH / "data" / "fed_processed_meetings.json"
|
| 18 |
+
with open(processed_file, 'r', encoding='utf-8') as f:
|
| 19 |
+
data = json.load(f)
|
| 20 |
+
|
| 21 |
+
# Transform to match expected format for the frontend
|
| 22 |
+
meetings = []
|
| 23 |
+
for meeting in data:
|
| 24 |
+
meetings.append({
|
| 25 |
+
"date": meeting.get("date", ""),
|
| 26 |
+
"title": meeting.get("title", ""),
|
| 27 |
+
"rate_decision": meeting.get("rate", ""),
|
| 28 |
+
"summary": meeting.get("forward_guidance", ""), # Show full text
|
| 29 |
+
"action": meeting.get("action", ""),
|
| 30 |
+
"magnitude": meeting.get("magnitude", ""),
|
| 31 |
+
"key_economic_factors": meeting.get("key_economic_factors", []),
|
| 32 |
+
"economic_outlook": meeting.get("economic_outlook", ""),
|
| 33 |
+
"market_impact": meeting.get("market_impact", ""),
|
| 34 |
+
"full_text": meeting.get("full_text", "")[:500] + "..." if meeting.get("full_text") else "",
|
| 35 |
+
"url": meeting.get("url", "")
|
| 36 |
+
})
|
| 37 |
+
return meetings
|
| 38 |
+
except FileNotFoundError:
|
| 39 |
+
print("Fed processed meetings file not found. Using fallback data.")
|
| 40 |
+
return [
|
| 41 |
+
{
|
| 42 |
+
"date": "2025-06-18",
|
| 43 |
+
"title": "FOMC Meeting 2025-06-18",
|
| 44 |
+
"rate_decision": "4.25%-4.50%",
|
| 45 |
+
"summary": "No processed data available. Please run the data pipeline first.",
|
| 46 |
+
"action": "Unknown",
|
| 47 |
+
"magnitude": "Unknown",
|
| 48 |
+
"key_economic_factors": [],
|
| 49 |
+
"economic_outlook": "Data not available",
|
| 50 |
+
"market_impact": "Data not available",
|
| 51 |
+
"full_text": "No data available",
|
| 52 |
+
"url": ""
|
| 53 |
+
}
|
| 54 |
+
]
|
| 55 |
+
except Exception as e:
|
| 56 |
+
print(f"Error loading processed meetings: {e}")
|
| 57 |
+
return []
|
| 58 |
+
|
| 59 |
+
# Load the processed meetings
|
| 60 |
+
FOMC_MEETINGS = load_processed_meetings()
|
| 61 |
|
| 62 |
def simulate_llm_function_call(user_message: str, selected_model: str) -> Dict[str, Any]:
|
| 63 |
"""Simulate LLM function calls based on user intent"""
|
|
|
|
| 137 |
"""
|
| 138 |
return response
|
| 139 |
|
| 140 |
+
def respond_for_chat_interface(
|
| 141 |
message: str,
|
| 142 |
history: list[tuple[str, str]],
|
| 143 |
api_key: str,
|
| 144 |
):
|
| 145 |
+
"""Enhanced response function for gr.ChatInterface with Fed AI Savant capabilities"""
|
| 146 |
|
| 147 |
if not message.strip():
|
| 148 |
yield "Please enter a question about Federal Reserve policy or FOMC meetings."
|
|
|
|
| 174 |
"""Generate sidebar content with FOMC meeting details"""
|
| 175 |
sidebar_content = "## 📋 Recent FOMC Meetings\n\n"
|
| 176 |
|
| 177 |
+
for meeting in FOMC_MEETINGS:
|
| 178 |
sidebar_content += f"""
|
| 179 |
**{meeting['date']}**
|
| 180 |
*{meeting['title'][:50]}...*
|
|
|
|
| 251 |
def create_fomc_meetings_accordion():
|
| 252 |
"""Create searchable accordion for FOMC meetings"""
|
| 253 |
accordions = []
|
| 254 |
+
for meeting in FOMC_MEETINGS:
|
| 255 |
title = f"{meeting['date']} - Rate: {meeting['rate_decision']}"
|
| 256 |
content = f"""
|
| 257 |
**Meeting Title:** {meeting['title']}
|
|
|
|
| 273 |
with gr.Row():
|
| 274 |
with gr.Column():
|
| 275 |
gr.Markdown("""
|
| 276 |
+
# 🏛️ Fed AI Savant 🏛️
|
| 277 |
**Intelligent Analysis of Federal Reserve Policy and FOMC Meetings**
|
| 278 |
|
| 279 |
Ask questions about interest rate decisions, monetary policy changes, and economic analysis based on Federal Reserve meeting minutes.
|
|
|
|
| 281 |
|
| 282 |
# Row 2: API Key Configuration
|
| 283 |
with gr.Row():
|
| 284 |
+
with gr.Column(scale=1):
|
| 285 |
+
gr.Markdown("### Powered by")
|
| 286 |
+
gr.Image(
|
| 287 |
+
value=str(_FILE_PATH / "assets" / "fireworks_logo.png"),
|
| 288 |
+
height=60,
|
| 289 |
+
width=200,
|
| 290 |
+
show_label=False,
|
| 291 |
+
show_download_button=False,
|
| 292 |
+
container=False,
|
| 293 |
+
show_fullscreen_button=False,
|
| 294 |
+
show_share_button=False,
|
| 295 |
+
)
|
| 296 |
+
with gr.Column(scale=1):
|
| 297 |
+
gr.Markdown("### 🔑 Configuration")
|
| 298 |
api_key = gr.Textbox(
|
| 299 |
label="AI API Key",
|
| 300 |
type="password",
|
| 301 |
+
placeholder="Please enter your FireworksAI API key",
|
| 302 |
+
value=os.getenv("FIREWORKS_API_KEY", ""),
|
|
|
|
| 303 |
)
|
| 304 |
+
with gr.Column(scale=2):
|
| 305 |
gr.Markdown("### 📋 How to Use")
|
| 306 |
gr.Markdown("""
|
| 307 |
1. **Enter your AI API key** (OpenAI, Anthropic, etc.)
|
|
|
|
| 322 |
lines=1
|
| 323 |
)
|
| 324 |
|
| 325 |
+
with gr.Accordion("FOMC Meetings", open=False):
|
| 326 |
+
# Dynamic HTML generation for meetings
|
| 327 |
+
def generate_meetings_html(meetings_list):
|
| 328 |
+
"""Generate HTML for meetings list"""
|
| 329 |
+
if not meetings_list:
|
| 330 |
+
return '<p style="color: #6b7280; text-align: center; padding: 20px;">No meetings available</p>'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 331 |
|
| 332 |
+
html_content = '<div style="space-y: 8px;">'
|
| 333 |
+
for meeting in meetings_list:
|
| 334 |
+
# Format key economic factors for display (show all factors)
|
| 335 |
+
factors_html = ""
|
| 336 |
+
if meeting.get('key_economic_factors') and len(meeting['key_economic_factors']) > 0:
|
| 337 |
+
factors_html = "<p><strong>Key Factors:</strong></p><ul>"
|
| 338 |
+
for factor in meeting['key_economic_factors']: # Show all factors
|
| 339 |
+
factors_html += f"<li>{factor}</li>"
|
| 340 |
+
factors_html += "</ul>"
|
| 341 |
+
|
| 342 |
+
html_content += f"""
|
| 343 |
+
<details style="border: 1px solid #e5e7eb; border-radius: 6px; padding: 12px; margin-bottom: 8px;">
|
| 344 |
+
<summary style="font-weight: 600; cursor: pointer; color: #1f2937;">
|
| 345 |
+
📅 {meeting['date']} - Rate: {meeting['rate_decision']}
|
| 346 |
+
</summary>
|
| 347 |
+
<div style="margin-top: 12px; padding-top: 12px; border-top: 1px solid #e5e7eb;">
|
| 348 |
+
<p><strong>Meeting:</strong> {meeting['title']}</p>
|
| 349 |
+
<p><strong>Action:</strong> {meeting.get('action', 'N/A')}</p>
|
| 350 |
+
<p><strong>Rate:</strong> {meeting['rate_decision']}</p>
|
| 351 |
+
<p><strong>Magnitude:</strong> {meeting.get('magnitude', 'N/A')}</p>
|
| 352 |
+
<p><strong>Forward Guidance:</strong> {meeting['summary']}</p>
|
| 353 |
+
{factors_html}
|
| 354 |
+
<p><strong>Economic Outlook:</strong> {meeting.get('economic_outlook', 'N/A')}</p>
|
| 355 |
+
<p><strong>Market Impact:</strong> {meeting.get('market_impact', 'N/A')}</p>
|
| 356 |
+
{f'<p><strong>Source:</strong> <a href="{meeting["url"]}" target="_blank">Fed Minutes PDF</a></p>' if meeting.get('url') else ''}
|
| 357 |
+
</div>
|
| 358 |
+
</details>
|
| 359 |
+
"""
|
| 360 |
+
html_content += '</div>'
|
| 361 |
+
return html_content
|
| 362 |
+
|
| 363 |
+
meetings_accordion = gr.HTML(generate_meetings_html(FOMC_MEETINGS))
|
| 364 |
|
| 365 |
+
# Row 4: Chat Interface using gr.ChatInterface
|
| 366 |
with gr.Row():
|
| 367 |
with gr.Column():
|
| 368 |
gr.Markdown("### 💬 Fed AI Assistant")
|
| 369 |
+
|
| 370 |
+
chat_interface = gr.ChatInterface(
|
| 371 |
+
fn=respond_for_chat_interface,
|
| 372 |
+
chatbot=gr.Chatbot(height=200, show_label=False),
|
| 373 |
+
textbox=gr.Textbox(placeholder="Ask about Fed policy, rate decisions, or FOMC meetings...", scale=10),
|
| 374 |
+
examples=[
|
| 375 |
+
"What was the rate decision in the last FOMC meeting?"
|
| 376 |
+
"Compare June 2024 vs July 2024 FOMC meetings",
|
| 377 |
+
"Tell me about inflation expectations",
|
| 378 |
+
"Has the Fed's employment stance changed?",
|
| 379 |
+
"What was the rate decision in the last FOMC meeting?",
|
| 380 |
+
],
|
| 381 |
+
submit_btn="Send",
|
|
|
|
|
|
|
|
|
|
| 382 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 383 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 384 |
|
| 385 |
# Search functionality for FOMC meetings
|
| 386 |
def search_meetings(search_term):
|
| 387 |
"""Filter FOMC meetings based on search term"""
|
| 388 |
if not search_term.strip():
|
| 389 |
# Return all meetings if no search term
|
| 390 |
+
return generate_meetings_html(FOMC_MEETINGS)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 391 |
else:
|
| 392 |
# Filter meetings based on search term
|
| 393 |
filtered_meetings = []
|
| 394 |
search_lower = search_term.lower()
|
| 395 |
|
| 396 |
+
for meeting in FOMC_MEETINGS:
|
| 397 |
+
# Search in date, title, summary, economic factors, etc.
|
| 398 |
+
search_fields = [
|
| 399 |
+
meeting.get('date', ''),
|
| 400 |
+
meeting.get('title', ''),
|
| 401 |
+
meeting.get('summary', ''),
|
| 402 |
+
meeting.get('rate_decision', ''),
|
| 403 |
+
meeting.get('action', ''),
|
| 404 |
+
meeting.get('economic_outlook', ''),
|
| 405 |
+
meeting.get('market_impact', ''),
|
| 406 |
+
' '.join(meeting.get('key_economic_factors', []))
|
| 407 |
+
]
|
| 408 |
+
|
| 409 |
+
if any(search_lower in field.lower() for field in search_fields):
|
| 410 |
filtered_meetings.append(meeting)
|
| 411 |
|
| 412 |
if filtered_meetings:
|
| 413 |
+
return generate_meetings_html(filtered_meetings)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 414 |
else:
|
| 415 |
+
return f'<p style="color: #6b7280; text-align: center; padding: 20px;">No meetings found matching "{search_term}"</p>'
|
|
|
|
|
|
|
| 416 |
|
| 417 |
# Wire up search functionality
|
| 418 |
date_search.change(
|
|
|
|
| 421 |
outputs=meetings_accordion
|
| 422 |
)
|
| 423 |
|
| 424 |
+
# Example buttons are now handled by ChatInterface examples parameter
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 425 |
|
| 426 |
if __name__ == "__main__":
|
| 427 |
demo.launch()
|
src/modules/data_pipeline.py
CHANGED
|
@@ -16,11 +16,13 @@ from dotenv import load_dotenv
|
|
| 16 |
from pydantic import BaseModel
|
| 17 |
import pdfplumber
|
| 18 |
import tempfile
|
|
|
|
| 19 |
|
| 20 |
from src.modules.llm_completions import get_llm, run_multi_llm_completions
|
| 21 |
from src.modules.constants import PROMPT_LIBRARY
|
| 22 |
|
| 23 |
DATA_DIR = Path(__file__).parents[2] / "data"
|
|
|
|
| 24 |
|
| 25 |
class RateDecision(BaseModel):
|
| 26 |
"""Enhanced Pydantic model for comprehensive Fed decision analysis"""
|
|
@@ -41,8 +43,14 @@ class Meeting:
|
|
| 41 |
self.title = title
|
| 42 |
self.full_text = full_text
|
| 43 |
self.url = url
|
| 44 |
-
self.
|
| 45 |
self.summary = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
def to_dict(self) -> Dict:
|
| 48 |
return {
|
|
@@ -50,8 +58,13 @@ class Meeting:
|
|
| 50 |
"title": self.title,
|
| 51 |
"full_text": self.full_text,
|
| 52 |
"url": self.url,
|
| 53 |
-
"
|
| 54 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
}
|
| 56 |
|
| 57 |
@classmethod
|
|
@@ -59,6 +72,13 @@ class Meeting:
|
|
| 59 |
meeting = cls(data["date"], data["title"], data["full_text"], data.get("url", ""))
|
| 60 |
meeting.rate_decision = data.get("rate_decision")
|
| 61 |
meeting.summary = data.get("summary")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
return meeting
|
| 63 |
|
| 64 |
|
|
@@ -114,8 +134,9 @@ class FedScraper:
|
|
| 114 |
response.raise_for_status()
|
| 115 |
return BeautifulSoup(response.content, 'html.parser')
|
| 116 |
|
| 117 |
-
async def scrape_meetings(
|
| 118 |
-
|
|
|
|
| 119 |
"""Scrape multiple meetings"""
|
| 120 |
print("Fetching FOMC calendar page...")
|
| 121 |
soup = self.get_calendar_page()
|
|
@@ -123,7 +144,7 @@ class FedScraper:
|
|
| 123 |
print(f"Extracting meeting links for years {year_range[0]}-{year_range[1]}...")
|
| 124 |
meeting_links = self.extract_meeting_links(soup, year_range)
|
| 125 |
|
| 126 |
-
|
| 127 |
(date, f"FOMC Meeting {date}", link)
|
| 128 |
for date, _, link in meeting_links if link.lower().endswith('.pdf')
|
| 129 |
]
|
|
@@ -141,8 +162,8 @@ class FedScraper:
|
|
| 141 |
|
| 142 |
meetings = []
|
| 143 |
|
| 144 |
-
async with self:
|
| 145 |
-
for i, (date, title, url) in enumerate(
|
| 146 |
try:
|
| 147 |
print(f"\n[{i}/{len(meeting_links)}] Scraping: {date}")
|
| 148 |
print(f" URL: {url}")
|
|
@@ -157,8 +178,8 @@ class FedScraper:
|
|
| 157 |
|
| 158 |
# Rate limiting - be respectful to Fed servers
|
| 159 |
if i < len(meeting_links):
|
| 160 |
-
print(" Waiting
|
| 161 |
-
await asyncio.sleep(
|
| 162 |
|
| 163 |
except Exception as e:
|
| 164 |
print(f" Error scraping meeting {date}: {e}")
|
|
@@ -328,8 +349,8 @@ class DataProcessor:
|
|
| 328 |
self.llm = get_llm(model, api_key)
|
| 329 |
|
| 330 |
|
| 331 |
-
async def process_meetings(self, meetings: List[Meeting]) -> List[
|
| 332 |
-
"""Process all meetings with LLM analysis"""
|
| 333 |
print(f"Processing {len(meetings)} meetings with LLM analysis...")
|
| 334 |
|
| 335 |
prompts = [
|
|
@@ -347,7 +368,25 @@ class DataProcessor:
|
|
| 347 |
output_class=RateDecision
|
| 348 |
)
|
| 349 |
|
| 350 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 351 |
|
| 352 |
|
| 353 |
class FedDataPipeline:
|
|
@@ -400,16 +439,8 @@ class FedDataPipeline:
|
|
| 400 |
|
| 401 |
print(f"\nProcessing {len(meetings)} meetings with LLM analysis...")
|
| 402 |
processed_results = await self.processor.process_meetings(meetings)
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
if len(processed_results) == len(meetings):
|
| 406 |
-
for i, result in enumerate(processed_results):
|
| 407 |
-
meetings[i].rate_decision = result.dict() if hasattr(result, 'dict') else result
|
| 408 |
-
|
| 409 |
-
# Save final processed data
|
| 410 |
-
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 411 |
-
processed_filename = f"fed_meetings_processed_{timestamp}.json"
|
| 412 |
-
output_file = self.save_meetings(meetings, processed_filename)
|
| 413 |
|
| 414 |
print("\nProcessing completed successfully!")
|
| 415 |
print(f"Processed data: {output_file}")
|
|
@@ -438,16 +469,11 @@ class FedDataPipeline:
|
|
| 438 |
# Step 2: Process with LLM analysis
|
| 439 |
print("\n2. Processing meetings with LLM analysis...")
|
| 440 |
processed_results = await self.processor.process_meetings(meetings)
|
| 441 |
-
|
| 442 |
-
# Update meetings with processed results
|
| 443 |
-
if len(processed_results) == len(meetings):
|
| 444 |
-
for i, result in enumerate(processed_results):
|
| 445 |
-
meetings[i].rate_decision = result.dict() if hasattr(result, 'dict') else result
|
| 446 |
|
| 447 |
# Step 3: Save final processed data
|
| 448 |
print("\n3. Saving final processed data...")
|
| 449 |
-
|
| 450 |
-
output_file = self.save_meetings(meetings, processed_filename)
|
| 451 |
|
| 452 |
print("\nPipeline completed successfully!")
|
| 453 |
print(f"Scraped data: {scraped_filepath}")
|
|
@@ -457,16 +483,13 @@ class FedDataPipeline:
|
|
| 457 |
|
| 458 |
async def main():
|
| 459 |
"""Main function for running the pipeline as a script"""
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
# Load environment variables
|
| 463 |
load_dotenv()
|
| 464 |
|
| 465 |
parser = argparse.ArgumentParser(description="Fed AI Savant Data Pipeline")
|
| 466 |
-
parser.add_argument("--max-meetings", type=int, default=
|
| 467 |
parser.add_argument("--start-year", type=int, default=2022, help="Start year for meeting range")
|
| 468 |
parser.add_argument("--end-year", type=int, default=2025, help="End year for meeting range")
|
| 469 |
-
parser.add_argument("--data-dir", default="data", help="Directory to save data files")
|
| 470 |
parser.add_argument("--from-scraped", type=str, help="Process from already scraped data file (skips scraping)")
|
| 471 |
|
| 472 |
args = parser.parse_args()
|
|
@@ -482,7 +505,6 @@ async def main():
|
|
| 482 |
pipeline = FedDataPipeline(
|
| 483 |
api_key=api_key,
|
| 484 |
model="small",
|
| 485 |
-
data_dir=args.data_dir
|
| 486 |
)
|
| 487 |
|
| 488 |
# Check if processing from already scraped data
|
|
|
|
| 16 |
from pydantic import BaseModel
|
| 17 |
import pdfplumber
|
| 18 |
import tempfile
|
| 19 |
+
import argparse
|
| 20 |
|
| 21 |
from src.modules.llm_completions import get_llm, run_multi_llm_completions
|
| 22 |
from src.modules.constants import PROMPT_LIBRARY
|
| 23 |
|
| 24 |
DATA_DIR = Path(__file__).parents[2] / "data"
|
| 25 |
+
PROCESSED_MEETINGS = "fed_processed_meetings.json"
|
| 26 |
|
| 27 |
class RateDecision(BaseModel):
|
| 28 |
"""Enhanced Pydantic model for comprehensive Fed decision analysis"""
|
|
|
|
| 43 |
self.title = title
|
| 44 |
self.full_text = full_text
|
| 45 |
self.url = url
|
| 46 |
+
self.action = None
|
| 47 |
self.summary = None
|
| 48 |
+
self.rate = None
|
| 49 |
+
self.magnitude = None
|
| 50 |
+
self.forward_guidance = None
|
| 51 |
+
self.key_economic_factors = None
|
| 52 |
+
self.economic_outlook = None
|
| 53 |
+
self.market_impact = None
|
| 54 |
|
| 55 |
def to_dict(self) -> Dict:
|
| 56 |
return {
|
|
|
|
| 58 |
"title": self.title,
|
| 59 |
"full_text": self.full_text,
|
| 60 |
"url": self.url,
|
| 61 |
+
"action": self.action,
|
| 62 |
+
"rate": self.rate,
|
| 63 |
+
"magnitude": self.magnitude,
|
| 64 |
+
"forward_guidance": self.forward_guidance,
|
| 65 |
+
"key_economic_factors": self.key_economic_factors,
|
| 66 |
+
"economic_outlook": self.economic_outlook,
|
| 67 |
+
"market_impact": self.market_impact
|
| 68 |
}
|
| 69 |
|
| 70 |
@classmethod
|
|
|
|
| 72 |
meeting = cls(data["date"], data["title"], data["full_text"], data.get("url", ""))
|
| 73 |
meeting.rate_decision = data.get("rate_decision")
|
| 74 |
meeting.summary = data.get("summary")
|
| 75 |
+
meeting.action = data.get("action")
|
| 76 |
+
meeting.rate = data.get("rate")
|
| 77 |
+
meeting.magnitude = data.get("magnitude")
|
| 78 |
+
meeting.forward_guidance = data.get("forward_guidance")
|
| 79 |
+
meeting.key_economic_factors = data.get("key_economic_factors")
|
| 80 |
+
meeting.economic_outlook = data.get("economic_outlook")
|
| 81 |
+
meeting.market_impact = data.get("market_impact")
|
| 82 |
return meeting
|
| 83 |
|
| 84 |
|
|
|
|
| 134 |
response.raise_for_status()
|
| 135 |
return BeautifulSoup(response.content, 'html.parser')
|
| 136 |
|
| 137 |
+
async def scrape_meetings(
|
| 138 |
+
self, max_meetings: int = 20, year_range: Tuple[int, int] = (2022, 2024)
|
| 139 |
+
) -> List[Meeting]:
|
| 140 |
"""Scrape multiple meetings"""
|
| 141 |
print("Fetching FOMC calendar page...")
|
| 142 |
soup = self.get_calendar_page()
|
|
|
|
| 144 |
print(f"Extracting meeting links for years {year_range[0]}-{year_range[1]}...")
|
| 145 |
meeting_links = self.extract_meeting_links(soup, year_range)
|
| 146 |
|
| 147 |
+
meeting_links = [
|
| 148 |
(date, f"FOMC Meeting {date}", link)
|
| 149 |
for date, _, link in meeting_links if link.lower().endswith('.pdf')
|
| 150 |
]
|
|
|
|
| 162 |
|
| 163 |
meetings = []
|
| 164 |
|
| 165 |
+
async with self:
|
| 166 |
+
for i, (date, title, url) in enumerate(meeting_links, 1):
|
| 167 |
try:
|
| 168 |
print(f"\n[{i}/{len(meeting_links)}] Scraping: {date}")
|
| 169 |
print(f" URL: {url}")
|
|
|
|
| 178 |
|
| 179 |
# Rate limiting - be respectful to Fed servers
|
| 180 |
if i < len(meeting_links):
|
| 181 |
+
print(" Waiting 1 seconds before next request...")
|
| 182 |
+
await asyncio.sleep(1)
|
| 183 |
|
| 184 |
except Exception as e:
|
| 185 |
print(f" Error scraping meeting {date}: {e}")
|
|
|
|
| 349 |
self.llm = get_llm(model, api_key)
|
| 350 |
|
| 351 |
|
| 352 |
+
async def process_meetings(self, meetings: List[Meeting]) -> List[Meeting]:
|
| 353 |
+
"""Process all meetings with LLM analysis and update meeting objects"""
|
| 354 |
print(f"Processing {len(meetings)} meetings with LLM analysis...")
|
| 355 |
|
| 356 |
prompts = [
|
|
|
|
| 368 |
output_class=RateDecision
|
| 369 |
)
|
| 370 |
|
| 371 |
+
final_results = [
|
| 372 |
+
RateDecision.model_validate_json(
|
| 373 |
+
response.choices[0].message.content
|
| 374 |
+
)
|
| 375 |
+
for response in meetings_extracted
|
| 376 |
+
]
|
| 377 |
+
|
| 378 |
+
# Update meetings with processed results
|
| 379 |
+
if len(final_results) == len(meetings):
|
| 380 |
+
for i, result in enumerate(final_results):
|
| 381 |
+
meetings[i].action = result.action
|
| 382 |
+
meetings[i].rate = result.rate
|
| 383 |
+
meetings[i].magnitude = result.magnitude
|
| 384 |
+
meetings[i].forward_guidance = result.forward_guidance
|
| 385 |
+
meetings[i].key_economic_factors = result.key_economic_factors
|
| 386 |
+
meetings[i].economic_outlook = result.economic_outlook
|
| 387 |
+
meetings[i].market_impact = result.market_impact
|
| 388 |
+
|
| 389 |
+
return meetings
|
| 390 |
|
| 391 |
|
| 392 |
class FedDataPipeline:
|
|
|
|
| 439 |
|
| 440 |
print(f"\nProcessing {len(meetings)} meetings with LLM analysis...")
|
| 441 |
processed_results = await self.processor.process_meetings(meetings)
|
| 442 |
+
|
| 443 |
+
output_file = self.save_meetings(processed_results, PROCESSED_MEETINGS)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 444 |
|
| 445 |
print("\nProcessing completed successfully!")
|
| 446 |
print(f"Processed data: {output_file}")
|
|
|
|
| 469 |
# Step 2: Process with LLM analysis
|
| 470 |
print("\n2. Processing meetings with LLM analysis...")
|
| 471 |
processed_results = await self.processor.process_meetings(meetings)
|
| 472 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
| 473 |
|
| 474 |
# Step 3: Save final processed data
|
| 475 |
print("\n3. Saving final processed data...")
|
| 476 |
+
output_file = self.save_meetings(processed_results, PROCESSED_MEETINGS)
|
|
|
|
| 477 |
|
| 478 |
print("\nPipeline completed successfully!")
|
| 479 |
print(f"Scraped data: {scraped_filepath}")
|
|
|
|
| 483 |
|
| 484 |
async def main():
|
| 485 |
"""Main function for running the pipeline as a script"""
|
| 486 |
+
|
|
|
|
|
|
|
| 487 |
load_dotenv()
|
| 488 |
|
| 489 |
parser = argparse.ArgumentParser(description="Fed AI Savant Data Pipeline")
|
| 490 |
+
parser.add_argument("--max-meetings", type=int, default=25, help="Maximum number of meetings to scrape")
|
| 491 |
parser.add_argument("--start-year", type=int, default=2022, help="Start year for meeting range")
|
| 492 |
parser.add_argument("--end-year", type=int, default=2025, help="End year for meeting range")
|
|
|
|
| 493 |
parser.add_argument("--from-scraped", type=str, help="Process from already scraped data file (skips scraping)")
|
| 494 |
|
| 495 |
args = parser.parse_args()
|
|
|
|
| 505 |
pipeline = FedDataPipeline(
|
| 506 |
api_key=api_key,
|
| 507 |
model="small",
|
|
|
|
| 508 |
)
|
| 509 |
|
| 510 |
# Check if processing from already scraped data
|
src/modules/llm_completions.py
CHANGED
|
@@ -3,18 +3,18 @@ from pydantic import BaseModel
|
|
| 3 |
import asyncio
|
| 4 |
|
| 5 |
MODELS = {
|
| 6 |
-
"small": "accounts/fireworks/models/
|
| 7 |
-
"large": "accounts/fireworks/models/
|
| 8 |
}
|
| 9 |
|
| 10 |
-
semaphore = asyncio.Semaphore(
|
| 11 |
|
| 12 |
def get_llm(model: str, api_key: str) -> LLM:
|
| 13 |
return LLM(model=MODELS[model], api_key=api_key, deployment_type="serverless")
|
| 14 |
|
| 15 |
|
| 16 |
async def get_llm_completion(llm: LLM, prompt_text: str, output_class: BaseModel = None) -> str:
|
| 17 |
-
if
|
| 18 |
return llm.chat.completions.create(
|
| 19 |
messages=[
|
| 20 |
{
|
|
@@ -23,7 +23,10 @@ async def get_llm_completion(llm: LLM, prompt_text: str, output_class: BaseModel
|
|
| 23 |
},
|
| 24 |
],
|
| 25 |
temperature=0.1,
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
| 27 |
)
|
| 28 |
return llm.chat.completions.create(
|
| 29 |
messages=[
|
|
@@ -45,14 +48,16 @@ async def run_multi_llm_completions(llm: LLM, prompts: list[str], output_class:
|
|
| 45 |
:param output_class:
|
| 46 |
:return:
|
| 47 |
"""
|
| 48 |
-
with semaphore:
|
| 49 |
-
if
|
|
|
|
| 50 |
tasks = [
|
| 51 |
asyncio.create_task(
|
| 52 |
get_llm_completion(llm=llm, prompt_text=prompt, output_class=output_class)
|
| 53 |
) for prompt in prompts
|
| 54 |
]
|
| 55 |
else:
|
|
|
|
| 56 |
tasks = [
|
| 57 |
asyncio.create_task(
|
| 58 |
get_llm_completion(llm=llm, prompt_text=prompt)
|
|
|
|
| 3 |
import asyncio
|
| 4 |
|
| 5 |
MODELS = {
|
| 6 |
+
"small": "accounts/fireworks/models/qwen3-235b-a22b-instruct-2507",
|
| 7 |
+
"large": "accounts/fireworks/models/kimi-k2-instruct"
|
| 8 |
}
|
| 9 |
|
| 10 |
+
semaphore = asyncio.Semaphore(10)
|
| 11 |
|
| 12 |
def get_llm(model: str, api_key: str) -> LLM:
|
| 13 |
return LLM(model=MODELS[model], api_key=api_key, deployment_type="serverless")
|
| 14 |
|
| 15 |
|
| 16 |
async def get_llm_completion(llm: LLM, prompt_text: str, output_class: BaseModel = None) -> str:
|
| 17 |
+
if output_class:
|
| 18 |
return llm.chat.completions.create(
|
| 19 |
messages=[
|
| 20 |
{
|
|
|
|
| 23 |
},
|
| 24 |
],
|
| 25 |
temperature=0.1,
|
| 26 |
+
response_format={
|
| 27 |
+
"type": "json_object",
|
| 28 |
+
"schema": output_class.model_json_schema(),
|
| 29 |
+
},
|
| 30 |
)
|
| 31 |
return llm.chat.completions.create(
|
| 32 |
messages=[
|
|
|
|
| 48 |
:param output_class:
|
| 49 |
:return:
|
| 50 |
"""
|
| 51 |
+
async with semaphore:
|
| 52 |
+
if output_class:
|
| 53 |
+
print(f"Running LLM with structured outputs")
|
| 54 |
tasks = [
|
| 55 |
asyncio.create_task(
|
| 56 |
get_llm_completion(llm=llm, prompt_text=prompt, output_class=output_class)
|
| 57 |
) for prompt in prompts
|
| 58 |
]
|
| 59 |
else:
|
| 60 |
+
print(f"Running LLM with non-structured outputs")
|
| 61 |
tasks = [
|
| 62 |
asyncio.create_task(
|
| 63 |
get_llm_completion(llm=llm, prompt_text=prompt)
|