Skip to main content

Universal API Integration

Costa Code provides an OpenAI-compatible API that works with virtually any AI agent, custom application, or automation tool. This allows you to integrate enterprise-grade AI capabilities into your existing workflows while maintaining the highest security standards.

API Configuration

Base Configuration

export COSTA_API_KEY="REPLACE_WITH_YOUR_COSTA_API_KEY"
export COSTA_BASE_URL="https://ai.costa.app/api/v1"
export COSTA_MODEL="costa/auto"

Integration Examples

Python SDK Integration

import openai

# Configure Costa Code as OpenAI provider
client = openai.OpenAI(
    api_key="costa_ent_your_key_here",
    base_url="https://ai.costa.app/api/v1"
)

# Basic chat completion
response = client.chat.completions.create(
    model="costa/enterprise-coder-v1",
    messages=[
        {"role": "user", "content": "Write a secure Python function for user authentication"}
    ],
    max_tokens=1000,
    temperature=0.7
)

print(response.choices[0].message.content)

# With enterprise security headers
response = client.chat.completions.create(
    model="costa/secure-claude-3-5-sonnet",
    messages=[
        {"role": "user", "content": "Review this code for security vulnerabilities"}
    ],
    extra_headers={
        "Costa-Security-Level": "maximum",
        "Costa-Data-Residency": "us-east",
        "Costa-Audit-Enabled": "true",
        "Costa-Zero-Retention": "true"
    }
)

JavaScript/Node.js Integration

import OpenAI from 'openai';

// Configure Costa Code client
const openai = new OpenAI({
  apiKey: 'costa_ent_your_key_here',
  baseURL: 'https://ai.costa.app/api/v1'
});

// Basic completion
async function generateCode(prompt) {
  const completion = await openai.chat.completions.create({
    model: 'costa/enterprise-coder-v1',
    messages: [{ role: 'user', content: prompt }],
    max_tokens: 1000,
    temperature: 0.7
  });
  
  return completion.choices[0].message.content;
}

// Enterprise security completion
async function secureGeneration(prompt, securityLevel = 'high') {
  const completion = await openai.chat.completions.create({
    model: 'costa/secure-claude-3-5-sonnet',
    messages: [{ role: 'user', content: prompt }],
    max_tokens: 1500,
    extra_headers: {
      'Costa-Security-Level': securityLevel,
      'Costa-Audit-Enabled': 'true',
      'Costa-Data-Residency': 'us-east'
    }
  });
  
  return completion.choices[0].message.content;
}

// Usage
const code = await generateCode('Create a REST API for user management');
const secureCode = await secureGeneration('Review this payment processing code', 'maximum');

cURL Examples

curl -X POST "https://ai.costa.app/api/v1/chat/completions" \
  -H "Authorization: Bearer costa_ent_your_key_here" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "costa/enterprise-coder-v1",
    "messages": [
      {
        "role": "user",
        "content": "Write a secure authentication middleware for Express.js"
      }
    ],
    "max_tokens": 1000,
    "temperature": 0.7
  }'

AutoGPT Integration

ai_provider: custom
api_base: https://ai.costa.app/api/v1
api_key: costa_ent_your_key_here

models:
  fast_llm: costa/enterprise-coder-v1
  smart_llm: costa/secure-claude-3-5-sonnet
  
security:
  audit_enabled: true
  data_residency: us-east
  security_level: high

headers:
  Costa-Security-Level: high
  Costa-Audit-Enabled: "true"
  Costa-Data-Residency: us-east

LangChain Integration

from langchain.llms import OpenAI
from langchain.chat_models import ChatOpenAI
from langchain.schema import HumanMessage

# Configure Costa Code as LangChain provider
costa_llm = ChatOpenAI(
    openai_api_key="costa_ent_your_key_here",
    openai_api_base="https://ai.costa.app/api/v1",
    model_name="costa/enterprise-coder-v1",
    temperature=0.7
)

# Use with LangChain chains
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate

prompt = PromptTemplate(
    input_variables=["task"],
    template="Write secure, enterprise-grade code for: {task}"
)

chain = LLMChain(llm=costa_llm, prompt=prompt)
result = chain.run(task="user authentication system with MFA")

