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
- Send the request. One
POST /sessionsstarts the turn. - Wait for the turn. It runs in the background, typically for about 25 minutes. Check the session until it ends.
- Read the summary. The answer describes the deck.
- Find the deck. It is the session's slide artifact.
- Download it and open it in PowerPoint, Keynote, or Google Slides.
Prerequisites
| Requirement | Where to set up |
|---|---|
| Credentials | Client ID, client secret, and refresh token. See Authentication. |
| Runtime | Python 3.9+ with requests, or Node.js 20+. |
| AI credits | Each 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.
- Python
- JavaScript
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()
const API_URL = 'https://api.research.alpha-sense.com/superanalyst/v1/superanalysts/default'
class TokenProvider {
#refreshToken = process.env.ALPHASENSE_REFRESH_TOKEN
#accessToken = null
#expiresAt = 0
#renewal = null
async headers() {
if (Date.now() > this.#expiresAt - 60_000) {
this.#renewal ??= this.#renew().finally(() => (this.#renewal = null))
await this.#renewal
}
return {Authorization: `Bearer ${this.#accessToken}`}
}
async #renew() {
const response = await fetch('https://auth.research.alpha-sense.com/oauth/token', {
method: 'POST',
body: new URLSearchParams({
grant_type: 'refresh_token',
client_id: process.env.ALPHASENSE_CLIENT_ID,
client_secret: process.env.ALPHASENSE_CLIENT_SECRET,
refresh_token: this.#refreshToken,
}),
})
if (!response.ok) throw new Error(`Token request failed: ${response.status}`)
const token = await response.json()
this.#accessToken = token.access_token
this.#expiresAt = Date.now() + token.expires_in * 1000
// Also store a rotated refresh token in your secret store.
this.#refreshToken = token.refresh_token ?? this.#refreshToken
}
}
const tokens = new TokenProvider()
async function call(method, path, body) {
const response = await fetch(`${API_URL}${path}`, {
method,
headers: {...(await tokens.headers()), 'Content-Type': 'application/json'},
body: body && JSON.stringify(body),
})
if (!response.ok) {
const error = new Error(`${response.status} ${await response.text()}`)
error.status = response.status
throw error
}
return response.json()
}
Save the samples as .mjs files, or set "type": "module", to use top-level await.
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).
- Python
- JavaScript
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']}")
const 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.'
const session = await call('POST', '/sessions', {input: {text: PROMPT}})
const sessionPath = `/sessions/${encodeURIComponent(session.id)}`
console.log(`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).
- Python
- JavaScript
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']}")
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
const RETRYABLE = [429, 502, 503, 504]
async function waitForTurn(sessionPath, timeout = 60 * 60_000) {
const deadline = Date.now() + timeout
while (Date.now() < deadline) {
await sleep(30_000)
let current
try {
current = await call('GET', sessionPath)
} catch (error) {
// Checking is safe to repeat. A network failure is a TypeError with no status.
if (error instanceof TypeError || RETRYABLE.includes(error.status)) continue
throw error
}
if (!['queued', 'in_progress'].includes(current.status)) return current
}
throw new Error('The deck is still being built. Check the session again later.')
}
const finished = await waitForTurn(sessionPath)
if (finished.status !== 'completed') {
throw new Error(`The turn ended as ${finished.status}: ${finished.error?.message}`)
}
console.log(`Finished: ${finished.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.
- Python
- JavaScript
answer = call("GET", f"{session_path}/messages", params={"limit": 1})["data"][0]
print(answer["content"][0]["text"])
const [answer] = (await call('GET', `${sessionPath}/messages?limit=1`)).data
console.log(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.
- Python
- JavaScript
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']}")
const PPTX = 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
const {data: artifacts} = await call('GET', `${sessionPath}/artifacts?limit=100`)
let decks = artifacts.filter(a => a.mime_type === PPTX)
if (decks.length === 0) throw new Error('This session has no slide deck.')
if (decks.length > 1) {
decks = await Promise.all(decks.map(a => call('GET', `/artifacts/${encodeURIComponent(a.id)}`)))
}
const deck = decks.reduce((a, b) => ((a.updated_at ?? '') >= (b.updated_at ?? '') ? a : b))
console.log(`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.
- Python
- JavaScript
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)")
import {writeFile} from 'node:fs/promises'
import path from 'node:path'
const content = await call('GET', `/artifacts/${encodeURIComponent(deck.id)}/content`)
if (content.delivery !== 'inline') {
throw new Error(`${deck.name} can't be downloaded: ${content.error.code}`)
}
const name = path.basename(deck.name)
const data = Buffer.from(content.content_base64, 'base64')
await writeFile(name, data)
console.log(`Saved ${name} (${data.length.toLocaleString()} bytes)`)
Open the deck in PowerPoint, Keynote, or Google Slides.
Complete script
Python: request, wait, and download the deck in one file
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
- Sessions: statuses, cancelling a turn, and follow-ups.
- Streaming: show progress while the deck builds.
- Artifacts and Files: list and download every file a session produces.
- Errors and Limits: what to retry, and the download size limit.