Skip to main content

Integration Examples

This document presents simple examples of how to integrate the NeoSpace API with different popular frameworks and libraries.

Integration with LangChain for Document Processing

This example shows how to use LangChain and the NeoSpace API to process documents and extract specific information.

from langchain.llms import OpenAI
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
import requests

# Configuration
NEOSPACE_API_KEY = "your_api_key_here"
NEOSPACE_URL = "https://api.neospace.ai/v1"
OPENAI_API_KEY = "your_openai_key_here"

# Configure LangChain
llm = OpenAI(temperature=0, api_key=OPENAI_API_KEY)
prompt = PromptTemplate(
input_variables=["text"],
template="Extract the following data from the text below:\n- Company name\n- Document date\n- Total value mentioned\n\nText: {text}\n\nResults:"
)
chain = LLMChain(llm=llm, prompt=prompt)

# Function to fetch document from NeoSpace
def get_document(doc_id):
headers = {
"Authorization": f"Bearer {NEOSPACE_API_KEY}",
"Content-Type": "application/json"
}
response = requests.get(f"{NEOSPACE_URL}/documents/{doc_id}", headers=headers)
return response.json()

# Function to save results to NeoSpace
def save_results(doc_id, results):
headers = {
"Authorization": f"Bearer {NEOSPACE_API_KEY}",
"Content-Type": "application/json"
}
payload = {
"document_id": doc_id,
"extraction_results": results,
"status": "processed"
}
response = requests.post(f"{NEOSPACE_URL}/extractions", headers=headers, json=payload)
return response.json()

# Process a document
def process_document(doc_id):
# 1. Get the document
document = get_document(doc_id)
print(f"Document retrieved: {document['title']}")

# 2. Extract information with LangChain
extraction_result = chain.run(text=document["content"])
print(f"Information extracted:\n{extraction_result}")

# 3. Save results
saved = save_results(doc_id, extraction_result)
print(f"Results saved with ID: {saved['id']}")

return extraction_result

# Run the processing
if __name__ == "__main__":
doc_id = "doc_12345"
process_document(doc_id)

Workflow Automation with Node.js

This example demonstrates how to create an automated workflow that processes data from the NeoSpace API and performs actions based on this data.

const axios = require('axios');

// Configuration
const NEOSPACE_API_KEY = 'your_api_key_here';
const NEOSPACE_URL = 'https://api.neospace.ai/v1';

// API Client
const api = axios.create({
baseURL: NEOSPACE_URL,
headers: {
'Authorization': `Bearer ${NEOSPACE_API_KEY}`,
'Content-Type': 'application/json'
}
});

// 1. Fetch pending tasks
async function fetchPendingTasks() {
try {
const response = await api.get('/tasks', {
params: { status: 'pending', limit: 10 }
});
return response.data.items;
} catch (error) {
console.error('Error fetching tasks:', error.message);
return [];
}
}

// 2. Process a task
async function processTask(task) {
console.log(`Processing task: ${task.id} - ${task.title}`);

try {
// Fetch additional required data
const taskDetails = await api.get(`/tasks/${task.id}/details`);

// Perform specific processing
const result = await performTaskProcessing(task, taskDetails.data);

// Update task status
await api.patch(`/tasks/${task.id}`, {
status: 'completed',
result: result
});

console.log(`Task ${task.id} completed successfully`);
return true;
} catch (error) {
console.error(`Error processing task ${task.id}:`, error.message);

// Log the error
await api.patch(`/tasks/${task.id}`, {
status: 'failed',
error: error.message
});

return false;
}
}

// Specific processing logic
async function performTaskProcessing(task, details) {
// This is a simple example - replace with your actual logic
console.log(`Performing specific processing for task type: ${task.type}`);

// Example: different processing by task type
switch (task.type) {
case 'data_validation':
return {
valid: details.data_points.every(point => point.value >= 0),
validation_date: new Date().toISOString()
};

case 'report_generation':
return {
report_url: `https://app.neospace.ai/reports/${task.id}`,
generated_at: new Date().toISOString()
};

default:
return {
processed: true,
timestamp: new Date().toISOString()
};
}
}

