Andromeda Labs
  • Welcome
  • SERVICES
    • Getting Started
    • Creating ChatBots & Inference API's
    • Accessing Created API Endpoints
    • Hosting Machine Learning Models
  • SUPPORT
    • Support
Powered by GitBook
On this page
  1. SERVICES

Accessing Created API Endpoints

Using code to access the API endpoints


// Basic example of using the Andromeda Labs Chat API
const endpoint = 'https://meda-pd1c26oq.b4a.run/chat/7a0068f3-87bf-4766-a424-66a2124504f0/';

// For Inference Endpoints
const requestData = {
  "history": [
    {"role": "assistant", "content": "how can i help you today"}
  ],
  "query": "What is Science",
  // This must be the id of the asset
  "asset": "79083119-db53-4e5e-b0c4-914c7e42064c"
};

// sending a request
fetch(endpoint, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(requestData)
})
.then(response => response.json())
.then(data => console.log('Response:', data));
# Basic example of using the Andromeda Labs Chat API with Python

# you should run the command below first before using requests
# pip install requests 

import requests

import json

endpoint = 'https://meda-pd1c26oq.b4a.run/chat/7a0068f3-87bf-4766-a424-66a2124504f0/'

request_data = {
    "history": [
        {"role": "assistant", "content": "how can i help you today"}
    ],
    "query": "What is Science",
    "asset": "79083119-db53-4e5e-b0c4-914c7e42064c"
}

response = requests.post(
    endpoint,
    headers={'Content-Type': 'application/json'},
    data=json.dumps(request_data)
)

print('Response:', response.json())
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class AndromedaLabsChatAPI {
    public static void main(String[] args) {
        try {
            // Basic example of using the Andromeda Labs Chat API
            String endpoint = "https://meda-pd1c26oq.b4a.run/chat/7a0068f3-87bf-4766-a424-66a2124504f0/";
            
            // Create the request body
            String requestBody = "{"
                + "\"history\": ["
                + "    {\"role\": \"assistant\", \"content\": \"how can i help you today\"}"
                + "],"
                + "\"query\": \"What is Science\","
                + "\"asset\": \"79083119-db53-4e5e-b0c4-914c7e42064c\""
                + "}";
            
            // Create the connection
            URL url = new URL(endpoint);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);
            
            // Send the request
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = requestBody.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }
            
            // Read the response
            int responseCode = connection.getResponseCode();
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                System.out.println("Response: " + response.toString());
            }
            
            connection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
/// Define interfaces for the request and response
interface ChatMessage {
  role: 'user' | 'assistant';
  content: string;
}

interface ChatRequest {
  history: ChatMessage[];
  query: string;
  asset: string;
}

interface ChatResponse {
  // Add expected response properties here
  // This is a placeholder and should be updated with actual response structure
  message?: string;
  response?: string;
  [key: string]: any;
}

// Basic example of using the Andromeda Labs Chat API
const endpoint: string = 'https://meda-pd1c26oq.b4a.run/chat/7a0068f3-87bf-4766-a424-66a2124504f0/';

// For Inference Endpoints
const requestData: ChatRequest = {
  "history": [
    {"role": "assistant", "content": "how can i help you today"}
  ],
  "query": "What is Science",
  // This must be the id of the asset
  "asset": "79083119-db53-4e5e-b0c4-914c7e42064c"
};

// Function to send a request
async function sendChatRequest(endpoint: string, data: ChatRequest): Promise<ChatResponse> {
  try {
    const response = await fetch(endpoint, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    });
    
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    
    return await response.json() as ChatResponse;
  } catch (error) {
    console.error('Error sending chat request:', error);
    throw error;
  }
}

// Example usage
sendChatRequest(endpoint, requestData)
  .then(data => console.log('Response:', data))
  .catch(error => console.error('Request failed:', error));

// Alternative usage with async/await in an async function
async function makeRequest() {
  try {
    const data = await sendChatRequest(endpoint, requestData);
    console.log('Response:', data);
  } catch (error) {
    console.error('Request failed:', error);
  }
}

// Call the async function
// makeRequest();
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
)

// ChatMessage represents a message in the chat history
type ChatMessage struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

// ChatRequest represents the request structure for the chat API
type ChatRequest struct {
	History []ChatMessage `json:"history"`
	Query   string        `json:"query"`
	Asset   string        `json:"asset"`
}

func main() {
	// Basic example of using the Andromeda Labs Chat API
	endpoint := "https://meda-pd1c26oq.b4a.run/chat/7a0068f3-87bf-4766-a424-66a2124504f0/"

	// For Inference Endpoints
	requestData := ChatRequest{
		History: []ChatMessage{
			{
				Role:    "assistant",
				Content: "how can i help you today",
			},
		},
		Query: "What is Science",
		// This must be the id of the asset
		Asset: "79083119-db53-4e5e-b0c4-914c7e42064c",
	}

	// Convert the request data to JSON
	jsonData, err := json.Marshal(requestData)
	if err != nil {
		log.Fatalf("Error marshaling JSON: %v", err)
	}

	// Create a new request
	req, err := http.NewRequest("POST", endpoint, bytes.NewBuffer(jsonData))
	if err != nil {
		log.Fatalf("Error creating request: %v", err)
	}

	// Set headers
	req.Header.Set("Content-Type", "application/json")

	// Send the request
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		log.Fatalf("Error sending request: %v", err)
	}
	defer resp.Body.Close()

	// Read the response
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatalf("Error reading response: %v", err)
	}

	// Parse response as JSON
	var responseData map[string]interface{}
	err = json.Unmarshal(body, &responseData)
	if err != nil {
		log.Printf("Error parsing JSON response: %v", err)
		// Print raw response if JSON parsing fails
		fmt.Println("Response:", string(body))
		return
	}

	// Print the response
	fmt.Println("Response:", responseData)
}
import 'dart:convert';
import 'package:http/http.dart' as http;

void main() async {
  // copy this from the website
  final String endpoint =
      'https://meda-pd1c26oq.b4a.run/chat/7a0068f3-87bf-4766-a424-66a2124504f0/';

  final Map<String, dynamic> requestData = {
    "history": [
      {"role": "assistant", "content": "how can i help you today"}
    ],
    "query": "What is Science",
    "asset": "79083119-db53-4e5e-b0c4-914c7e42064c",
  };

  try {
    final response = await http.post(
      Uri.parse(endpoint),
      headers: {'Content-Type': 'application/json'},
      body: jsonEncode(requestData),
    );

    if (response.statusCode == 200) {
      final Map<String, dynamic> data = jsonDecode(response.body);
      print('Response: $data');
    } else {
      print('Request failed with status: ${response.statusCode}');
      print('Response body: ${response.body}');
    }
  } catch (error) {
    print('Error sending request: $error');
  }
}

Once you’ve tested the API , its now okay to go ahead and integrate it into your project as you wish

PreviousCreating ChatBots & Inference API'sNextHosting Machine Learning Models

Last updated 1 month ago

Page cover image