SUTRA-V2 Online Search

Welcome to the SUTRA-V2 Online Search Guide — designed to help developers leverage SUTRA-V2’s online search feature via the Two.ai API to fetch real-time information, such as the latest news on artificial intelligence. SUTRA-V2’s online search capability allows it to access up-to-date web data, making it ideal for dynamic queries that require current information.

🔍 What is SUTRA-V2?

SUTRA-V2 is a powerful AI model optimized for:

  • Multi-step logical inference
  • Structured problem-solving
  • Deep contextual analysis
  • High-performance conversational AI across 50+ languages

With the online search feature, SUTRA-V2 can fetch real-time data from the web, enhancing its ability to answer queries about current events, trends, and more.

Perfect for applications in:

  • Real-time news aggregation
  • Market trend analysis
  • Dynamic Q&A systems
  • Research automation

🧪 Quickstart: Fetching Latest AI News with SUTRA-V2

Prerequisites

Step 1: Set Up Your Environment

Ensure you have Python installed. You’ll use the built-in http.client library, so no additional packages are required.

Set your SUTRA API key as an environment variable:

export SUTRA_API_KEY="your-sutra-api-key"

Step 2: Use SUTRA-V2’s Online Search Feature

Create a Python script to query the latest AI news using SUTRA-V2’s online search capability:

import http.client
import json
import os

# Establish connection to Two.ai API
conn = http.client.HTTPSConnection("api.two.ai")

# Prepare the request payload
payload = json.dumps({
    "model": "sutra-v2",
    "messages": [
        {
            "role": "system",
            "content": "You are a helpful assistant."
        },
        {
            "role": "user",
            "content": "Give me the latest news on artificial intelligence as of May 27, 2025."
        }
    ],
    "max_tokens": 100,
    "temperature": 0.3,
    "stream": False,
    "extra_body": {
        "online_search": True
    }
})

# Set up headers with your API key
headers = {
    'Content-Type': "application/json",
    'Authorization': "Bearer sutra api key here"
}

try:
    # Send the request
    conn.request("POST", "/v2/chat/completions", payload, headers)

    # Get and process the response
    res = conn.getresponse()
    data = res.read()

    # Print the response
    print(data.decode("utf-8"))

except Exception as e:
    print(f"Error occurred: {e}")

finally:
    conn.close()

Step 3: Run the Script

Execute the script to fetch the latest AI news. On May 27, 2025, SUTRA-V2 might return news like:

  • Researchers at Sussex University are exploring AI consciousness using the "Dreamachine" project, investigating whether AI could become sentient as large language models evolve.
  • Google DeepMind’s CEO, Demis Hassabis, warned that AI will disrupt jobs within 5 years, urging teens to prepare by becoming "AI ninjas" and mastering the technology.

These updates reflect SUTRA-V2’s ability to pull real-time web data, ensuring you get the most current information available.


Example: Querying Parks in Multiple Cities with Two.ai API

This example demonstrates how to use the Two.ai SUTRA API to query information about parks in multiple cities using Python. The script sets different user locations and retrieves information about nearby parks.

import http.client
import os
import json
import time

# API key for Two.ai SUTRA API
api_key = ""

# Check if API key is available
if not api_key:
    print("Error: API key not set.")
    print("Get your API key from: https://developer.two.ai")
    exit(1)

# Create connection to Two.ai API
conn = http.client.HTTPSConnection("api.two.ai")

# Define multiple locations
locations = [
    {
        "city": "Mumbai",
        "region": "Maharashtra",
        "country_name": "India",
        "country_code": "IN",
        "language_code": "en",
        "locale": "en-IN"
    },
    {
        "city": "New York",
        "region": "New York",
        "region_type": "state",
        "country_name": "United States",
        "country_code": "US",
        "language_code": "en",
        "locale": "en-US"
    },
    {
        "city": "Seoul",
        "country_name": "South Korea",
        "country_code": "KR",
        "language_code": "en",
        "locale": "en-US"
    },
    {
        "city": "San Francisco",
        "region": "California",
        "region_type": "state",
        "country_name": "United States",
        "country_code": "US",
        "language_code": "en",
        "locale": "en-US"
    }
]

