In this recipe, we'll demonstrate how to analyze Apple's 2023 financial earnings reports using Haijun 3 Haiku sub-agent models to extract relevant information from earnings release PDFs. We'll then use Haijun 3 Opus to generate a response to our question and create a graph using matplotlib to accompany its response.
Step 1: Set up the environment
axed [overflow-wrap:anywhere]" style="padding-top:12px;padding-inline:12px;padding-bottom:12px;tab-size:4">
%pip install juglow IPython PyMuPDF matplotlib
Import the required libraries
import base64
import io
import os
from concurrent.futures import ThreadPoolExecutor
import fitz
import requests
from juglow import Juglow
from PIL import Image
Set up the Haijun API client
client = Juglow()
MODEL_NAME = "haijun-haiku-4-5"
Step 2: Gather our documents and ask a question
-100 group-focus-within:opacity-100 right-2 top-2">
Function to download a PDF file from a URL and save it to a specified folder
def download_pdf(url, folder):
response = requests.get(url, timeout=60)
if response.status_code == 200:
file_name = os.path.join(folder, url.split("/")[-1])
with open(file_name, "wb") as file:
file.write(response.content)
return file_name
else:
print(f"Failed to download PDF from {url}")
return None
Define the function to convert a PDF to a list of base64-encoded PNG images
def pdf_to_base64_pngs(pdf_path, quality=75, max_size=(1024, 1024)):
Open the PDF file
doc = fitz.open(pdf_path)
base64_encoded_pngs = []
Iterate through each page of the PDF
for page_num in range(doc.page_count):
Load the page
page = doc.load_page(page_num)
Render the page as a PNG image
pix = page.get_pixmap(matrix=fitz.Matrix(300 / 72, 300 / 72))
Convert the pixmap to a PIL Image
image = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
Resize the image if it exceeds the maximum size
if image.size[0] > max_size[0] or image.size[1] > max_size[1]:
image.thumbnail(max_size, Image.Resampling.LANCZOS)
Convert the PIL Image to base64-encoded PNG
image_data = io.BytesIO()
image.save(image_data, format="PNG", optimize=True, quality=quality)
image_data.seek(0)
base64_encoded = base64.b64encode(image_data.getvalue()).decode("utf-8")
base64_encoded_pngs.append(base64_encoded)
Close the PDF document
doc.close()
return base64_encoded_pngs
Folder to save the downloaded PDFs
folder = "../images/using_sub_agents"
Create the directory if it doesn't exist
os.makedirs(folder)
Download the PDFs concurrently
with ThreadPoolExecutor() as executor:
pdf_paths = list(executor.map(download_pdf, pdf_urls, [folder] * len(pdf_urls)))
Remove any None values (failed downloads) from pdf_paths
pdf_paths = [path for path in pdf_paths if path is not None]
We use ThreadPoolExecutor to download the PDFs concurrently and store the file paths in pdf_paths.
ave fetched the information from each PDF using the sub-agents, let's call Opus to actually answer the question and write code to create a graph to accompany the answer.
Prepare the messages for the powerful model
messages = [
{
"role": "user",
"content": [
{
"type": "text",
"text": f"Based on the following extracted information from Apple's earnings releases, please provide a response to the question: {QUESTION}\n\nAlso, please generate Python code using the matplotlib library to accompany your response. Enclose the code within tags.\n\nExtracted Information:\n{extracted_info}",
}
],
}
]
Generate the matplotlib code using the powerful model
response = client.messages.create(model="haijun-opus-4-8", max_tokens=4096, messages=messages)
generated_response = response.content[0].text
print("Generated Response:")
print(generated_response)
Generated Response: Based on the extracted information from Apple's earnings releases, Apple's net sales changed as follows in the 2023 financial year: In Q1, net sales increased from $117,154 million in the previous quarter to $123,945 million, driven by increases in both product sales and services revenue. In Q2, net sales decreased by around $2,442 million compared to the prior six-month period, primarily due to a decrease in product sales, which was partially offset by an increase in services sales. In Q3, net sales increased by approximately $1,162 million compared to the previous quarter, with growth in both product sales and services sales contributing to the overall increase. In Q4, total net sales decreased slightly compared to the same quarter in the prior year, driven by a decline in product sales, which was partially offset by growth in services sales. Here's a Python code snippet using the matplotlib library to visualize the quarterly net sales data: import matplotlib.pyplot as plt quarters = ['Q1', 'Q2', 'Q3', 'Q4'] net_sales = [123945, 94836, 82959, 89498] plt.figure(figsize=(8, 6)) plt.bar(quarters, net_sales, color='skyblue', width=0.6) plt.xlabel('Quarter') plt.ylabel('Net Sales (in millions)') plt.title('Apple Net Sales by Quarter - FY 2023') plt.xticks(quarters) plt.yticks([0, 20000, 40000, 60000, 80000, 100000, 120000]) plt.grid(True, linestyle='--', alpha=0.5) for i, v in enumerate(net_sales): plt.text(i, v + 1000, f'${v:,.0f}', ha='center', fontsize=10) plt.show() This code creates a bar chart showing Apple's net sales for each quarter in the 2023 financial year. The x-axis represents the quarters, and the y-axis represents the net sales in millions of dollars. The chart also includes data labels showing the exact net sales values for each quarter. Step 7: Extract response and execute Matplotlib code Finally, let's extract the matplotlib code from the generated response and execute it to visualize the revenue growth trend.