Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.neuraltalk.ai/llms.txt

Use this file to discover all available pages before exploring further.

Client SDK Documentation

Integrate NeuralTalk AI into your applications using our official client SDKs for JavaScript, Python, and other popular languages.

Overview

Our client SDKs provide a simple and intuitive way to integrate NeuralTalk AI into your applications. They handle authentication, request formatting, error handling, and response parsing automatically.

Supported Languages

  • JavaScript/Node.js - For web applications and server-side development
  • Python - For data science, machine learning, and backend services
  • PHP - For web applications and content management systems
  • Java - For enterprise applications and Android development
  • C# - For .NET applications and Windows development
  • Go - For high-performance backend services
  • Ruby - For web applications and scripting

JavaScript SDK

Installation

npm install @neuraltalk/ai-sdk

Basic Usage

import { NeuralTalkClient } from '@neuraltalk/ai-sdk';

// Initialize the client
const client = new NeuralTalkClient({
  apiKey: 'your-api-key',
  assistantId: 'your-assistant-id'
});

// Send a message
async function sendMessage() {
  try {
    const response = await client.sendMessage({
      message: 'Hello, I need help with my account',
      userId: 'user_123'
    });
    
    console.log('Response:', response.message);
  } catch (error) {
    console.error('Error:', error.message);
  }
}

Advanced Usage

// Initialize with custom configuration
const client = new NeuralTalkClient({
  apiKey: 'your-api-key',
  assistantId: 'your-assistant-id',
  baseUrl: 'https://api.neuraltalk.ai',
  timeout: 30000,
  retries: 3
});

// Send message with metadata
const response = await client.sendMessage({
  message: 'I need help with billing',
  userId: 'user_123',
  metadata: {
    source: 'website',
    page: '/billing',
    userAgent: navigator.userAgent
  }
});

// Get conversation history
const conversation = await client.getConversation('conv_123456789');

// Update feedback
await client.updateFeedback('msg_123456789', {
  feedback: 'positive',
  rating: 5,
  comment: 'Very helpful!'
});

React Integration

import React, { useState, useEffect } from 'react';
import { NeuralTalkClient } from '@neuraltalk/ai-sdk';

const ChatComponent = () => {
  const [client] = useState(new NeuralTalkClient({
    apiKey: process.env.REACT_APP_NEURALTALK_API_KEY,
    assistantId: process.env.REACT_APP_NEURALTALK_ASSISTANT_ID
  }));
  
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');
  const [loading, setLoading] = useState(false);
  
  const sendMessage = async () => {
    if (!input.trim()) return;
    
    setLoading(true);
    
    try {
      const response = await client.sendMessage({
        message: input,
        userId: 'user_123'
      });
      
      setMessages(prev => [
        ...prev,
        { role: 'user', content: input },
        { role: 'assistant', content: response.message }
      ]);
      
      setInput('');
    } catch (error) {
      console.error('Error sending message:', error);
    } finally {
      setLoading(false);
    }
  };
  
  return (
    <div className="chat-container">
      <div className="messages">
        {messages.map((msg, index) => (
          <div key={index} className={`message ${msg.role}`}>
            {msg.content}
          </div>
        ))}
      </div>
      
      <div className="input-container">
        <input
          type="text"
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyPress={(e) => e.key === 'Enter' && sendMessage()}
          placeholder="Type your message..."
          disabled={loading}
        />
        <button onClick={sendMessage} disabled={loading}>
          {loading ? 'Sending...' : 'Send'}
        </button>
      </div>
    </div>
  );
};

export default ChatComponent;

Python SDK

Installation

pip install neuraltalk-ai

Basic Usage

from neuraltalk import NeuralTalkClient

# Initialize the client
client = NeuralTalkClient(
    api_key='your-api-key',
    assistant_id='your-assistant-id'
)

# Send a message
def send_message():
    try:
        response = client.send_message(
            message='Hello, I need help with my account',
            user_id='user_123'
        )
        print(f'Response: {response.message}')
    except Exception as error:
        print(f'Error: {error}')

# Usage
send_message()

Advanced Usage

from neuraltalk import NeuralTalkClient
from neuraltalk.types import Message, Feedback

# Initialize with custom configuration
client = NeuralTalkClient(
    api_key='your-api-key',
    assistant_id='your-assistant-id',
    base_url='https://api.neuraltalk.ai',
    timeout=30,
    retries=3
)

# Send message with metadata
response = client.send_message(
    message='I need help with billing',
    user_id='user_123',
    metadata={
        'source': 'website',
        'page': '/billing',
        'user_agent': 'Mozilla/5.0...'
    }
)

# Get conversation history
conversation = client.get_conversation('conv_123456789')

# Update feedback
client.update_feedback(
    message_id='msg_123456789',
    feedback=Feedback(
        feedback='positive',
        rating=5,
        comment='Very helpful!'
    )
)

Flask Integration

from flask import Flask, request, jsonify, render_template
from neuraltalk import NeuralTalkClient

