Skip to main content

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​

.env
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​

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.

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.

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='')}"

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.

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']}")

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.

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"])

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
superanalyst_quickstart.py
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​