API

Ecosistema completo para organización y gestión de contenido con interfaces espaciales

gograb-ai API Reference

This document provides a detailed reference of the gograb-ai library API.

Core Services

AIFactoryService

The central service for obtaining provider-specific AI services.

import { AIFactoryService, AIProvider } from '@gograb-ai';

// Inject the service
private aiFactory = inject(AIFactoryService);

// Get a specific provider's service
const openaiService = this.aiFactory.getService(AIProvider.OPENAI);
const anthropicService = this.aiFactory.getService(AIProvider.ANTHROPIC);

// Get the best available service (tries in order: Anthropic, OpenAI)
const bestService = this.aiFactory.getBestAvailableService();

Methods

Method Description Parameters Return Type
getService(provider: AIProvider) Gets a specific AI service provider: The AI provider to use AIService
getBestAvailableService() Gets the first available service None AIService
isProviderAvailable(provider: AIProvider) Checks if a provider is available provider: The AI provider to check boolean

AIConfigService

Manages configuration for AI providers.

import { AIConfigService, AIProvider } from '@gograb-ai';

// Inject the service
private aiConfig = inject(AIConfigService);

// Get configuration for a provider
const openaiConfig = this.aiConfig.getConfig(AIProvider.OPENAI);

// Set API key
this.aiConfig.setApiKey(AIProvider.ANTHROPIC, 'sk-ant-api03-...');

// Update other configuration parameters
this.aiConfig.setTemperature(AIProvider.OPENAI, 0.7);
this.aiConfig.setMaxTokens(AIProvider.ANTHROPIC, 1000);

Methods

Method Description Parameters Return Type
getConfig(provider: AIProvider) Gets configuration for a provider provider: The AI provider AIProviderConfig
setApiKey(provider: AIProvider, key: string) Sets API key provider: Provider, key: API key void
setTemperature(provider: AIProvider, temp: number) Sets temperature provider: Provider, temp: Value (0-1) void
setMaxTokens(provider: AIProvider, tokens: number) Sets max tokens provider: Provider, tokens: Max tokens void
setDefaultModel(provider: AIProvider, model: string) Sets default model provider: Provider, model: Model name void
updateConfig(provider: AIProvider, config: Partial<AIProviderConfig>) Updates multiple config values provider: Provider, config: Config object void
resetConfig(provider: AIProvider) Resets config to defaults provider: The AI provider void

AIService Interface

Interface implemented by all AI provider services.

import { AIService, AIProvider, MessageRole } from '@gograb-ai';

// Example usage pattern (typically obtained through AIFactoryService)
const aiService: AIService = this.aiFactory.getService(AIProvider.OPENAI);

// Use the service to complete a prompt
aiService.complete([
  { role: MessageRole.SYSTEM, content: 'You are a helpful assistant.' },
  { role: MessageRole.USER, content: 'Tell me a joke.' }
], {
  temperature: 0.7,
  maxTokens: 500
}).subscribe({
  next: (response) => console.log(response.text),
  error: (err) => console.error('Error:', err)
});

Methods

Method Description Parameters Return Type
complete(messages: Message[], options?: CompleteOptions) Generates AI completion messages: Array of messages, options: Optional settings Observable<AIResponse>
testConnection() Tests API connection None Observable<boolean>
getDefaultModel() Gets default model for provider None string

Core Types and Interfaces

AIProvider Enum

Identifies supported AI providers.

enum AIProvider {
  OPENAI = 'openai',
  ANTHROPIC = 'anthropic'
}

MessageRole Enum

Identifies message role types.

enum MessageRole {
  SYSTEM = 'system',
  USER = 'user',
  ASSISTANT = 'assistant'
}

Message Interface

Represents a message in a conversation.

interface Message {
  role: MessageRole;
  content: string;
}

AIResponse Interface

Response from an AI completion request.

interface AIResponse {
  text: string;
  usage?: {
    promptTokens?: number;
    completionTokens?: number;
    totalTokens?: number;
  };
}

CompleteOptions Interface

Options for AI completion requests.

interface CompleteOptions {
  systemPrompt?: string;          // System prompt to prepend
  temperature?: number;           // Temperature (0-1)
  maxTokens?: number;             // Maximum tokens in response
  model?: string;                 // Model to use, overrides default
  promptTemplate?: {              // Custom prompt template
    prefix?: string;
    suffix?: string;
  };
  templateVars?: Record<string, string>; // Variables for template
  stream?: boolean;               // Whether to stream the response
  betaHeader?: string;            // For Anthropic beta features
}