app = Flask(__name__)

# Initialize the client
client = NeuralTalkClient(
    api_key='your-api-key',
    assistant_id='your-assistant-id'
)

@app.route('/')
def index():
    return render_template('chat.html')

@app.route('/api/chat', methods=['POST'])
def chat():
    data = request.get_json()
    
    try:
        response = client.send_message(
            message=data['message'],
            user_id=data.get('user_id', 'anonymous'),
            metadata=data.get('metadata', {})
        )
        
        return jsonify({
            'success': True,
            'message': response.message,
            'conversation_id': response.conversation_id
        })
    except Exception as error:
        return jsonify({
            'success': False,
            'error': str(error)
        }), 500

@app.route('/api/feedback', methods=['POST'])
def feedback():
    data = request.get_json()
    
    try:
        client.update_feedback(
            message_id=data['message_id'],
            feedback=Feedback(
                feedback=data['feedback'],
                rating=data.get('rating'),
                comment=data.get('comment')
            )
        )
        
        return jsonify({'success': True})
    except Exception as error:
        return jsonify({
            'success': False,
            'error': str(error)
        }), 500

if __name__ == '__main__':
    app.run(debug=True)

PHP SDK

Installation

composer require neuraltalk/ai-sdk

Basic Usage

<?php
require_once 'vendor/autoload.php';

use NeuralTalk\NeuralTalkClient;

// Initialize the client
$client = new NeuralTalkClient([
    'api_key' => 'your-api-key',
    'assistant_id' => 'your-assistant-id'
]);

// Send a message
try {
    $response = $client->sendMessage([
        'message' => 'Hello, I need help with my account',
        'user_id' => 'user_123'
    ]);
    
    echo 'Response: ' . $response['message'];
} catch (Exception $error) {
    echo 'Error: ' . $error->getMessage();
}
?>

Laravel Integration

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use NeuralTalk\NeuralTalkClient;

class ChatController extends Controller
{
    private $client;
    
    public function __construct()
    {
        $this->client = new NeuralTalkClient([
            'api_key' => config('neuraltalk.api_key'),
            'assistant_id' => config('neuraltalk.assistant_id')
        ]);
    }
    
    public function sendMessage(Request $request)
    {
        $request->validate([
            'message' => 'required|string',
            'user_id' => 'nullable|string'
        ]);
        
        try {
            $response = $this->client->sendMessage([
                'message' => $request->message,
                'user_id' => $request->user_id ?? 'anonymous',
                'metadata' => $request->metadata ?? []
            ]);
            
            return response()->json([
                'success' => true,
                'message' => $response['message'],
                'conversation_id' => $response['conversation_id']
            ]);
        } catch (Exception $error) {
            return response()->json([
                'success' => false,
                'error' => $error->getMessage()
            ], 500);
        }
    }
    
    public function updateFeedback(Request $request)
    {
        $request->validate([
            'message_id' => 'required|string',
            'feedback' => 'required|string',
            'rating' => 'nullable|integer|min:1|max:5',
            'comment' => 'nullable|string'
        ]);
        
        try {
            $this->client->updateFeedback([
                'message_id' => $request->message_id,
                'feedback' => $request->feedback,
                'rating' => $request->rating,
                'comment' => $request->comment
            ]);
            
            return response()->json(['success' => true]);
        } catch (Exception $error) {
            return response()->json([
                'success' => false,
                'error' => $error->getMessage()
            ], 500);
        }
    }
}
?>

Java SDK

Installation

Add to your pom.xml:
<dependency>
    <groupId>ai.neuraltalk</groupId>
    <artifactId>neuraltalk-sdk</artifactId>
    <version>1.0.0</version>
</dependency>

Basic Usage

import ai.neuraltalk.NeuralTalkClient;
import ai.neuraltalk.models.Message;
import ai.neuraltalk.models.Response;

public class ChatExample {
    public static void main(String[] args) {
        // Initialize the client
        NeuralTalkClient client = new NeuralTalkClient.Builder()
            .apiKey("your-api-key")
            .assistantId("your-assistant-id")
            .build();
        
        // Send a message
        try {
            Message message = new Message.Builder()
                .content("Hello, I need help with my account")
                .userId("user_123")
                .build();
            
            Response response = client.sendMessage(message);
            System.out.println("Response: " + response.getMessage());
        } catch (Exception error) {
            System.err.println("Error: " + error.getMessage());
        }
    }
}

Spring Boot Integration

@RestController
@RequestMapping("/api/chat")
public class ChatController {
    
    @Autowired
    private NeuralTalkClient neuralTalkClient;
    
    @PostMapping("/send")
    public ResponseEntity<Map<String, Object>> sendMessage(@RequestBody Map<String, String> request) {
        try {
            Message message = new Message.Builder()
                .content(request.get("message"))
                .userId(request.getOrDefault("user_id", "anonymous"))
                .build();
            
            Response response = neuralTalkClient.sendMessage(message);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", response.getMessage());
            result.put("conversation_id", response.getConversationId());
            
            return ResponseEntity.ok(result);
        } catch (Exception error) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("error", error.getMessage());
            
            return ResponseEntity.status(500).body(result);
        }
    }
}

