Skip to main content

Overview

AnyAPI is compatible with OpenAI SDKs, allowing you to seamlessly integrate our API into your applications using familiar tools and libraries. Simply configure the SDK to point to https://api.anyapi.ai and use your AnyAPI key for authentication.

Python

Install the official OpenAI Python library:
pip install openai

Example Usage

from openai import OpenAI

# Initialize the client with AnyAPI endpoint
client = OpenAI(
    api_key="your_anyapi_key_here",
    base_url="https://api.anyapi.ai/v1"
)

# Create a chat completion
completion = client.chat.completions.create(
    model="model_name",
    messages=[
        {"role": "user", "content": "Hi, can you help me?"}
    ]
)

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

Async Support

import asyncio
from openai import AsyncOpenAI

async def main():
    client = AsyncOpenAI(
        api_key="your_anyapi_key_here",
        base_url="https://api.anyapi.ai/v1"
    )
    
    completion = await client.chat.completions.create(
        model="model_name",
        messages=[
            {"role": "user", "content": "Hi, can you help me?"}
        ]
    )
    
    print(completion.choices[0].message.content)

asyncio.run(main())

Node.js TypeScript

Install the official OpenAI Node.js library:
npm install openai

Example Usage (TypeScript)

import OpenAI from 'openai';
import type { ChatCompletion } from 'openai/resources';

const client = new OpenAI({
  apiKey: 'your_anyapi_key_here',
  baseURL: 'https://api.anyapi.ai/v1',
});

async function main(): Promise<void> {
  const completion: ChatCompletion = await client.chat.completions.create({
    model: 'model_name',
    messages: [
      { role: 'user', content: 'Hi, can you help me?' }
    ],
  });

  console.log(completion.choices[0].message.content);
}

main();

Example Usage (JavaScript)

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'your_anyapi_key_here',
  baseURL: 'https://api.anyapi.ai/v1',
});

async function main() {
  const completion = await client.chat.completions.create({
    model: 'model_name',
    messages: [
      { role: 'user', content: 'Hi, can you help me?' }
    ],
  });

  console.log(completion.choices[0].message.content);
}

main();

C# .NET

Install the official OpenAI .NET library:
dotnet add package OpenAI

Example Usage

using System;
using System.ClientModel;
using OpenAI;
using OpenAI.Chat;

namespace ConsoleApp;

class Program
{
    static async Task Main()
    {
        var client = new OpenAIClient(
            new ApiKeyCredential("your_anyapi_key_here"),
            new OpenAIClientOptions
            {
                Endpoint = new Uri("https://api.anyapi.ai/v1")
            }
        );

        var chatClient = client.GetChatClient("model_name");

        var completion = await chatClient.CompleteChatAsync("Hi, can you help me?");

        Console.WriteLine($"[ASSISTANT]: {completion.Value.Content[0].Text}");
    }
}

Java

Install a community OpenAI Java library. Here’s an example using the popular openai-java library:
<dependency>
    <groupId>com.theokanning.openai-gpt3-java</groupId>
    <artifactId>service</artifactId>
    <version>0.18.2</version>
</dependency>

Example Usage

import com.theokanning.openai.OpenAiApi;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.service.OpenAiService;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;

import java.time.Duration;
import java.util.List;

public class AnyAPIExample {
    public static void main(String[] args) {
        String apiKey = "your_anyapi_key_here";
        String baseUrl = "https://api.anyapi.ai/";
        
        OkHttpClient client = new OkHttpClient.Builder()
                .readTimeout(Duration.ofMinutes(2))
                .build();
        
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(client)
                .build();
        
        OpenAiApi api = retrofit.create(OpenAiApi.class);
        OpenAiService service = new OpenAiService(api);
        
        ChatCompletionRequest request = ChatCompletionRequest.builder()
                .model("model_name")
                .messages(List.of(
                    new ChatMessage("user", "Hi, can you help me?")
                ))
                .build();
        
        service.createChatCompletion(request)
                .getChoices()
                .forEach(choice -> {
                    System.out.println(choice.getMessage().getContent());
                });
    }
}

Go

Install a community OpenAI Go library:
go get github.com/sashabaranov/go-openai

Example Usage

package main

import (
    "context"
    "fmt"
    "log"

    openai "github.com/sashabaranov/go-openai"
)

func main() {
    config := openai.DefaultConfig("your_anyapi_key_here")
    config.BaseURL = "https://api.anyapi.ai/v1"
    
    client := openai.NewClientWithConfig(config)
    
    resp, err := client.CreateChatCompletion(
        context.Background(),
        openai.ChatCompletionRequest{
            Model: "model_name",
            Messages: []openai.ChatCompletionMessage{
                {
                    Role:    openai.ChatMessageRoleUser,
                    Content: "Hi, can you help me?",
                },
            },
        },
    )
    
    if err != nil {
        log.Fatalf("ChatCompletion error: %v", err)
    }
    
    fmt.Println(resp.Choices[0].Message.Content)
}

Ruby

Install a community OpenAI Ruby library:
gem install ruby-openai

Example Usage

require 'openai'

client = OpenAI::Client.new(
  access_token: 'your_anyapi_key_here',
  uri_base: 'https://api.anyapi.ai/v1'
)

response = client.chat(
  parameters: {
    model: 'model_name',
    messages: [
      { role: 'user', content: 'Hi, can you help me?' }
    ]
  }
)

puts response.dig('choices', 0, 'message', 'content')

PHP

Install a community OpenAI PHP library:
composer require openai-php/client

Example Usage

<?php

require 'vendor/autoload.php';

use OpenAI;

$client = OpenAI::factory()
    ->withApiKey('your_anyapi_key_here')
    ->withBaseUri('https://api.anyapi.ai/v1')
    ->make();

$response = $client->chat()->create([
    'model' => 'model_name',
    'messages' => [
        ['role' => 'user', 'content' => 'Hi, can you help me?'],
    ],
]);

echo $response->choices[0]->message->content;

Rust

Install a community OpenAI Rust library:
[dependencies]
async-openai = "0.17"
tokio = { version = "1", features = ["full"] }

Example Usage

use async_openai::{
    types::{ChatCompletionRequestMessage, CreateChatCompletionRequestArgs},
    Client, config::OpenAIConfig,
};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = OpenAIConfig::new()
        .with_api_key("your_anyapi_key_here")
        .with_api_base("https://api.anyapi.ai/v1");
    
    let client = Client::with_config(config);
    
    let request = CreateChatCompletionRequestArgs::default()
        .model("model_name")
        .messages(vec![
            ChatCompletionRequestMessage::User(
                "Hi, can you help me?".into()
            )
        ])
        .build()?;
    
    let response = client.chat().create(request).await?;
    
    println!("{}", response.choices[0].message.content.as_ref().unwrap());
    
    Ok(())
}

Additional Languages

Don’t see your preferred language? AnyAPI’s REST API is compatible with any HTTP client. You can also use any OpenAI-compatible library by configuring it to use https://api.anyapi.ai/v1 as the base URL.

REST API Reference

View the complete REST API documentation

Authentication

All requests to AnyAPI require authentication using your API key. Set your API key in the SDK configuration:
client = OpenAI(
api_key="your_anyapi_key_here",
base_url="https://api.anyapi.ai/v1"
)
Keep your API key secure and never expose it in client-side code or public repositories.

Getting Help