AIProviderConfig Interface

Configuration for an AI provider.

interface AIProviderConfig {
  provider: AIProvider;           // Provider identifier
  apiKey: string;                 // API key
  defaultModel: string;           // Default model to use
  temperature: number;            // Default temperature
  maxTokens: number;              // Default max tokens
  implementationConfig?: any;     // Provider-specific config
}

Provider-Specific Services

OpenAIService

Implements AIService for OpenAI API.

// This service is obtained through AIFactoryService
const openaiService = this.aiFactory.getService(AIProvider.OPENAI);

Supported Models

AnthropicService

Implements AIService for Anthropic API.

// This service is obtained through AIFactoryService
const anthropicService = this.aiFactory.getService(AIProvider.ANTHROPIC);

Supported Models

AnthropicProxyService

Manages the connection to the Anthropic proxy server.

import { AnthropicProxyService } from '@gograb-ai';

// Inject the service
private proxyService = inject(AnthropicProxyService);

// Check proxy status
this.proxyService.checkProxyStatus().subscribe({
  next: () => console.log('Proxy is running'),
  error: () => console.log('Proxy is not running')
});

Methods

Method Description Parameters Return Type
checkProxyStatus() Checks if proxy is running None Observable<any>
getProxyUrl() Gets the proxy URL None string

Utility Services

SearchEnhancementService

Provides AI-enhanced search capabilities.

import { SearchEnhancementService, SearchEnhancementOptions } from '@gograb-ai';

// Inject the service
private searchService = inject(SearchEnhancementService);

// Define search options
const options: SearchEnhancementOptions = {
  query: 'user search query',
  context: ['product', 'description'],
  fuzzyThreshold: 0.6,
  enableSynonyms: true,
  synonymMap: {
    'product': ['item', 'goods'],
  }
};

// Search through items
this.searchService.enhanceSearch(options, items).subscribe(results => {
  console.log('Search results:', results.results);
  console.log('Enhanced query:', results.enhancedQuery);
});

Methods

Method Description Parameters Return Type
enhanceSearch(options: SearchEnhancementOptions, items: any[]) Enhances search results options: Search options, items: Items to search Observable<SearchResult>
enhanceQuery(query: string, context: string[]) Enhances a search query query: Original query, context: Search context Observable<string>

Configuration Function

provideGograbAI

Configures and provides all gograb-ai services.

import { provideGograbAI, AIProvider } from '@gograb-ai';

// Basic configuration
return provideGograbAI({
  openAIKey: 'sk-...',
  anthropicKey: 'sk-ant-...'
});

// Advanced configuration
return provideGograbAI({
  openAIKey: 'sk-...',
  anthropicKey: 'sk-ant-...',
  implementationConfig: {
    [AIProvider.ANTHROPIC]: {
      baseUrl: 'http://localhost:3001/api/anthropic',
      maxRetries: 1,
      timeout: 60000
    }
  }
});

Parameters

Parameter Type Description Required
openAIKey string OpenAI API key Optional
anthropicKey string Anthropic API key Optional
implementationConfig Record<AIProvider, any> Provider-specific configuration Optional

Components

AiTesterComponent

A component for testing AI provider connections and functionality.

import { AiTesterComponent } from '@gograb-ai';

@Component({
  selector: 'app-ai-settings',
  standalone: true,
  imports: [AiTesterComponent],
  template: `
    <h1>AI Settings</h1>
    <app-ai-tester></app-ai-tester>
  `
})
export class AiSettingsComponent {}

Error Handling

The library provides typed error handling for all AI providers.

aiService.complete(messages, options).subscribe({
  next: (response) => {
    // Handle successful response
    console.log(response.text);
  },
  error: (error) => {
    if (error.type === 'authentication_error') {
      console.error('Authentication failed. Check your API key.');
    } else if (error.type === 'rate_limit_error') {
      console.error('Rate limit exceeded. Try again later.');
    } else {
      console.error('An error occurred:', error.message);
    }
  }
});

Common Error Types

Error Type Description
authentication_error Invalid API key or authentication issue
permission_error Insufficient permissions for the operation
invalid_request_error Malformed request or invalid parameters
rate_limit_error API rate limit exceeded
server_error Internal server error from the AI provider
connection_error Cannot connect to the API or proxy