# Common headers for all requests
headers = {
    "Content-Type": "application/json",
    "Authorization": f"Bearer {api_key}"
}

# Function to query about parks in a specific location
def query_parks_in_location(location):
    city_name = location["city"]
    
    # Set the user's location
    print(f"\n{'='*50}")
    print(f"Setting user location to {city_name}...")
    conn.request("POST", "/v2/location", json.dumps(location), headers)
    res = conn.getresponse()
    data = res.read()
    print(f"Location response: {data.decode('utf-8')}")
    
    # Create chat payload for this location
    chat_payload = {
        "model": "sutra-v2",
        "messages": [
            {"role": "system", "content": "You are a helpful assistant that provides information about local places."},
            {"role": "user", "content": f"Which is the nearest park to me in {city_name}? Please keep your answer brief and mention 1-2 popular parks."}
        ],
        "max_tokens": 300,
        "temperature": 0.7
    }
    
    # Ask about the nearest park
    print(f"\nAsking about parks in {city_name}...")
    conn.request("POST", "/v2/chat/completions", json.dumps(chat_payload), headers)
    res = conn.getresponse()
    data = res.read()
    
    # Parse and display the response
    response = json.loads(data.decode("utf-8"))
    if "choices" in response and len(response["choices"]) > 0:
        print(f"\nParks in {city_name}:")
        print(response["choices"][0]["message"]["content"])
    else:
        print(f"\nError or unexpected response format for {city_name}:")
        print(json.dumps(response, indent=2))

# Query each location
print("Querying about parks in multiple cities...")
for location in locations:
    query_parks_in_location(location)
    # Add a small delay between requests to avoid rate limiting
    time.sleep(1)

Usage Instructions

  1. Replace api_key = "" with your actual Two.ai API key from Two.ai SUTRA API.
  2. Run the script to query park information for Mumbai, New York, Seoul, and San Francisco.
  3. The script sets the user location for each city and retrieves information about 1-2 popular parks nearby.
  4. A 1-second delay is included between requests to avoid hitting API rate limits.

Notes

  • Ensure a valid API key is provided to avoid authentication errors.
  • The script uses the http.client module for HTTPS requests and json for payload handling.
  • Responses are parsed and displayed in a formatted manner for each city.

🧠 Best Practices for Online Search with SUTRA-V2

  • Enable Online Search: Always set "online_search": True in the extra_body of your payload to activate this feature.
  • Specify Dates: For time-sensitive queries, include the date in your prompt (e.g., "as of May 27, 2025") to ensure accurate results.
  • Limit Response Length: Use max_tokens (e.g., 100) to keep responses concise for news summaries.
  • Handle Errors: Add error handling (as shown in the script) to manage network issues or API errors gracefully.
  • Use Low Temperature: A temperature of 0.3 ensures more factual and deterministic responses for news queries.

ParameterPurposeRecommended for V2
temperatureControls randomness0.3 for factual output
max_tokensLimits response length100–200 for summaries
extra_bodyEnables online search{"online_search": True}

🔗 API Access (cURL)

Test the SUTRA-V2 online search feature directly with a cURL command:

curl -X POST https://api.two.ai/v2/chat/completions \
-H "Authorization: Bearer $SUTRA_API_KEY" \
-H "Content-Type: application/json" \
-d '{
  "model": "sutra-v2",
  "messages": [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "Give me the latest news on artificial intelligence as of May 27, 2025."}
  ],
  "max_tokens": 100,
  "temperature": 0.3,
  "extra_body": {"online_search": True}
}'

🛠 Troubleshooting

  • Invalid API Key: Ensure SUTRA_API_KEY is set in your environment variables and correctly included in the Authorization header.
  • Online Search Not Working: Verify that "online_search": True is set in the extra_body of your payload.
  • Incomplete Responses: Increase max_tokens if the news summary is cut off (e.g., try 200).
  • Network Errors: Check your internet connection and ensure the Two.ai API endpoint (https://api.two.ai/v2) is accessible.
  • Outdated Information: Include the current date in your prompt to ensure SUTRA-V2 fetches the latest data.