AlphaSense Generative Search API - Usage Guide
This guide walks through the complete workflow for using the AlphaSense Generative Search API, from authentication to retrieving results.
Overview
The generative search workflow consists of three main steps:
- Authentication - Obtain an access token
- Initiate Search - Trigger a Generative Search request
- Retrieve Results - Poll for and retrieve the search results
Step 1: Authentication
First, authenticate to obtain an access token.
Authentication Code
import requests
# Your credentials
email = 'your-email@example.com'
password = 'your-password'
api_key = 'your-api-key'
client_id = 'your-client-id'
client_secret = 'your-client-secret'
# Authentication request
url = "https://api.alpha-sense.com/auth"
payload = f'grant_type=password&username={email}&password={password}&client_id={client_id}&client_secret={client_secret}'
headers = {
'x-api-key': api_key,
'Content-Type': 'application/x-www-form-urlencoded'
}
response = requests.post(url, headers=headers, data=payload)
access_token = response.json()['access_token']
print(f"Access Token: {access_token}")
Expected Response
{
"access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6...",
"token_type": "bearer",
"expires_in": 3600,
"scope": "...",
"jti": "..."
}
Save the access_token
- you'll need it for the next steps.
Step 2: Initiate Generative Search
Use the access token to initiate a generative search request.
Search Request Code
import requests
import json
# GraphQL endpoint
uri = "https://api.alpha-sense.com/gql"
# Headers with your access token
headers = {
'x-api-key': '<YOUR API KEY>'
'clientid': '<YOUR CLIENT ID>',
'Authorization': f'Bearer {access_token}', # Use token from Step 1
'Content-Type': 'application/json'
}
# Your search prompt
params = {
"input": {"prompt": "What is Apple's strategy for the iPhone Air?"}
}
# GraphQL mutation to initiate search
query = '''mutation GenSearch($input: GenSearchInput!) {
genSearch {
thinkLonger(input: $input) {
id
}
}
}'''
# Make the request
response = requests.post(uri, headers=headers, json={'query': query, "variables": params})
result = response.json()
# Extract and save the conversation ID
conversation_id = result['data']['genSearch']['thinkLonger']['id']
print(f"Conversation ID: {conversation_id}")
Expected Response
{
"data": {
"genSearch": {
"thinkLonger": {
"id": "xxxxxx__xxxxxxxxxxxxx"
}
}
}
}
Save the conversation ID (xxxxxx__xxxxxxxxxxxxx
) - you'll need this to retrieve results.
Step 3: Retrieve Search Results
Poll for results using the conversation ID. Since the API processes requests asynchronously, you'll
need to poll multiple times until progress
reaches 1.0
.
Retrieval Code (Single Poll)
import requests
import json
# GraphQL endpoint
uri = "https://api.alpha-sense.com/gql"
# Headers with your access token
headers = {
'x-api-key': '<YOUR API KEY>'
'clientid': '<YOUR CLIENT ID>',
'Authorization': f'Bearer {access_token}', # Use token from Step 1
'Content-Type': 'application/json'
}
# Conversation ID from Step 2
params = {
"conversationId": "xxxxxx__xxxxxxxxxxxxx"
}
# GraphQL query to retrieve results
query = '''query Query($conversationId: String!) {
genSearch {
conversation(id: $conversationId) {
id
markdown
progress
error {
code
}
}
}
}'''
# Make the request
response = requests.post(uri, headers=headers, json={'query': query, "variables": params})
result = response.json()
# Extract conversation data
conversation = result['data']['genSearch']['conversation']
progress = conversation['progress']
markdown_content = conversation['markdown']
print(f"Progress: {progress}")
if progress == 1.0:
print("Search complete!")
print(f"\nResults:\n{markdown_content}")
else:
print("Still processing... poll again in 20 seconds")
Retrieval Code (Automatic Polling)
import requests
import json
import time
# GraphQL endpoint
uri = "https://api.alpha-sense.com/gql"
# Headers with your access token
headers = {
'x-api-key': '<YOUR API KEY>'
'clientid': '<YOUR CLIENT ID>',
'Authorization': f'Bearer {access_token}', # Use token from Step 1
'Content-Type': 'application/json'
}
# Conversation ID from Step 2
conversation_id = "xxxxxx__xxxxxxxxxxxxx"
params = {
"conversationId": conversation_id
}
# GraphQL query to retrieve results
query = '''query Query($conversationId: String!) {
genSearch {
conversation(id: $conversationId) {
id
markdown
progress
error {
code
}
}
}
}'''
# Poll until complete
max_attempts = 30 # Maximum 30 attempts (10 minutes with 20 second intervals)
for attempt in range(max_attempts):
response = requests.post(uri, headers=headers, json={'query': query, "variables": params})
result = response.json()
conversation = result['data']['genSearch']['conversation']
progress = conversation['progress']
print(f"Attempt {attempt + 1}: Progress = {progress}")
if progress == 1.0:
markdown_content = conversation['markdown']
print("\nSearch complete!")
# Save results
with open(f"outputs/{conversation_id}.md", 'w') as f:
f.write(markdown_content)
print(f"Results saved to outputs/{conversation_id}.md")
break
elif conversation.get('error'):
print(f"Error occurred: {conversation['error']}")
break
else:
print("Still processing... waiting 10 seconds\n")
time.sleep(10)
Understanding the Response
While Processing (progress < 1.0)
{
"data": {
"genSearch": {
"conversation": {
"id": "xxxxxx__xxxxxxxxxxxxx",
"markdown": "",
"progress": 0.45,
"error": null
}
}
}
}
Action: Wait 20 seconds and poll again.
Complete (progress = 1.0)
{
"data": {
"genSearch": {
"conversation": {
"id": "xxxxxx__xxxxxxxxxxxxx",
"markdown": "# Apple's iPhone Air Strategy\n\n...",
"progress": 1.0,
"error": null
}
}
}
}
Success! The markdown
field contains your results.
Complete Example (All Steps Combined)
import requests
import json
import time
# Step 1: Authenticate
print("Step 1: Authenticating...")
email = 'your-email@example.com'
password = 'your-password'
api_key = 'your-api-key'
client_id = 'your-client-id'
client_secret = 'your-client-secret'
auth_url = "https://api.alpha-sense.com/auth"
auth_payload = f'grant_type=password&username={email}&password={password}&client_id={client_id}&client_secret={client_secret}'
auth_headers = {
'x-api-key': api_key,
'Content-Type': 'application/x-www-form-urlencoded'
}
auth_response = requests.post(auth_url, headers=auth_headers, data=auth_payload)
access_token = auth_response.json()['access_token']
print(f"✓ Authenticated\n")
# Step 2: Initiate Search
print("Step 2: Initiating generative search...")
uri = "https://api.alpha-sense.com/gql"
headers = {
'x-api-key': '<YOUR API KEY>'
'clientid': '<YOUR CLIENT ID>',
'Authorization': f'Bearer {access_token}', # Use token from Step 1
'Content-Type': 'application/json'
}
search_params = {
"input": {"prompt": "What is Apple's strategy for the iPhone Air?"}
}
search_query = '''mutation GenSearch($input: GenSearchInput!) {
genSearch {
thinkLonger(input: $input) {
id
}
}
}'''
search_response = requests.post(uri, headers=headers, json={'query': search_query, "variables": search_params})
conversation_id = search_response.json()['data']['genSearch']['thinkLonger']['id']
print(f"✓ Search initiated. Conversation ID: {conversation_id}\n")
# Step 3: Poll for Results
print("Step 3: Polling for results...")
retrieval_params = {"conversationId": conversation_id}
retrieval_query = '''query Query($conversationId: String!) {
genSearch {
conversation(id: $conversationId) {
id
markdown
progress
error {
code
}
}
}
}'''
max_attempts = 30
for attempt in range(max_attempts):
response = requests.post(uri, headers=headers, json={'query': retrieval_query, "variables": retrieval_params})
result = response.json()
conversation = result['data']['genSearch']['conversation']
progress = conversation['progress']
print(f" Attempt {attempt + 1}: Progress = {progress * 100:.0f}%")
if progress == 1.0:
markdown_content = conversation['markdown']
print("\n✓ Search complete!\n")
print("Results:")
print("=" * 80)
print(markdown_content)
print("=" * 80)
# Optional: Save to file
with open(f"{conversation_id}.md", 'w') as f:
f.write(markdown_content)
print(f"\nResults saved to {conversation_id}.md")
break
elif conversation.get('error'):
print(f"\n✗ Error occurred: {conversation['error']}")
break
else:
time.sleep(20)
Troubleshooting
Authentication Errors
- 401 Unauthorized: Check your credentials in
api_auth.py
- 403 Forbidden: Verify your API key is correct
Search Request Errors
- 401 Unauthorized: Your access token may have expired (tokens typically last 1 hour)
- 400 Bad Request: Check your GraphQL query syntax and parameters
Retrieval Errors
- No markdown content: The search is still processing - wait and retry
- Error object present: Check the error code in the response for details
- NO_DOCS: Please run the search again, no results were found within the request
Polling Best Practices
- Wait 20 seconds between polling attempts
- Check the
progress
field: 0.0 = started, 1.0 = complete - Consider implementing automatic polling with a loop and sleep interval
API Endpoints
- Authentication:
https://api.alpha-sense.com/auth
- GraphQL Router:
https://api.alpha-sense.com/gql
Notes
- Access tokens expire after 24 hour - re-authenticate if needed
- The generative search API is asynchronous - always poll for results
- Conversation IDs are unique to each search request and can be viewed in the UI as well at
https://research.alpha-sense.com/gensearch/xxxxxx__xxxxxxxxxxxxx
- Results are returned in markdown format for easy parsing and display