# Enterprise security configuration
costa_secure = ChatOpenAI(
    openai_api_key="costa_ent_your_key_here",
    openai_api_base="https://ai.costa.app/api/v1",
    model_name="costa/secure-claude-3-5-sonnet",
    model_kwargs={
        "extra_headers": {
            "Costa-Security-Level": "maximum",
            "Costa-Audit-Enabled": "true"
        }
    }
)

Custom AI Agent Template

import requests
import json
from typing import Dict, List, Optional

class EnterpriseAIAgent:
    def __init__(self, api_key: str, default_model: str = "costa/enterprise-coder-v1"):
        self.api_key = api_key
        self.base_url = "https://ai.costa.app/api/v1"
        self.default_model = default_model
        self.session = requests.Session()
        self.session.headers.update({
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        })
    
    def execute_task(
        self, 
        task: str, 
        model: Optional[str] = None,
        security_level: str = "high",
        compliance_frameworks: List[str] = None,
        **kwargs
    ) -> Dict:
        """Execute AI task with enterprise security"""
        
        headers = {
            "Costa-Security-Level": security_level,
            "Costa-Audit-Enabled": "true",
            "Costa-Data-Residency": kwargs.get("region", "us-east")
        }
        
        if kwargs.get("zero_retention", False):
            headers["Costa-Zero-Retention"] = "true"
        
        if compliance_frameworks:
            headers["Costa-Compliance-Frameworks"] = ",".join(compliance_frameworks)
        
        payload = {
            "model": model or self.default_model,
            "messages": [{"role": "user", "content": task}],
            "max_tokens": kwargs.get("max_tokens", 1000),
            "temperature": kwargs.get("temperature", 0.7)
        }
        
        response = self.session.post(
            f"{self.base_url}/chat/completions",
            headers=headers,
            json=payload
        )
        
        response.raise_for_status()
        return response.json()
    
    def code_review(self, code: str, framework: str = "general") -> Dict:
        """Perform security-focused code review"""
        
        model_map = {
            "hipaa": "costa/compliance-assistant",
            "sox": "costa/compliance-assistant", 
            "pci": "costa/compliance-assistant",
            "general": "costa/secure-claude-3-5-sonnet"
        }
        
        task = f"Perform a comprehensive security review of this code for {framework} compliance:\n\n{code}"
        
        return self.execute_task(
            task=task,
            model=model_map.get(framework, "costa/secure-claude-3-5-sonnet"),
            security_level="maximum",
            compliance_frameworks=[framework] if framework != "general" else [],
            zero_retention=True
        )
    
    def generate_code(self, requirements: str, language: str = "python") -> Dict:
        """Generate enterprise-grade code"""
        
        task = f"Generate secure, enterprise-grade {language} code for: {requirements}"
        
        return self.execute_task(
            task=task,
            model="costa/enterprise-coder-v1",
            security_level="high",
            max_tokens=2000
        )

# Usage example
agent = EnterpriseAIAgent("costa_ent_your_key_here")

# Generate secure code
code_result = agent.generate_code(
    "User authentication system with JWT and rate limiting",
    language="python"
)

# Review code for compliance
review_result = agent.code_review(
    code="def process_payment(card_data): ...",
    framework="pci"
)

print("Generated code:", code_result["choices"][0]["message"]["content"])
print("Security review:", review_result["choices"][0]["message"]["content"])

Enterprise Headers Reference

Header: Costa-Security-LevelValues:
  • standard - Default security measures
  • high - Enhanced security protocols
  • maximum - Highest security, compliance mode
Usage:
-H "Costa-Security-Level: maximum"
Header: Costa-Data-ResidencyValues:
  • us-east - US East Coast
  • us-west - US West Coast
  • eu-west - European Union
  • asia-pacific - Asia Pacific
Usage:
-H "Costa-Data-Residency: eu-west"
Header: Costa-Audit-EnabledValues: true, falseUsage:
-H "Costa-Audit-Enabled: true"
Header: Costa-Zero-RetentionValues: true, falseDescription: Enable zero data retention modeUsage:
-H "Costa-Zero-Retention: true"
Header: Costa-Compliance-FrameworksValues: Comma-separated list of hipaa, sox, pci-dss, gdprUsage:
-H "Costa-Compliance-Frameworks: hipaa,sox"