// Main function
async function main() {
console.log('Starting automated workflow...');

// Fetch pending tasks
const pendingTasks = await fetchPendingTasks();
console.log(`Found ${pendingTasks.length} pending tasks`);

// Process each task
let completed = 0;
for (const task of pendingTasks) {
const success = await processTask(task);
if (success) completed++;
}

console.log(`Processing completed. ${completed}/${pendingTasks.length} tasks completed successfully.`);
}

// Run the workflow
main().catch(error => {
console.error('Error in workflow:', error);
});

Sentiment Analysis with Java and NeoSpace API

This example shows how to integrate the NeoSpace API with a Java application to perform sentiment analysis on comments.

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;

public class SentimentAnalysisExample {

private static final String NEOSPACE_API_KEY = "your_api_key_here";
private static final String NEOSPACE_URL = "https://api.neospace.ai/v1";
private static final HttpClient client = HttpClient.newHttpClient();
private static final ObjectMapper mapper = new ObjectMapper();

public static void main(String[] args) {
try {
// 1. Fetch comments for analysis
List<Map<String, Object>> comments = fetchComments();
System.out.println("Comments retrieved: " + comments.size());

// 2. Analyze sentiment for each comment
List<Map<String, Object>> results = new ArrayList<>();
for (Map<String, Object> comment : comments) {
Map<String, Object> sentiment = analyzeSentiment(comment);
results.add(sentiment);
}

// 3. Save analysis results
Map<String, Object> savedResults = saveResults(results);
System.out.println("Results saved with ID: " + savedResults.get("id"));

// 4. Generate sentiment report
generateSentimentReport(savedResults);

} catch (Exception e) {
System.err.println("Error in processing: " + e.getMessage());
e.printStackTrace();
}
}

private static List<Map<String, Object>> fetchComments() throws Exception {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(NEOSPACE_URL + "/comments?status=pending&limit=50"))
.header("Authorization", "Bearer " + NEOSPACE_API_KEY)
.GET()
.build();

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
Map<String, Object> data = mapper.readValue(response.body(), Map.class);
return (List<Map<String, Object>>) data.get("items");
}

private static Map<String, Object> analyzeSentiment(Map<String, Object> comment) throws Exception {
// Prepare data for analysis
String text = (String) comment.get("text");
String commentId = (String) comment.get("id");

// Send to the sentiment analysis endpoint
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(NEOSPACE_URL + "/ai/sentiment-analysis"))
.header("Authorization", "Bearer " + NEOSPACE_API_KEY)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(
mapper.writeValueAsString(Map.of("text", text))
))
.build();

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
Map<String, Object> sentimentResult = mapper.readValue(response.body(), Map.class);

// Add comment ID to the result
sentimentResult.put("comment_id", commentId);

System.out.println("Analyzed comment " + commentId + ": " +
sentimentResult.get("sentiment") + " (" +
sentimentResult.get("score") + ")");

return sentimentResult;
}

private static Map<String, Object> saveResults(List<Map<String, Object>> results) throws Exception {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(NEOSPACE_URL + "/analysis-results"))
.header("Authorization", "Bearer " + NEOSPACE_API_KEY)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(
mapper.writeValueAsString(Map.of(
"type", "sentiment_analysis",
"results", results,
"timestamp", System.currentTimeMillis()
))
))
.build();

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
return mapper.readValue(response.body(), Map.class);
}

private static void generateSentimentReport(Map<String, Object> analysisResults) throws Exception {
String analysisId = (String) analysisResults.get("id");

HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(NEOSPACE_URL + "/reports"))
.header("Authorization", "Bearer " + NEOSPACE_API_KEY)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(
mapper.writeValueAsString(Map.of(
"type", "sentiment_analysis",
"analysis_id", analysisId,
"format", "pdf"
))
))
.build();

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
Map<String, Object> report = mapper.readValue(response.body(), Map.class);

System.out.println("Report generated: " + report.get("url"));
}
}

Additional Integrations These are just some of the many possibilities for integrating with the NeoSpace API. You can also explore:

Integration with Go: For high-performance and microservices applications Webhooks: To receive real-time notifications for events on the NeoSpace platform Integration with BI tools: For data visualization and analysis Automation with GitHub Actions: For CI/CD workflows

Next Steps

Explore the API Reference to see all available endpoints Consult Practical Guides for advanced integration techniques See Best Practices for optimizing your integrations