Quick Start
This guide takes you from credentials to a cited answer and a follow-up question. You need the
client ID, client secret, and refresh token from Authentication,
and one of: Python 3.9+ with requests, Node.js 20+, or curl with jq.
Prefer not to write code yet? Import the Postman collection, fill in your credentials, and run Get access token, then Create a session and run its first turn.
1. Set your credentials
ALPHASENSE_CLIENT_ID=your_client_id
ALPHASENSE_CLIENT_SECRET=your_client_secret
ALPHASENSE_REFRESH_TOKEN=your_refresh_token
Keep this file out of source control. Load it with export $(grep -v '^#' .env | xargs).
2. Get an access token
- Python
- JavaScript
- cURL
import os
import requests
API_URL = "https://api.research.alpha-sense.com/superanalyst/v1/superanalysts/default"
token = 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": os.environ["ALPHASENSE_REFRESH_TOKEN"],
},
)
token.raise_for_status()
api = requests.Session()
api.headers["Authorization"] = f"Bearer {token.json()['access_token']}"
api.hooks["response"].append(lambda response, *args, **kwargs: response.raise_for_status())
api sends your token with every request and raises an error for any failed request.
const API_URL = 'https://api.research.alpha-sense.com/superanalyst/v1/superanalysts/default'
const token = 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: process.env.ALPHASENSE_REFRESH_TOKEN,
}),
})
if (!token.ok) throw new Error(`Token request failed: ${token.status}`)
const authHeader = {Authorization: `Bearer ${(await token.json()).access_token}`}
async function api(path, {method = 'GET', body} = {}) {
const response = await fetch(`${API_URL}${path}`, {
method,
headers: {...authHeader, 'Content-Type': 'application/json'},
body: body && JSON.stringify(body),
})
if (!response.ok) {
const error = new Error(`${response.status} ${await response.text()}`)
throw Object.assign(error, {
status: response.status,
retryAfter: response.headers.get('Retry-After'),
})
}
return response.json()
}
api() sends your token with every request and throws for any failed request. Save the samples as
.mjs files, or set "type": "module", to use top-level await.
API_URL="https://api.research.alpha-sense.com/superanalyst/v1/superanalysts/default"
ACCESS_TOKEN=$(curl -sS -X POST "https://auth.research.alpha-sense.com/oauth/token" \
--data-urlencode "grant_type=refresh_token" \
--data-urlencode "client_id=$ALPHASENSE_CLIENT_ID" \
--data-urlencode "client_secret=$ALPHASENSE_CLIENT_SECRET" \
--data-urlencode "refresh_token=$ALPHASENSE_REFRESH_TOKEN" \
| jq -r '.access_token // empty')
if [ -n "$ACCESS_TOKEN" ]; then
echo "Authenticated."
else
echo "Token request failed. Check your credentials before trying again."
fi
If the token response includes a new refresh_token, it replaces your old one. Save it in .env
before the next run. The complete script does this for you.
3. Ask a question
POST /sessions starts a conversation and runs its first turn. The session id identifies the
conversation. It can contain :, so URL-encode it when you put it in a path.
- Python
- JavaScript
- cURL
from urllib.parse import quote
question = {"input": {"text": "What were the key themes in NVIDIA's latest earnings call?"}}
session = api.post(f"{API_URL}/sessions", json=question).json()
session_url = f"{API_URL}/sessions/{quote(session['id'], safe='')}"
const question = {input: {text: "What were the key themes in NVIDIA's latest earnings call?"}}
const session = await api('/sessions', {method: 'POST', body: question})
const sessionPath = `/sessions/${encodeURIComponent(session.id)}`
SESSION_ID=$(curl -sS -X POST "$API_URL/sessions" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"input": {"text": "What were the key themes in NVIDIA'\''s latest earnings call?"}}' \
| jq -r '.id | @uri')
SESSION_URL="$API_URL/sessions/$SESSION_ID"
A user's first request can return 503 RUNTIME_UNAVAILABLE while their workspace is set up. Wait
the number of seconds in the Retry-After header, then send it again.
4. Get the answer
The turn runs in the background. A question usually takes a few minutes; a report, deck, or
dashboard can take 25 minutes or more. Check the session until its status is no longer queued or
in_progress, then read the newest message: that is the answer.
wait_for_answer also takes the previous answer, for follow-ups: right after you send one, the
session can still show the previous turn as completed for a moment.
- Python
- JavaScript
- cURL
import time
RETRYABLE = {429, 502, 503, 504}
# Raise timeout for long-running turns, such as reports and decks.
def wait_for_answer(session_url, previous_answer=None, timeout=960):
"""Return the answer to the latest turn. After a follow-up, pass the previous answer."""
started = time.time()
while time.time() < started + timeout:
time.sleep(5)
try:
session = api.get(session_url).json()
if session["status"] in ("queued", "in_progress"):
continue
if session["status"] != "completed":
# Right after a follow-up, the session can still show the previous turn's status.
if previous_answer and time.time() < started + 30:
continue
raise RuntimeError(f"The turn ended as {session['status']}: {session['error']}")
latest = api.get(f"{session_url}/messages", params={"limit": 1}).json()["data"][0]
except (requests.ConnectionError, requests.Timeout):
continue # Checking is safe to repeat.
except requests.HTTPError as error:
if error.response.status_code in RETRYABLE:
continue # Checking is safe to repeat.
raise
if latest["role"] == "assistant" and latest["id"] != (previous_answer or {}).get("id"):
return latest
raise TimeoutError("No answer yet. Check the session again later.")
answer = wait_for_answer(session_url)
print(answer["content"][0]["text"])
for citation in answer["citations"]:
print(f"- {citation['title']}: {citation['url']}")
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
const RETRYABLE = [429, 502, 503, 504]
// Return the answer to the latest turn. After a follow-up, pass the previous answer.
// Raise timeout for long-running turns, such as reports and decks.
async function waitForAnswer(sessionPath, previousAnswer = null, timeout = 960_000) {
const started = Date.now()
while (Date.now() < started + timeout) {
await sleep(5000)
try {
const session = await api(sessionPath)
if (['queued', 'in_progress'].includes(session.status)) continue
if (session.status !== 'completed') {
// Right after a follow-up, the session can still show the previous turn's status.
if (previousAnswer && Date.now() < started + 30_000) continue
throw new Error(`The turn ended as ${session.status}: ${session.error?.message}`)
}
const [latest] = (await api(`${sessionPath}/messages?limit=1`)).data
if (latest.role === 'assistant' && latest.id !== previousAnswer?.id) return latest
} 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
}
}
throw new Error('No answer yet. Check the session again later.')
}
const answer = await waitForAnswer(sessionPath)
console.log(answer.content[0].text)
for (const citation of answer.citations) console.log(`- ${citation.title}: ${citation.url}`)
while curl -sS "$SESSION_URL" -H "Authorization: Bearer $ACCESS_TOKEN" \
| jq -e '.status == "queued" or .status == "in_progress"' > /dev/null; do
sleep 5
done
curl -sS "$SESSION_URL/messages?limit=1" -H "Authorization: Bearer $ACCESS_TOKEN" \
| jq -r 'if .data[0].role == "assistant" then .data[0].content[0].text
else "No answer. Check the session status." end'
The answer is Markdown. Its sources are in citations, and each one's url opens it in AlphaSense.
To mark where the text cites each source, see Citations. To show the
answer while it is written, stream the turn instead of checking the
session.
5. Ask a follow-up
POST /sessions/{session_id}/messages asks the next question in the same conversation. Then wait
for an answer newer than the previous one.
- Python
- JavaScript
- cURL
followup = {"input": {"text": "Which of those themes did analysts push back on?"}}
api.post(f"{session_url}/messages", json=followup)
followup_answer = wait_for_answer(session_url, previous_answer=answer)
print(followup_answer["content"][0]["text"])
const followup = {input: {text: 'Which of those themes did analysts push back on?'}}
await api(`${sessionPath}/messages`, {method: 'POST', body: followup})
const followupAnswer = await waitForAnswer(sessionPath, answer)
console.log(followupAnswer.content[0].text)
PREVIOUS_ANSWER=$(curl -sS "$SESSION_URL/messages?limit=1" -H "Authorization: Bearer $ACCESS_TOKEN" \
| jq -r '.data[0].id')
curl -sS -X POST "$SESSION_URL/messages" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"input": {"text": "Which of those themes did analysts push back on?"}}' > /dev/null
# For the first 30 seconds, a failed status can still be the previous turn's.
SECONDS=0
until curl -sS "$SESSION_URL/messages?limit=1" -H "Authorization: Bearer $ACCESS_TOKEN" \
| jq -e --arg previous "$PREVIOUS_ANSWER" --argjson settled "$((SECONDS >= 30))" \
'(.session_status == "completed" and .data[0].role == "assistant" and .data[0].id != $previous)
or ($settled == 1 and (.session_status | IN("failed", "cancelled", "timed_out")))' > /dev/null; do
sleep 5
done
curl -sS "$SESSION_URL/messages?limit=1" -H "Authorization: Bearer $ACCESS_TOKEN" \
| jq -r 'if .session_status == "completed" then .data[0].content[0].text
else "The turn ended as \(.session_status)." end'
Send one follow-up at a time, and wait for its answer before the next. A follow-up sent while a turn
is running returns 409 SESSION_BUSY.
Complete script
Python: the full Quick Start in one file
import os
import time
from urllib.parse import quote
import requests
API_URL = "https://api.research.alpha-sense.com/superanalyst/v1/superanalysts/default"
def get_access_token():
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": os.environ["ALPHASENSE_REFRESH_TOKEN"],
},
)
response.raise_for_status()
token = response.json()
if "refresh_token" in token:
save_refresh_token(token["refresh_token"])
return token["access_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")
RETRYABLE = {429, 502, 503, 504}
# Raise timeout for long-running turns, such as reports and decks.
def wait_for_answer(api, session_url, previous_answer=None, timeout=960):
"""Return the answer to the latest turn. After a follow-up, pass the previous answer."""
started = time.time()
while time.time() < started + timeout:
time.sleep(5)
try:
session = api.get(session_url).json()
if session["status"] in ("queued", "in_progress"):
continue
if session["status"] != "completed":
# Right after a follow-up, the session can still show the previous turn's status.
if previous_answer and time.time() < started + 30:
continue
raise RuntimeError(f"The turn ended as {session['status']}: {session['error']}")
latest = api.get(f"{session_url}/messages", params={"limit": 1}).json()["data"][0]
except (requests.ConnectionError, requests.Timeout):
continue # Checking is safe to repeat.
except requests.HTTPError as error:
if error.response.status_code in RETRYABLE:
continue # Checking is safe to repeat.
raise
if latest["role"] == "assistant" and latest["id"] != (previous_answer or {}).get("id"):
return latest
raise TimeoutError("No answer yet. Check the session again later.")
def main():
api = requests.Session()
api.headers["Authorization"] = f"Bearer {get_access_token()}"
api.hooks["response"].append(lambda response, *args, **kwargs: response.raise_for_status())
question = {"input": {"text": "What were the key themes in NVIDIA's latest earnings call?"}}
session = api.post(f"{API_URL}/sessions", json=question).json()
session_url = f"{API_URL}/sessions/{quote(session['id'], safe='')}"
answer = wait_for_answer(api, session_url)
print(answer["content"][0]["text"])
for citation in answer["citations"]:
print(f"- {citation['title']}: {citation['url']}")
followup = {"input": {"text": "Which of those themes did analysts push back on?"}}
api.post(f"{session_url}/messages", json=followup)
print(wait_for_answer(api, session_url, previous_answer=answer)["content"][0]["text"])
if __name__ == "__main__":
main()
Run it with:
python3 -m venv .venv
source .venv/bin/activate
pip install requests
export $(grep -v '^#' .env | xargs)
python superanalyst_quickstart.py
Next steps
- Sessions: statuses, cancelling a turn, listing sessions, and reading the transcript.
- Streaming: show progress and the answer as the turn runs.
- Citations: show an answer's sources in its text.
- Artifacts and Files: download the files SuperAnalyst produces.
- Errors and Limits: what to retry, and how.