Quick Start
Auth to first GenSearch result in under 5 minutes
This guide walks you through authenticating with the AlphaSense Agent API and running your first GenSearch query. By the end you will have a working script that asks a financial question and returns a cited, markdown-formatted answer.
Prerequisite
- An AlphaSense API account with credentials (API key, client ID, client secret, email, and password)
Set up your environment variables
Create a .env file in your project root (or export the variables in your shell) with the following
template:
ALPHASENSE_API_KEY=your_api_key_here
ALPHASENSE_CLIENT_ID=your_client_id_here
ALPHASENSE_CLIENT_SECRET=your_client_secret_here
ALPHASENSE_EMAIL=your_email_here
ALPHASENSE_PASSWORD=your_password_here
Contact your account team at support@alpha-sense.com to request API access.
Authenticate
The AlphaSense API uses OAuth 2.0 password-grant authentication. Send your credentials to the
/auth endpoint and receive a Bearer token that is valid for subsequent requests.
- Python
- JavaScript
- cURL
import os
import requests
api_key = os.environ["ALPHASENSE_API_KEY"]
client_id = os.environ["ALPHASENSE_CLIENT_ID"]
client_secret = os.environ["ALPHASENSE_CLIENT_SECRET"]
email = os.environ["ALPHASENSE_EMAIL"]
password = os.environ["ALPHASENSE_PASSWORD"]
auth_response = requests.post(
"https://api.alpha-sense.com/auth",
headers={
"x-api-key": api_key,
"Content-Type": "application/x-www-form-urlencoded",
},
data={
"grant_type": "password",
"username": email,
"password": password,
"client_id": client_id,
"client_secret": client_secret,
},
)
auth_response.raise_for_status()
access_token = auth_response.json()["access_token"]
print("Authenticated successfully.")
const apiKey = process.env.ALPHASENSE_API_KEY
const clientId = process.env.ALPHASENSE_CLIENT_ID
const clientSecret = process.env.ALPHASENSE_CLIENT_SECRET
const email = process.env.ALPHASENSE_EMAIL
const password = process.env.ALPHASENSE_PASSWORD
const authResponse = await fetch('https://api.alpha-sense.com/auth', {
method: 'POST',
headers: {
'x-api-key': apiKey,
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
grant_type: 'password',
username: email,
password: password,
client_id: clientId,
client_secret: clientSecret,
}),
})
if (!authResponse.ok) {
throw new Error(`Auth failed: ${authResponse.status} ${await authResponse.text()}`)
}
const {access_token: accessToken} = await authResponse.json()
console.log('Authenticated successfully.')
ACCESS_TOKEN=$(curl -s -X POST "https://api.alpha-sense.com/auth" \
-H "x-api-key: $ALPHASENSE_API_KEY" \
-d "grant_type=password" \
-d "username=$ALPHASENSE_EMAIL" \
-d "password=$ALPHASENSE_PASSWORD" \
-d "client_id=$ALPHASENSE_CLIENT_ID" \
-d "client_secret=$ALPHASENSE_CLIENT_SECRET" \
| python3 -c "import sys,json; print(json.load(sys.stdin)['access_token'])")
echo "Authenticated successfully."
Ask a question (GenSearch fast mode)
Use the genSearch.fast GraphQL mutation to submit a natural-language question. Fast mode returns
results optimized for speed. The mutation returns a conversation id that you use to poll for the
answer.
- Python
- JavaScript
- cURL
import json
GRAPHQL_URL = "https://api.alpha-sense.com/gql"
mutation = """
mutation GenSearch($input: GenSearchInput!) {
genSearch {
fast(input: $input) {
id
}
}
}
"""
variables = {
"input": {
"prompt": "What were Apple's key Q4 2024 financial results?"
}
}
headers = {
"x-api-key": api_key,
"clientid": client_id,
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json",
}
response = requests.post(
GRAPHQL_URL,
headers=headers,
json={"query": mutation, "variables": variables},
)
response.raise_for_status()
conversation_id = response.json()["data"]["genSearch"]["fast"]["id"]
print(f"GenSearch started — conversation ID: {conversation_id}")
const GRAPHQL_URL = 'https://api.alpha-sense.com/gql'
const mutation = `
mutation GenSearch($input: GenSearchInput!) {
genSearch {
fast(input: $input) {
id
}
}
}
`
const variables = {
input: {
prompt: "What were Apple's key Q4 2024 financial results?",
},
}
const headers = {
'x-api-key': apiKey,
clientid: clientId,
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json',
}
const searchResponse = await fetch(GRAPHQL_URL, {
method: 'POST',
headers,
body: JSON.stringify({query: mutation, variables}),
})
if (!searchResponse.ok) {
throw new Error(`GenSearch failed: ${searchResponse.status} ${await searchResponse.text()}`)
}
const searchData = await searchResponse.json()
const conversationId = searchData.data.genSearch.fast.id
console.log(`GenSearch started — conversation ID: ${conversationId}`)
GRAPHQL_URL="https://api.alpha-sense.com/gql"
CONVERSATION_ID=$(curl -s -X POST "$GRAPHQL_URL" \
-H "x-api-key: $ALPHASENSE_API_KEY" \
-H "clientid: $ALPHASENSE_CLIENT_ID" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d "$(cat <<'QUERY'
{
"query": "mutation GenSearch($input: GenSearchInput!) { genSearch { fast(input: $input) { id } } }",
"variables": {
"input": {
"prompt": "What were Apple's key Q4 2024 financial results?"
}
}
}
QUERY
)" \
| python3 -c "import sys,json; print(json.load(sys.stdin)['data']['genSearch']['fast']['id'])")
echo "GenSearch started — conversation ID: $CONVERSATION_ID"
Get your answer
Poll the genSearch.conversation query until progress reaches 1.0 (or an error is returned).
The markdown field contains the full answer with inline citations in the format [[N • Source]].
- Python
- JavaScript
- cURL
import time
poll_query = """
query Query($conversationId: String!) {
genSearch {
conversation(id: $conversationId) {
id
markdown
progress
error {
code
}
}
}
}
"""
while True:
poll_response = requests.post(
GRAPHQL_URL,
headers=headers,
json={
"query": poll_query,
"variables": {"conversationId": conversation_id},
},
)
poll_response.raise_for_status()
conversation = poll_response.json()["data"]["genSearch"]["conversation"]
progress = conversation["progress"]
print(f"Progress: {progress:.0%}")
if conversation.get("error"):
raise RuntimeError(f"GenSearch error: {conversation['error']['code']}")
if progress >= 1.0:
break
time.sleep(2)
print("\n--- Answer ---\n")
print(conversation["markdown"])
const pollQuery = `
query Query($conversationId: String!) {
genSearch {
conversation(id: $conversationId) {
id
markdown
progress
error {
code
}
}
}
}
`
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
let conversation
while (true) {
const pollResponse = await fetch(GRAPHQL_URL, {
method: 'POST',
headers,
body: JSON.stringify({
query: pollQuery,
variables: {conversationId},
}),
})
if (!pollResponse.ok) {
throw new Error(`Poll failed: ${pollResponse.status} ${await pollResponse.text()}`)
}
const pollData = await pollResponse.json()
conversation = pollData.data.genSearch.conversation
const progress = conversation.progress
console.log(`Progress: ${(progress * 100).toFixed(0)}%`)
if (conversation.error) {
throw new Error(`GenSearch error: ${conversation.error.code}`)
}
if (progress >= 1.0) {
break
}
await sleep(2000)
}
console.log('\n--- Answer ---\n')
console.log(conversation.markdown)
GRAPHQL_URL="https://api.alpha-sense.com/gql"
while true; do
RESULT=$(curl -s -X POST "$GRAPHQL_URL" \
-H "x-api-key: $ALPHASENSE_API_KEY" \
-H "clientid: $ALPHASENSE_CLIENT_ID" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d "$(cat <<QUERY
{
"query": "query Query(\$conversationId: String!) { genSearch { conversation(id: \$conversationId) { id markdown progress error { code } } } }",
"variables": {
"conversationId": "$CONVERSATION_ID"
}
}
QUERY
)")
PROGRESS=$(echo "$RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin)['data']['genSearch']['conversation']['progress'])")
echo "Progress: ${PROGRESS}"
ERROR=$(echo "$RESULT" | python3 -c "import sys,json; e=json.load(sys.stdin)['data']['genSearch']['conversation'].get('error'); print(e['code'] if e else '')")
if [ -n "$ERROR" ]; then
echo "GenSearch error: $ERROR"
exit 1
fi
DONE=$(echo "$PROGRESS" | python3 -c "import sys; print('yes' if float(sys.stdin.read().strip()) >= 1.0 else 'no')")
if [ "$DONE" = "yes" ]; then
break
fi
sleep 2
done
echo ""
echo "--- Answer ---"
echo ""
echo "$RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin)['data']['genSearch']['conversation']['markdown'])"
Complete script (Python)
Below is a single, copy-paste-ready Python script that combines all three steps. Make sure your environment variables are set before running.
#!/usr/bin/env python3
"""AlphaSense Agent API — Quickstart (GenSearch fast mode)."""
import os
import time
import requests
# ---------------------------------------------------------------------------
# Configuration (reads from environment variables)
# ---------------------------------------------------------------------------
API_KEY = os.environ["ALPHASENSE_API_KEY"]
CLIENT_ID = os.environ["ALPHASENSE_CLIENT_ID"]
CLIENT_SECRET = os.environ["ALPHASENSE_CLIENT_SECRET"]
EMAIL = os.environ["ALPHASENSE_EMAIL"]
PASSWORD = os.environ["ALPHASENSE_PASSWORD"]
AUTH_URL = "https://api.alpha-sense.com/auth"
GRAPHQL_URL = "https://api.alpha-sense.com/gql"
# ---------------------------------------------------------------------------
# Step 1 — Authenticate
# ---------------------------------------------------------------------------
auth_response = requests.post(
AUTH_URL,
headers={
"x-api-key": API_KEY,
"Content-Type": "application/x-www-form-urlencoded",
},
data={
"grant_type": "password",
"username": EMAIL,
"password": PASSWORD,
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
},
)
auth_response.raise_for_status()
access_token = auth_response.json()["access_token"]
print("Step 1 complete — authenticated successfully.\n")
# Shared headers for GraphQL requests
gql_headers = {
"x-api-key": API_KEY,
"clientid": CLIENT_ID,
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json",
}
# ---------------------------------------------------------------------------
# Step 2 — Ask a question (GenSearch fast mode)
# ---------------------------------------------------------------------------
mutation = """
mutation GenSearch($input: GenSearchInput!) {
genSearch {
fast(input: $input) {
id
}
}
}
"""
variables = {
"input": {
"prompt": "What were Apple's key Q4 2024 financial results?"
}
}
search_response = requests.post(
GRAPHQL_URL,
headers=gql_headers,
json={"query": mutation, "variables": variables},
)
search_response.raise_for_status()
conversation_id = search_response.json()["data"]["genSearch"]["fast"]["id"]
print(f"Step 2 complete — conversation ID: {conversation_id}\n")
# ---------------------------------------------------------------------------
# Step 3 — Poll for the answer
# ---------------------------------------------------------------------------
poll_query = """
query Query($conversationId: String!) {
genSearch {
conversation(id: $conversationId) {
id
markdown
progress
error {
code
}
}
}
}
"""
while True:
poll_response = requests.post(
GRAPHQL_URL,
headers=gql_headers,
json={
"query": poll_query,
"variables": {"conversationId": conversation_id},
},
)
poll_response.raise_for_status()
conversation = poll_response.json()["data"]["genSearch"]["conversation"]
progress = conversation["progress"]
print(f" Polling… progress: {progress:.0%}")
if conversation.get("error"):
raise RuntimeError(f"GenSearch error: {conversation['error']['code']}")
if progress >= 1.0:
break
time.sleep(2)
print("\nStep 3 complete — answer received.\n")
print("=" * 60)
print(conversation["markdown"])
print("=" * 60)
Run the script:
# Load your .env (if using dotenv-style file)
export $(grep -v '^#' .env | xargs)
python quickstart.py
What's next?
You have successfully authenticated and retrieved your first GenSearch answer. Here are three paths to explore next:
| Path | Description |
|---|---|
| GenSearch Modes | Learn about auto (recommended), fast, thinkLonger, and deepResearch modes and when to use each. |
| Model Context Protocol (MCP) | Connect the AlphaSense Agent API to AI assistants that support MCP for seamless tool use. |
This documentation is designed to be read by LLMs. You can point your AI assistant to developer.alpha-sense.com/llms.txt for a machine-readable overview, or simply ask it to fetch any page from this portal for full details and code examples.