Skip to main content

Mag 7 Coverage Primers

Analysts who pick up a coverage list start with a primer on each company. This use case gets SuperAnalyst to write all of them in one request: a cited slide deck of primers for the Magnificent 7. Your code sends the request, waits for the turn, and downloads the deck.

The request asks for:

  • One slide comparing Apple, Microsoft, Alphabet, Amazon, Meta, NVIDIA, and Tesla.
  • Two or three slides per company: what the business does and how it makes money, the latest quarterly results against expectations, the key bull and bear debates, and what to watch next quarter.
  • Sources cited throughout.

To cover other companies, change the list in the prompt.

How it works​

  1. Send the request. One POST /sessions starts the turn.
  2. Wait for the turn. It runs in the background, typically for about 25 minutes. Check the session until it ends.
  3. Read the summary. The answer describes the deck.
  4. Find the deck. It is the session's slide artifact.
  5. Download it and open it in PowerPoint, Keynote, or Google Slides.

Prerequisites​

RequirementWhere to set up
CredentialsClient ID, client secret, and refresh token. See Authentication.
RuntimePython 3.9+ with requests, or Node.js 20+.
AI creditsEach request uses credits. See Overview.

Shared setup​

A deck like this takes about as long as an access token lasts, and longer coverage lists take more time, so every request gets its token from a TokenProvider that renews it when needed. It is the same class as in Keep tokens fresh.

import os
import threading
import time
from urllib.parse import quote

import requests

API_URL = "https://api.research.alpha-sense.com/superanalyst/v1/superanalysts/default"


class TokenProvider:
def __init__(self):
self._refresh_token = os.environ["ALPHASENSE_REFRESH_TOKEN"]
self._access_token = None
self._expires_at = 0.0
self._lock = threading.Lock()

def headers(self):
with self._lock:
if time.time() > self._expires_at - 60:
self._renew()
return {"Authorization": f"Bearer {self._access_token}"}

def _renew(self):
response = requests.post(
"https://auth.research.alpha-sense.com/oauth/token",
data={
"grant_type": "refresh_token",
"client_id": os.environ["ALPHASENSE_CLIENT_ID"],
"client_secret": os.environ["ALPHASENSE_CLIENT_SECRET"],
"refresh_token": self._refresh_token,
},
)
response.raise_for_status()
token = response.json()
self._access_token = token["access_token"]
self._expires_at = time.time() + token["expires_in"]
# Also store a rotated refresh token in your secret store.
self._refresh_token = token.get("refresh_token", self._refresh_token)


tokens = TokenProvider()


def call(method, path, **kwargs):
response = requests.request(
method, f"{API_URL}{path}", headers=tokens.headers(), timeout=120, **kwargs
)
response.raise_for_status()
return response.json()

Step 1: Send the request​

The prompt names the coverage list, what each primer covers, and the format. Ending with a size limit keeps the deck within the API's download limit (see Timeouts and limits).

PROMPT = (
"Build a coverage deck of company primers for the Magnificent 7: Apple, Microsoft, Alphabet, "
"Amazon, Meta, NVIDIA, and Tesla. Open with one slide comparing all seven. Then give each company "
"two or three slides: what the business does and how it makes money, its latest quarterly results "
"against expectations, the key bull and bear debates, and what to watch next quarter. Cite your "
"sources. Keep the file under 2 MB."
)

session = call("POST", "/sessions", json={"input": {"text": PROMPT}})
session_path = f"/sessions/{quote(session['id'], safe='')}"
print(f"Started: {session['status']}")

Send the request once. Every create starts a new turn and uses credits. If the request fails with a timeout, find the session with List sessions instead of sending it again.

Step 2: Wait for the turn​

Check the session every 30 seconds until its status is no longer queued or in_progress. While a turn runs, a check can briefly fail with 429, 502, 503, or 504, or with a network error or timeout. Checking is safe to repeat, so keep waiting (see Retrying safely).

RETRYABLE = {429, 502, 503, 504}


def wait_for_turn(session_path, timeout=60 * 60):
deadline = time.time() + timeout
while time.time() < deadline:
time.sleep(30)
try:
session = call("GET", session_path)
except (requests.ConnectionError, requests.Timeout):
continue # Checking is safe to repeat. Try again next round.
except requests.HTTPError as error:
if error.response.status_code in RETRYABLE:
continue # Checking is safe to repeat. Try again next round.
raise
if session["status"] not in ("queued", "in_progress"):
return session
raise TimeoutError("The deck is still being built. Check the session again later.")


session = wait_for_turn(session_path)
if session["status"] != "completed":
raise RuntimeError(f"The turn ended as {session['status']}: {session['error']}")
print(f"Finished: {session['title']}")

To show progress while it runs, stream the turn instead.

Step 3: Read the summary​

The newest message is SuperAnalyst's answer. It describes the deck and its sources.

answer = call("GET", f"{session_path}/messages", params={"limit": 1})["data"][0]
print(answer["content"][0]["text"])

Step 4: Find the deck​

The deck is the session's PowerPoint artifact. A session can also hold working files, such as slide previews or a layout draft. SuperAnalyst writes the finished deck last, so if there is more than one PowerPoint file, take the most recently updated. updated_at is approximate on lists, so the sample reads each candidate's exact time from the artifact itself.

PPTX = "application/vnd.openxmlformats-officedocument.presentationml.presentation"