Error Handling

import requests
from requests.exceptions import RequestException

def safe_costa_request(api_key, model, messages, **kwargs):
    """Make a safe request to Costa Code API with error handling"""
    
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
        "Costa-Security-Level": kwargs.get("security_level", "high"),
        "Costa-Audit-Enabled": "true"
    }
    
    payload = {
        "model": model,
        "messages": messages,
        "max_tokens": kwargs.get("max_tokens", 1000),
        "temperature": kwargs.get("temperature", 0.7)
    }
    
    try:
        response = requests.post(
            "https://ai.costa.app/api/v1/chat/completions",
            headers=headers,
            json=payload,
            timeout=30
        )
        
        # Handle HTTP errors
        if response.status_code == 401:
            raise Exception("Invalid API key or authentication failed")
        elif response.status_code == 403:
            raise Exception("Access denied - check model permissions")
        elif response.status_code == 429:
            raise Exception("Rate limit exceeded - please retry later")
        elif response.status_code >= 500:
            raise Exception("Costa Code service error - please retry")
        
        response.raise_for_status()
        return response.json()
        
    except RequestException as e:
        raise Exception(f"Network error: {str(e)}")
    except Exception as e:
        raise Exception(f"API request failed: {str(e)}")

# Usage with error handling
try:
    result = safe_costa_request(
        api_key="costa_ent_your_key_here",
        model="costa/enterprise-coder-v1",
        messages=[{"role": "user", "content": "Generate secure code"}],
        security_level="high"
    )
    print("Success:", result["choices"][0]["message"]["content"])
    
except Exception as e:
    print("Error:", str(e))

Testing & Validation

import unittest
import requests

class CostaCodeAPITest(unittest.TestCase):
    
    def setUp(self):
        self.api_key = "costa_ent_your_test_key_here"
        self.base_url = "https://ai.costa.app/api/v1"
        self.headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }
    
    def test_basic_completion(self):
        """Test basic chat completion"""
        payload = {
            "model": "costa/enterprise-coder-v1",
            "messages": [{"role": "user", "content": "Hello, world!"}],
            "max_tokens": 50
        }
        
        response = requests.post(
            f"{self.base_url}/chat/completions",
            headers=self.headers,
            json=payload
        )
        
        self.assertEqual(response.status_code, 200)
        data = response.json()
        self.assertIn("choices", data)
        self.assertGreater(len(data["choices"]), 0)
    
    def test_security_headers(self):
        """Test enterprise security headers"""
        headers = {
            **self.headers,
            "Costa-Security-Level": "maximum",
            "Costa-Audit-Enabled": "true"
        }
        
        payload = {
            "model": "costa/secure-claude-3-5-sonnet",
            "messages": [{"role": "user", "content": "Test security"}],
            "max_tokens": 50
        }
        
        response = requests.post(
            f"{self.base_url}/chat/completions",
            headers=headers,
            json=payload
        )
        
        self.assertEqual(response.status_code, 200)
        data = response.json()
        self.assertIn("security", data)
    
    def test_model_availability(self):
        """Test available models"""
        response = requests.get(
            f"{self.base_url}/models",
            headers=self.headers
        )
        
        self.assertEqual(response.status_code, 200)
        data = response.json()
        model_ids = [model["id"] for model in data["data"]]
        self.assertIn("costa/enterprise-coder-v1", model_ids)

if __name__ == "__main__":
    unittest.main()

Best Practices

1

Authentication Security

  • Store API keys securely using environment variables
  • Rotate API keys regularly
  • Use different keys for development and production
2

Error Handling

  • Implement comprehensive error handling
  • Add retry logic for transient failures
  • Log errors for debugging and monitoring
3

Security Configuration

  • Use appropriate security levels for your use case
  • Enable audit logging for compliance requirements
  • Configure data residency based on regulations
4

Performance Optimization

  • Use streaming for real-time applications
  • Cache responses when appropriate
  • Monitor usage and optimize model selection

Enterprise Integration: When integrating Costa Code with AI agents, ensure proper security measures are implemented including secure API key storage, appropriate security levels, and compliance configuration for your industry requirements.