C# SDK

Installation

dotnet add package NeuralTalk.AI.SDK

Basic Usage

using NeuralTalk.AI;

class Program
{
    static async Task Main(string[] args)
    {
        // Initialize the client
        var client = new NeuralTalkClient(new NeuralTalkConfig
        {
            ApiKey = "your-api-key",
            AssistantId = "your-assistant-id"
        });
        
        // Send a message
        try
        {
            var message = new Message
            {
                Content = "Hello, I need help with my account",
                UserId = "user_123"
            };
            
            var response = await client.SendMessageAsync(message);
            Console.WriteLine($"Response: {response.Message}");
        }
        catch (Exception error)
        {
            Console.WriteLine($"Error: {error.Message}");
        }
    }
}

ASP.NET Core Integration

[ApiController]
[Route("api/[controller]")]
public class ChatController : ControllerBase
{
    private readonly NeuralTalkClient _neuralTalkClient;
    
    public ChatController(NeuralTalkClient neuralTalkClient)
    {
        _neuralTalkClient = neuralTalkClient;
    }
    
    [HttpPost("send")]
    public async Task<IActionResult> SendMessage([FromBody] SendMessageRequest request)
    {
        try
        {
            var message = new Message
            {
                Content = request.Message,
                UserId = request.UserId ?? "anonymous"
            };
            
            var response = await _neuralTalkClient.SendMessageAsync(message);
            
            return Ok(new
            {
                success = true,
                message = response.Message,
                conversation_id = response.ConversationId
            });
        }
        catch (Exception error)
        {
            return StatusCode(500, new
            {
                success = false,
                error = error.Message
            });
        }
    }
}

Go SDK

Installation

go get github.com/neuraltalk/ai-sdk-go

Basic Usage

package main

import (
    "fmt"
    "log"
    "github.com/neuraltalk/ai-sdk-go"
)

func main() {
    // Initialize the client
    client := neuraltalk.NewClient(&neuraltalk.Config{
        APIKey:      "your-api-key",
        AssistantID: "your-assistant-id",
    })
    
    // Send a message
    message := &neuraltalk.Message{
        Content: "Hello, I need help with my account",
        UserID:  "user_123",
    }
    
    response, err := client.SendMessage(message)
    if err != nil {
        log.Fatal(err)
    }
    
    fmt.Printf("Response: %s\n", response.Message)
}

Ruby SDK

Installation

gem install neuraltalk-ai

Basic Usage

require 'neuraltalk'

# Initialize the client
client = NeuralTalk::Client.new(
  api_key: 'your-api-key',
  assistant_id: 'your-assistant-id'
)

# Send a message
begin
  response = client.send_message(
    message: 'Hello, I need help with my account',
    user_id: 'user_123'
  )
  
  puts "Response: #{response.message}"
rescue => error
  puts "Error: #{error.message}"
end

Error Handling

All SDKs provide consistent error handling:
// JavaScript
try {
  const response = await client.sendMessage({
    message: 'Hello',
    userId: 'user_123'
  });
} catch (error) {
  if (error.code === 'RATE_LIMITED') {
    // Handle rate limiting
  } else if (error.code === 'UNAUTHORIZED') {
    // Handle authentication error
  } else {
    // Handle other errors
  }
}
# Python
try:
    response = client.send_message(
        message='Hello',
        user_id='user_123'
    )
except RateLimitedError:
    # Handle rate limiting
except UnauthorizedError:
    # Handle authentication error
except Exception as error:
    # Handle other errors

Configuration

All SDKs support the following configuration options:
OptionTypeDefaultDescription
api_keystringRequiredYour NeuralTalk AI API key
assistant_idstringRequiredYour assistant ID
base_urlstringhttps://api.neuraltalk.aiAPI base URL
timeoutinteger30Request timeout in seconds
retriesinteger3Number of retry attempts
debugbooleanfalseEnable debug logging

Best Practices

Authentication

  1. Secure Storage: Store API keys securely
  2. Environment Variables: Use environment variables for configuration
  3. Key Rotation: Regularly rotate API keys
  4. Access Control: Limit API key permissions

Error Handling

  1. Retry Logic: Implement exponential backoff
  2. Graceful Degradation: Handle errors gracefully
  3. Logging: Log errors for debugging
  4. User Feedback: Provide meaningful error messages

Performance

  1. Connection Pooling: Reuse connections when possible
  2. Caching: Cache responses when appropriate
  3. Batching: Batch requests when possible
  4. Monitoring: Monitor API usage and performance

Support

For additional help with the client SDKs:
Ready to integrate NeuralTalk AI? Choose your preferred language and start building with our client SDKs!