artifacts = call("GET", f"{session_path}/artifacts", params={"limit": 100})["data"]
decks = [a for a in artifacts if a["mime_type"] == PPTX]
if not decks:
raise RuntimeError("This session has no slide deck.")
if len(decks) > 1:
decks = [call("GET", f"/artifacts/{quote(a['id'], safe='')}") for a in decks]
deck = max(decks, key=lambda a: a["updated_at"] or "")
print(f"Found {deck['name']}")

Step 5: Download it​

A deck is binary, so it arrives base64-encoded. Check delivery first: a file over the download limit returns too_large (see Download an artifact). The sample keeps only the base name of the file, so nothing is written outside the folder.

import base64

content = call("GET", f"/artifacts/{quote(deck['id'], safe='')}/content")
if content["delivery"] != "inline":
raise RuntimeError(f"{deck['name']} can't be downloaded: {content['error']['code']}")

name = os.path.basename(deck["name"])
data = base64.b64decode(content["content_base64"])
with open(name, "wb") as f:
f.write(data)
print(f"Saved {name} ({len(data):,} bytes)")

Open the deck in PowerPoint, Keynote, or Google Slides.

Complete script​

Python: request, wait, and download the deck in one file
mag7_primers.py
import base64
import os
import threading
import time
from urllib.parse import quote

import requests

API_URL = "https://api.research.alpha-sense.com/superanalyst/v1/superanalysts/default"
PPTX = "application/vnd.openxmlformats-officedocument.presentationml.presentation"
RETRYABLE = {429, 502, 503, 504}

PROMPT = (
"Build a coverage deck of company primers for the Magnificent 7: Apple, Microsoft, Alphabet, "
"Amazon, Meta, NVIDIA, and Tesla. Open with one slide comparing all seven. Then give each company "
"two or three slides: what the business does and how it makes money, its latest quarterly results "
"against expectations, the key bull and bear debates, and what to watch next quarter. Cite your "
"sources. Keep the file under 2 MB."
)


class TokenProvider:
def __init__(self):
self._refresh_token = os.environ["ALPHASENSE_REFRESH_TOKEN"]
self._access_token = None
self._expires_at = 0.0
self._lock = threading.Lock()

def headers(self):
with self._lock:
if time.time() > self._expires_at - 60:
self._renew()
return {"Authorization": f"Bearer {self._access_token}"}

def _renew(self):
response = requests.post(
"https://auth.research.alpha-sense.com/oauth/token",
data={
"grant_type": "refresh_token",
"client_id": os.environ["ALPHASENSE_CLIENT_ID"],
"client_secret": os.environ["ALPHASENSE_CLIENT_SECRET"],
"refresh_token": self._refresh_token,
},
)
response.raise_for_status()
token = response.json()
self._access_token = token["access_token"]
self._expires_at = time.time() + token["expires_in"]
if "refresh_token" in token:
self._refresh_token = token["refresh_token"]
save_refresh_token(token["refresh_token"])


def save_refresh_token(refresh_token, env_file=".env"):
"""A new refresh token replaces the old one, so write it back to .env."""
with open(env_file) as f:
lines = f.read().splitlines()
lines = [
f"ALPHASENSE_REFRESH_TOKEN={refresh_token}"
if line.startswith("ALPHASENSE_REFRESH_TOKEN=")
else line
for line in lines
]
with open(env_file, "w") as f:
f.write("\n".join(lines) + "\n")


tokens = TokenProvider()


def call(method, path, **kwargs):
response = requests.request(
method, f"{API_URL}{path}", headers=tokens.headers(), timeout=120, **kwargs
)
response.raise_for_status()
return response.json()


def wait_for_turn(session_path, timeout=60 * 60):
deadline = time.time() + timeout
while time.time() < deadline:
time.sleep(30)
try:
session = call("GET", session_path)
except (requests.ConnectionError, requests.Timeout):
continue # Checking is safe to repeat. Try again next round.
except requests.HTTPError as error:
if error.response.status_code in RETRYABLE:
continue # Checking is safe to repeat. Try again next round.
raise
if session["status"] not in ("queued", "in_progress"):
return session
raise TimeoutError("The deck is still being built. Check the session again later.")


def main():
session = call("POST", "/sessions", json={"input": {"text": PROMPT}})
session_path = f"/sessions/{quote(session['id'], safe='')}"
print("Building the deck. This takes about 25 minutes.")

session = wait_for_turn(session_path)
if session["status"] != "completed":
raise RuntimeError(f"The turn ended as {session['status']}: {session['error']}")

answer = call("GET", f"{session_path}/messages", params={"limit": 1})["data"][0]
print(answer["content"][0]["text"])

artifacts = call("GET", f"{session_path}/artifacts", params={"limit": 100})["data"]
decks = [a for a in artifacts if a["mime_type"] == PPTX]
if not decks:
raise RuntimeError("This session has no slide deck.")
if len(decks) > 1:
decks = [call("GET", f"/artifacts/{quote(a['id'], safe='')}") for a in decks]
deck = max(decks, key=lambda a: a["updated_at"] or "")

content = call("GET", f"/artifacts/{quote(deck['id'], safe='')}/content")
if content["delivery"] != "inline":
raise RuntimeError(f"{deck['name']} can't be downloaded: {content['error']['code']}")

name = os.path.basename(deck["name"])
data = base64.b64decode(content["content_base64"])
with open(name, "wb") as f:
f.write(data)
print(f"Saved {name} ({len(data):,} bytes)")


if __name__ == "__main__":
main()

Run it with:

python3 -m venv .venv
source .venv/bin/activate
pip install requests
export $(grep -v '^#' .env | xargs)
python mag7_primers.py
Related pages