### Start AnotherAI Services Source: https://github.com/anotherai-dev/anotherai/blob/main/examples/quickstart/INSTRUCTIONS.md Starts all the services defined in the docker-compose.yml file. This command brings up the entire AnotherAI stack, making it accessible locally. ```bash docker-compose up ``` -------------------------------- ### Download Environment File Example Source: https://github.com/anotherai-dev/anotherai/blob/main/examples/quickstart/INSTRUCTIONS.md Downloads the .env.example file, which serves as a template for environment-specific configurations. Users should copy this to .env and populate it with their provider keys. ```bash curl -L "https://raw.githubusercontent.com/anotherai-dev/anotherai/refs/heads/main/.env.example" -o .env ``` -------------------------------- ### Self-Host AnotherAI with Claude Code Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/self-hosted.mdx Initiates the self-hosting setup for AnotherAI by instructing Claude Code to follow a specific markdown file. This is the recommended first step for self-hosting. ```bash claude "Please follow instructions in https://raw.githubusercontent.com/anotherai-dev/anotherai/refs/heads/main/examples/quickstart/INSTRUCTIONS.md" ``` -------------------------------- ### Start AnotherAI Services in Background Source: https://github.com/anotherai-dev/anotherai/blob/main/examples/quickstart/INSTRUCTIONS.md Starts all the services defined in the docker-compose.yml file in detached mode (background). This allows the services to run without keeping the terminal occupied. ```bash docker-compose up -d ``` -------------------------------- ### Create Directory and Navigate Source: https://github.com/anotherai-dev/anotherai/blob/main/examples/quickstart/INSTRUCTIONS.md Creates a new directory for the project and changes the current working directory into it. This is the initial setup step before downloading configuration files. ```bash mkdir anotherai && cd anotherai ``` -------------------------------- ### Add AnotherAI MCP Server via Claude Code CLI Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/self-hosted.mdx Installs AnotherAI as an MCP server using the Claude Code CLI. Supports user-scoped installation for personal use or project-scoped for team collaboration via a shared `.mcp.json` file. ```bash claude mcp add --scope user --transport http anotherai http://127.0.0.1:8000/mcp/ ``` -------------------------------- ### Setup AnotherAI CLI Environment Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/cli.private.mdx This snippet details the one-time setup required to prepare the environment for using the AnotherAI CLI tool. It involves creating a virtual environment, activating it, and installing necessary Python packages like openai and requests. ```bash python3 -m venv anotherai_env source anotherai_env/bin/activate pip install openai requests ``` -------------------------------- ### Add Claude to MCP Server Source: https://github.com/anotherai-dev/anotherai/blob/main/examples/quickstart/INSTRUCTIONS.md An example command to add the Claude provider to the MCP server using HTTP transport. It specifies the scope, transport protocol, and the server endpoint. ```bash claude mcp add --scope user --transport http anotherai http://localhost:8000/mcp/ ``` -------------------------------- ### Start Local AnotherAI Services with Docker Compose Source: https://github.com/anotherai-dev/anotherai/blob/main/CLAUDE.md Starts all AnotherAI services defined in the docker-compose file. It includes options to rebuild images if dependencies have changed. Use `--no-cache` to resolve potential build errors. Services will be accessible at http://localhost:8000 (API) and http://localhost:3000 (Web App). ```bash docker-compose up -d --build ``` -------------------------------- ### Setup and Run AnotherAI Development Environment Source: https://github.com/anotherai-dev/anotherai/blob/main/CONTRIBUTING.md Clones the AnotherAI repository, sets up environment variables, and starts the development stack using Docker Compose. This process includes building Docker images and ensures all necessary services are running locally. ```shell git clone https://github.com/anotherai-dev/anotherai.git cd anotherai cp .env.example .env docker-compose up --build -d ``` -------------------------------- ### Configure Clerk Authentication for AnotherAI Web Client Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/self-hosted.mdx Enables Clerk-based authentication for the AnotherAI web client by setting specific environment variables. These variables must be available at build time. ```bash NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY= CLERK_SECRET_KEY= ``` -------------------------------- ### Download Docker Compose Configuration Source: https://github.com/anotherai-dev/anotherai/blob/main/examples/quickstart/INSTRUCTIONS.md Downloads the docker-compose.yml file from the official GitHub repository. This file defines the services, networks, and volumes for the AnotherAI stack. ```bash curl -LO "https://raw.githubusercontent.com/anotherai-dev/anotherai/refs/heads/main/examples/quickstart/docker-compose.yml" ``` -------------------------------- ### Claude Code: Install AnotherAI MCP Server (Bash) Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/getting-started.mdx Commands to install AnotherAI as an MCP server in Claude Code via the command line. Supports both OAuth and API Key authentication. The OAuth method uses a simple add command, while API Key authentication requires specifying headers. ```bash claude mcp add --scope user --transport http anotherai {{API_URL}}/mcp ``` ```bash claude mcp add --scope user anotherai {{API_URL}}/mcp --transport http --header "Authorization: Bearer YOUR_API_KEY_HERE" ``` -------------------------------- ### Set Provider Keys for AnotherAI Self-Hosted Users Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/self-hosted.mdx Instructions for self-hosted users to configure AI provider credentials for AnotherAI via environment variables. These keys are mandatory for making requests to AI models. ```bash # Example: Setting OpenAI API key OPENAI_API_KEY=sk-... ``` -------------------------------- ### TypeScript Client Setup for WorkflowAI/AnotherAI Migration Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/use-cases/private.migrate-from-workflowai.mdx This snippet demonstrates the initial setup of a WorkflowAI client in TypeScript, which needs to be replaced with the AnotherAI client configuration. It defines input and output interfaces for an agent task and shows how to initialize an agent, highlighting the agent ID and deployment environment. ```typescript const workflowAI = new WorkflowAI({ key: process.env["WORKFLOWAI_API_KEY"], }); export interface AnalyzeBookCharactersTaskInput { book_title?: string; } export interface AnalyzeBookCharactersTaskOutput { characters?: { name?: string; goals?: string[]; weaknesses?: string[]; outcome?: string; }[]; } const analyzeBookCharacters: Agent< AnalyzeBookCharactersTaskInput, AnalyzeBookCharactersTaskOutput > = workflowAI.agent({ id: "analyze-book-characters", schemaId: 1, version: "production", }); ``` -------------------------------- ### AnotherAI CLI Metadata Examples Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/cli.private.mdx Provides examples of how to structure the metadata argument for the AnotherAI CLI. It covers simple key-value pairs, richer metadata with multiple fields including tags, and notes that metadata is optional. ```bash # Simple metadata --metadata '{"title": "Customer Support", "description": "Email analysis"}' # Rich metadata with multiple fields --metadata '{ "title": "Customer Support Analysis", "category": "support", "source": "zendesk", "experiment_id": "exp_001", "user_id": "analyst_123", "tags": "urgent,billing,complaint", "priority": "high", "version": "v2.1" }' # No metadata (optional) # Just use --content without --metadata ``` -------------------------------- ### Setup OpenAI Java SDK with AnotherAI Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/partials/openai-java-code.mdx This snippet shows how to configure the OpenAI Java SDK to connect to AnotherAI's compatible API endpoint. It requires setting the base URL to the AnotherAI API endpoint and using a valid API key. The example uses OkHttp as the underlying client. ```java import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.chat.completions.ChatCompletion; import com.openai.models.chat.completions.ChatCompletionCreateParams; public class AnotherAIExample { public static void main(String[] args) { // setup AnotherAI client OpenAIClient client = OpenAIOkHttpClient.builder() .baseUrl("{{API_URL}}/v1") // [!code highlight] .apiKey("aai-***") // use create_api_key MCP tool // [!code highlight] .build(); ChatCompletion chatCompletion = client.chat().completions().create( ChatCompletionCreateParams.builder() // your existing code .build() ); } } ``` -------------------------------- ### Configure Environment Variables for AnotherAI Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/self-hosted.mdx This snippet shows the necessary environment variables for API keys required by AnotherAI. Ensure these are set in your .env file before running the application. This configuration is crucial for the application to authenticate with external AI services. ```env OPENAI_API_KEY=sk-... ANTHROPIC_API_KEY=sk-ant-... GOOGLE_API_KEY=... ``` -------------------------------- ### Python Example: OpenAI Chat Completions with Tools Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/use-cases/tools.private.mdx This Python snippet demonstrates how to define tools for the OpenAI API's chat completions endpoint and make a request. It includes a sample 'get_weather' function definition and shows how to process the tool calls from the completion response. Ensure you have the OpenAI client library installed. ```python tools = [{ "type": "function", "function": { "name": "get_weather", "description": "Get current temperature for a given location.", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "City and country e.g. Bogotá, Colombia" } }, "required": [ "location" ], "additionalProperties": False }, "strict": True } }] completion = client.chat.completions.create( model="gpt-4.1", messages=[{"role": "user", "content": "What is the weather like in Paris today?"}], tools=tools ) print(completion.choices[0].message.tool_calls) ``` -------------------------------- ### Content Block Start - Tool Use Source: https://github.com/anotherai-dev/anotherai/blob/main/backend/tests/fixtures/anthropic/anthropic_stream_with_tools_1.txt Initiates a tool usage action. It includes a unique tool use ID and the name of the tool being invoked. The input field will be populated with tool arguments. ```json { "type": "content_block_start", "index": 1, "content_block": { "type": "tool_use", "id": "toolu_01D6dnPVG9x9nkvyMd24i6wc", "name": "perplexity-sonar-pro", "input": {} } } ``` -------------------------------- ### Go (OpenAI SDK) Integration Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/use-cases/private.migrate-from-workflowai.mdx Illustrates how to integrate with AnotherAI using the Go OpenAI SDK, including client setup and making calls to deployments. ```APIDOC ## Go (OpenAI SDK) Integration ### Description This section provides guidance on using AnotherAI with the Go OpenAI SDK. It includes setting up the client with the correct base URL and API key, defining input and output structures, and preparing parameters for a chat completion call to an AnotherAI deployment. ### Method POST ### Endpoint `{{API_URL}}/v1/chat/completions` ### Parameters #### Request Body - **Model** (string) - Required - The deployment ID in the format `anotherai/deployment/:`. Example: `anotherai/deployment/analyze-book-characters:production#1`. - **Messages** (array) - Required - Should be an empty array as the prompt is stored in AnotherAI. - **Metadata** (object) - Optional - User-provided metadata for the request. - **ResponseFormat** (object) - Optional - Specifies the format of the response, typically using JSON schema. - **Input** (object) - Required - The input parameters for the task, matching the expected input schema. ### Request Example ```go params := openai.ChatCompletionNewParams{ Model: "anotherai/deployment/analyze-book-characters:production#1", Messages: []openai.Message{}, // No need to pass messages Metadata: shared.Metadata{ //...any user provided metadata. }, ResponseFormat: openai.ChatCompletionNewParamsResponseFormatUnion{ OfJSONSchema: &openai.ResponseFormatJSONSchemaParam{ JSONSchema: openai.ResponseFormatJSONSchemaJSONSchemaParam{ // JSON schema for the expected output }, }, }, Input: input, // The input structure for the task } _, err := client.Chat.Completions(context.Background(), params) ``` ### Response #### Success Response (200) - The response structure will depend on the `ResponseFormat` specified and the output schema of the AnotherAI deployment. ``` -------------------------------- ### Query AnotherAI Completions API (Python) Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/use-cases/fundamentals/metrics.mdx Provides a Python example for interacting with the AnotherAI completions API. It utilizes the `requests` library to send a GET request with authentication headers and query parameters for data retrieval. ```python import requests url = "{{API_URL}}/v1/completions/query" headers = { "Authorization": "Bearer aai-your-api-key", "Content-Type": "application/json" } params = { "query": "SELECT * FROM completions WHERE agent_id = 'email-classifier' LIMIT 10" } response = requests.get(url, headers=headers, params=params) data = response.json() ``` -------------------------------- ### List Hosted Tools using cURL Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/use-cases/tools.private.mdx This command-line example shows how to retrieve a list of all available hosted tools by making a GET request to the '/v1/tools/hosted' endpoint. This endpoint does not require authentication and returns a JSON object containing information about the tools. It's useful for discovering available tools programmatically. ```bash curl -X GET "https://api.anotherai.com/v1/tools/hosted" \ -H "accept: application/json" \ ``` -------------------------------- ### Query AnotherAI Completions API (JavaScript) Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/use-cases/fundamentals/metrics.mdx Illustrates how to fetch data from the AnotherAI completions API using JavaScript. This example uses the `fetch` API to make a GET request, including the Authorization header and URL search parameters for the SQL query. ```javascript const url = new URL("{{API_URL}}/v1/completions/query"); url.searchParams.append("query", "SELECT * FROM completions WHERE agent_id = 'email-classifier' LIMIT 10"); const response = await fetch(url, { headers: { "Authorization": "Bearer aai-your-api-key", "Content-Type": "application/json" } }); const data = await response.json(); ``` -------------------------------- ### Setup OpenAI C# Client with AnotherAI Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/partials/openai-csharp-code.mdx This snippet shows how to initialize the OpenAIClient for C# using the AnotherAI endpoint and API key. It requires the OpenAI SDK and sets the custom endpoint for API communication. ```csharp using OpenAI; // setup AnotherAI client OpenAIClient client = new OpenAIClient( apiKey: "aai-***", // use create_api_key MCP tool // [!code highlight] new OpenAIClientOptions { Endpoint = new Uri("{{API_URL}}/v1") // [!code highlight] } ); ChatClient chatClient = client.GetChatClient("model-name"); ChatCompletion completion = chatClient.CompleteChat( // your existing code ); ``` -------------------------------- ### Content Block Start - Text Source: https://github.com/anotherai-dev/anotherai/blob/main/backend/tests/fixtures/anthropic/anthropic_stream_with_tools_1.txt Indicates the beginning of a text content block within a message. This is typically used for standard textual responses from the assistant. ```json { "type": "content_block_start", "index": 0, "content_block": { "type": "text", "text": "" } } ``` -------------------------------- ### Run Backend Tests with Pytest Source: https://github.com/anotherai-dev/anotherai/blob/main/CLAUDE.md Initiates the backend test suite using pytest. The `...` indicates that additional arguments or filters can be passed to pytest to target specific tests or configurations. ```bash uv run pytest backend ... ``` -------------------------------- ### Message Start Event - Assistant Response Source: https://github.com/anotherai-dev/anotherai/blob/main/backend/tests/fixtures/anthropic/anthropic_stream_with_tools_1.txt Represents the beginning of an assistant's message. It includes message metadata such as ID, type, role, model used, and initial content status. The usage object tracks token consumption. ```json { "type": "message_start", "message": { "id": "msg_0191evKqHTnjLERvonMoinoe", "type": "message", "role": "assistant", "model": "claude-3-5-sonnet-20241022", "content": [], "stop_reason": null, "stop_sequence": null, "usage": { "input_tokens": 716, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "output_tokens": 1 } } } ``` -------------------------------- ### JSON Configuration Example Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/use-cases/fundamentals/evaluating.mdx This snippet shows a configuration object for a dataset, specifying parameters like maximum word count and boolean flags for tracking links and notifications. It is part of a larger JSON structure for defining dataset properties. ```json { "max_word_count": 100, "provides_tracking_link": true, "mentions_notifications": true } } ] } ``` ``` -------------------------------- ### Setup AnotherAI Client with Instructor Python SDK Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/partials/instructor-python-code.mdx This snippet demonstrates how to initialize the OpenAI client with AnotherAI's base URL and API key, and then wrap it with the Instructor SDK using the recommended `OPENROUTER_STRUCTURED_OUTPUTS` mode for structured data generation. ```python import instructor from openai import OpenAI from pydantic import BaseModel # setup AnotherAI client anotherai_client = OpenAI( base_url="{{API_URL}}/v1", api_key="aai-***", ) client = instructor.from_openai(anotherai_client, mode=instructor.Mode.OPENROUTER_STRUCTURED_OUTPUTS, ... ) ``` -------------------------------- ### Configure Authentication for AnotherAI Backend Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/self-hosted.mdx Details environment variables for configuring authentication in the AnotherAI backend. It supports disabling authentication or validating JWT tokens using JWKS_URL or JWK. ```bash # Disable authentication NO_AUTHORIZATION_ALLOWED=true # Or, configure JWT validation # JWKS_URL= # JWK='{"kty":"RSA","kid":"...","use":"sig","n":"...","e":"..."}' ``` -------------------------------- ### Go: Call AnotherAI Deployment using OpenAI SDK Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/use-cases/private.migrate-from-workflowai.mdx This Go snippet shows how to initialize the AnotherAI client using the OpenAI SDK. It outlines the setup for the base URL and API key, defines input and output structures, and demonstrates how to generate a JSON schema for the output. The code prepares parameters for a chat completion call, specifying the deployment ID as the model. ```go import ( "context" // Make sure to use the v2 "github.com/openai/openai-go/v2" "github.com/openai/openai-go/v2/option" "github.com/openai/openai-go/v2/shared" "github.com/invopop/jsonschema" // library to generate JSON schemas if needed ) // setup AnotherAI client var client = openai.NewClient( option.WithBaseURL("{{API_URL}}/v1"), option.WithAPIKey(os.Getenv("ANOTHERAI_API_KEY")), ) // types are likely already present in the users' code type AnalyzeBookCharactersTaskInput struct { BookTitle string `json:"book_title"` } type AnalyzeBookCharactersTaskOutput struct { Characters []struct { Name string `json:"name"` Goals []string `json:"goals"` Weaknesses []string `json:"weaknesses"` Outcome string `json:"outcome"` } `json:"characters"` } // Generate the JSON schema for the output var AnalyzeBookCharactersTaskOutput = jsonschema.Reflect(&AnalyzeBookCharactersTaskOutput{}) func AnalyzeBookCharacters(input AnalyzeBookCharactersTaskInput) (AnalyzeBookCharactersTaskOutput, error) { params := openai.ChatCompletionNewParams{ // Pass a plain string here Model: "anotherai/deployment/analyze-book-characters:production#1", // No need to pass messages Metadata: shared.Metadata{ //...any user provided metadata. No need to pass agent_id here since it will be passed by the deployment }, ResponseFormat: openai.ChatCompletionNewParamsResponseFormatUnion{ OfJSONSchema: &openai.ResponseFormatJSONSchemaParam{ JSONSchema: openai.ResponseFormatJSONSchemaJSONSchemaParam{ ``` -------------------------------- ### Clean Up Local AnotherAI Docker Environment Source: https://github.com/anotherai-dev/anotherai/blob/main/CLAUDE.md Stops and removes all containers, networks, and images associated with the AnotherAI Docker Compose setup. Exercise caution as this action will delete all associated data. ```bash docker-compose down ``` -------------------------------- ### Improve Agent Prompt and Create Experiment using ChatGPT Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/use-cases/for-product-managers.mdx This snippet demonstrates how to instruct ChatGPT to refine an agent's prompt and set up an experiment to compare the original prompt against the improved one. It requires specifying the agent, the desired improvement, and the input data source for the experiment. The output includes an improved prompt, an experiment configuration, and a URL to view the experiment results. ```text Help me improve anotherai/agent/article-summarizer. It is producing summaries that are too long. I want the summaries to be under 100 words. Create an improved prompt and create an experiment that compares the current prompt with the improved prompt, using inputs from the last 10 production completions. ``` -------------------------------- ### Claude Code: Verify MCP Server Connection (Bash) Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/getting-started.mdx Bash commands to list and verify the connection status of installed MCP servers in Claude Code. This helps confirm that AnotherAI has been successfully added and is connected. ```bash claude mcp list ``` ```bash claude /mcp ``` -------------------------------- ### Initialize OpenAI Client for AnotherAI (Go) Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/foundations.mdx Initializes an OpenAI client in Go for interacting with the AnotherAI API. Set the base URL and API key using `option.WithBaseURL` and `option.WithAPIKey` respectively. This facilitates the use of the OpenAI Go SDK with AnotherAI. ```Go import ( "github.com/openai/openai-go/v2" "github.com/openai/openai-go/v2/option" ) var client = openai.NewClient( option.WithBaseURL("{{API_URL}}/v1"), option.WithAPIKey("aai-***"), ) ``` -------------------------------- ### Cursor IDE: Configure AnotherAI MCP Server (JSON) Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/getting-started.mdx Configuration for setting up AnotherAI as an MCP server in the Cursor IDE using JSON. Supports both OAuth and API Key authentication methods. Requires specifying the server URL and optionally an Authorization header. ```json { "mcpServers": { "AnotherAI": { "url": "{{API_URL}}/mcp" } } } ``` ```json { "mcpServers": { "anotherai": { "url": "{{API_URL}}/mcp", "headers": { "Authorization": "Bearer " } } } } ``` -------------------------------- ### Accessing Cost and Latency (JavaScript OpenAI SDK) Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/features/cost.mdx Illustrates how to get cost_usd and duration_seconds from the completion object using the OpenAI JavaScript SDK with AnotherAI. The API key and base URL must be set correctly. The example shows basic output logging. ```javascript import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'YOUR_ANOTHERAI_API_KEY', baseURL: '{{API_URL}}/v1', }); const completion = await client.chat.completions.create({ model: 'gpt-4o-mini', messages: [{ role: 'user', content: 'Hello!' }], metadata: { agent_id: 'my-agent' } }); // Access cost and latency from the first choice const cost = completion.choices[0].cost_usd; const latency = completion.choices[0].duration_seconds; console.log(`Cost: $${cost.toFixed(6)}`); console.log(`Latency: ${latency.toFixed(2)}s`); ``` -------------------------------- ### Configure AnotherAI MCP Server for Windsurf (JSON) Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/getting-started.mdx This JSON configuration snippet is used to add the AnotherAI MCP server to Windsurf. It specifies the server URL and requires an authorization header with your API key. Ensure you replace '' with your actual API key. ```json { "mcpServers": { "anotherai": { "url": "{{API_URL}}/mcp", "headers": { "Authorization": "Bearer " } } } } ``` -------------------------------- ### Configure OpenAI Go SDK Client for AnotherAI Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/partials/openai-go-code.mdx Sets up the OpenAI Go SDK client to connect to AnotherAI's compatible API endpoint. It requires specifying the base URL of the AnotherAI service and an API key obtained from AnotherAI's tools. Ensure the v2 of the SDK is used. The client is initialized globally for use throughout the application. ```go package main import ( "context" // Make sure to use the v2 "github.com/openai/openai-go/v2" "github.com/openai/openai-go/v2/option" "github.com/openai/openai-go/v2/shared" "github.com/invopop/jsonschema" // library to generate JSON schemas ) // setup AnotherAI client var client = openai.NewClient( option.WithBaseURL("{{API_URL}}/v1"), // [!code highlight] option.WithAPIKey("aai-***"), // use create_api_key MCP tool, should be stored in an environment variable ANOTHERAI_API_KEY // [!code highlight] ) ``` -------------------------------- ### Python Pydantic Model with Descriptions and Examples Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/features/structured-outputs.mdx Defines a Pydantic BaseModel for a CalendarEvent, using `Field` to provide descriptions and examples for each attribute. This helps LLMs understand the expected data format and content for structured output. ```python from typing import Optional, List from pydantic import BaseModel, Field class CalendarEvent(BaseModel): title: Optional[str] = Field( None, description="The event title/name", examples=["Team Meeting", "Quarterly Review"] ) date: Optional[str] = Field( None, description="Date in YYYY-MM-DD format", examples=["2023-05-21", "2023-06-15"] ) start_time: Optional[str] = Field( None, description="Start time in 24-hour format", examples=["14:00", "09:30"] ) ... ``` -------------------------------- ### Initialize AnotherAI Client and Configure SDK Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/partials/openai-agents-sdk-python.md This snippet demonstrates how to initialize the AsyncOpenAI client for AnotherAI and configure the OpenAI Agents SDK to use AnotherAI's services. It sets the base URL, API key, and specifies that only the Chat Completions API is supported. Tracing is also disabled. ```python from openai import AsyncOpenAI from agents import ( Agent, Runner, set_default_openai_client, set_default_openai_api, set_tracing_disabled, ) from agents import ModelSettings, RunConfig from pydantic import BaseModel anotherai_client = AsyncOpenAI( base_url="{{API_URL}}/v1/", # keep the trailing slash – the SDK expects it. api_key="aai-***" # use create_api_key MCP tool ) # Make every model call go through AnotherAI set_default_openai_client(anotherai_client) # AnotherAI currently only supports the Chat Completions API set_default_openai_api("chat_completions") # tracing must be disabled set_tracing_disabled(True) ``` -------------------------------- ### Chat Completion Chunk with Tool Call (JSON) Source: https://github.com/anotherai-dev/anotherai/blob/main/backend/tests/fixtures/mistralai/stream_completion_with_tools_1.txt This example demonstrates a chat completion chunk where the API has identified a need to use a tool. The 'delta' object contains a 'tool_calls' array, specifying the tool's name ('perplexity-sonar-pro') and its arguments, which is a JSON string representing the query. ```json data: {"id":"6049a2c718be44ca84bdf2653ae9f124","object":"chat.completion.chunk","created":1740146430,"model":"mistral-large-2411","choices":[{"index":0,"delta":{"tool_calls":[{"id":"qWvpC7maA","function":{"name":"perplexity-sonar-pro","arguments":"{\"query\": \"What is the score of the latest Jazz - Lakers game of Feb 12th, 2025\"}"}},{"index":0}]}},{"finish_reason":"tool_calls"}]},"usage":{"prompt_tokens":420,"total_tokens":469,"completion_tokens":49}} ``` -------------------------------- ### Compare Specific Model Completions - AnotherAI CLI Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/use-cases/fundamentals/experiments.mdx This command requests AnotherAI to re-run the last 5 completions for the 'anotherai/agent/email-rewriter' agent and compare the outputs against 'GPT 5 mini'. It's useful for direct A/B testing of specific models with existing production data. ```text Can you retry the last 5 completions of anotherai/agent/email-rewriter and compare the outputs with GPT 5 mini? ``` -------------------------------- ### Chat Completion Chunk Example (JSON) Source: https://github.com/anotherai-dev/anotherai/blob/main/backend/tests/fixtures/mistralai/stream_completion_with_tools_1.txt This snippet shows a typical chunk of data received during a chat completion request. It includes metadata like ID, object type, creation timestamp, and the model used. The 'choices' array contains the actual content, which can be an empty string at intermediate steps. ```json data: {"id":"6049a2c718be44ca84bdf2653ae9f124","object":"chat.completion.chunk","created":1740146430,"model":"mistral-large-2411","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]} ``` -------------------------------- ### Create a Plain Agent with OpenAI Go SDK Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/partials/openai-go-code.mdx Demonstrates how to create a basic chat completion request using the configured OpenAI Go SDK client. This function sends a simple user message and prints the cost and duration from the response's extra fields. It utilizes the `Chat.Completions.New` method with a `context.Context` and parameters including the model and messages. ```go func MyPlainAgent() { chatCompletion, err := client.Chat.Completions.New( context.TODO(), openai.ChatCompletionNewParams{ Model: "gpt-4o-mini", Messages: []openai.ChatCompletionMessage{ { Role: "user", Content: "Hello, how are you?", }, }, Metadata: shared.Metadata{ "agent_id": "my-plain-agent", }, }, ) // handle err if needed // Cost and latency are available in the response as extra JSON fields on the choice object // the Raw() method returns the raw JSON string that can be parsed as a float if needed fmt.Printf("Cost USD: %s", chatCompletion.choices[0].JSON.ExtraFields["cost_usd"].Raw()) fmt.Printf("Duration Seconds: %s", chatCompletion.choices[0].JSON.ExtraFields["duration_seconds"].Raw()) } ``` -------------------------------- ### Identifying WorkflowAI Deployments via API Call Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/use-cases/private.migrate-from-workflowai.mdx This example shows how to identify WorkflowAI deployments when making direct API calls. A `POST` request to `{{API_URL}}/v1/chat/completions` with a model name formatted as `travel-assistant/#1/production` indicates the use of a deployment. Calls without this format, like specifying `gpt-4o`, do not use deployments. ```sh Uses deployments: ```sh POST {{API_URL}}/v1/chat/completions Authorization: Bearer aai-*** Content-Type: application/json { "model": "travel-assistant/#1/production", # messages are optional here ... } ``` Does not use deployments, calls a model directly ```sh POST {{API_URL}}/v1/chat/completions Authorization: Bearer aai-*** Content-Type: application/json { "model": "gpt-4o", # messages are required here ... } ``` ``` -------------------------------- ### Switching Models Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/features/models.mdx To use a specific model, simply change the 'model' parameter in your API call. Examples are provided for Python, JavaScript, and curl. ```APIDOC ## Switching between models To use a specific model, simply change the `model` parameter in your API call. ### Request Example (Python) ```python import openai client = openai.OpenAI( api_key="YOUR_ANOTHERAI_API_KEY", base_url="{{API_URL}}/v1" ) # Using GPT-4 response = client.chat.completions.create( model="gpt-4o", messages=[{"role": "user", "content": "Hello!"}], metadata={"agent_id": "my-agent"} ) # Switching to Claude response = client.chat.completions.create( model="claude-3-7-sonnet-latest", messages=[{"role": "user", "content": "Hello!"}], metadata={"agent_id": "my-agent"} ) ``` ### Request Example (JavaScript) ```javascript import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'YOUR_ANOTHERAI_API_KEY', baseURL: '{{API_URL}}/v1', }); // Using GPT-4 let response = await client.chat.completions.create({ model: 'gpt-4o', messages: [{ role: 'user', content: 'Hello!' }], metadata: { agent_id: 'my-agent' } }); // Switching to Claude response = await client.chat.completions.create({ model: 'claude-3-7-sonnet-latest', messages: [{ role: 'user', content: 'Hello!' }], metadata: { agent_id: 'my-agent' } }); ``` ### Request Example (curl) ```bash # Using GPT-4 curl {{API_URL}}/v1/chat/completions \ -H "Authorization: Bearer YOUR_ANOTHERAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-4o", "messages": [{"role": "user", "content": "Hello!"}], "metadata": {"agent_id": "my-agent"} }' # Switching to Claude curl {{API_URL}}/v1/chat/completions \ -H "Authorization: Bearer YOUR_ANOTHERAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "claude-3-7-sonnet-latest", "messages": [{"role": "user", "content": "Hello!"}], "metadata": {"agent_id": "my-agent"} }' ``` ``` -------------------------------- ### Creating an Experiment with AnotherAI Tools Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/foundations.mdx Demonstrates the workflow for creating and managing AI experiments using AnotherAI's specialized tools. This involves creating experiments, adding inputs and versions, waiting for results, and documenting findings. These tools operate independently of the AnotherAI inference endpoint. ```python from anotherai.tools import create_experiment, add_inputs_to_experiment, add_versions_to_experiment, get_experiment, query_completions, add_experiment_result, get_annotations # 1. Create experiments experiment_id = create_experiment( name="My First Experiment", description="Testing different models and prompts for a summarization task." ) # 2. Add inputs add_inputs_to_experiment( experiment_id=experiment_id, inputs=[ {"text": "This is the first input.", "topic": "general"}, {"text": "Another piece of text for summarization.", "topic": "news"} ], # To re-use existing inputs, use the query parameter: # query="SELECT id FROM inputs WHERE topic = 'general'" ) # 3. Add versions add_versions_to_experiment( experiment_id=experiment_id, versions=[ {"model": "gpt-4o-mini", "prompt": "Summarize this text: {{text}}", "temperature": 0.7}, {"model": "claude-3-5-sonnet-20241022", "prompt": "Provide a concise summary: {{text}}", "temperature": 0.5} ], # To start with an existing version as a baseline: # version="existing_version_id" ) # 4. Wait for the results (returns a query to fetch results) completion_query = get_experiment(experiment_id=experiment_id, include_versions=True, include_inputs=True) print(f"Use this query to fetch results: {completion_query}") # 5. Get the results (using query_completions tool - example assumes completion_query is executed elsewhere) # results = query_completions(query=completion_query) # print(results) # 6. Add results/conclusions add_experiment_result( experiment_id=experiment_id, performance_metrics={'speed': 'fast', 'cost': '$0.05'}, key_findings="Model A performed better on general topics, Model B on news.", recommendations="Use Model A for general summarization." ) # 8. Check for user feedback # annotations = get_annotations(experiment_id=experiment_id) # print(annotations) # 9. Iterate (example: add a new version) # add_versions_to_experiment( # experiment_id=experiment_id, # versions=[ # {"model": "gpt-4o", "prompt": "Summarize briefly: {{text}}", "temperature": 0.6} # ] # ) # Provide experiment URL for user review WEB_APP_URL = "https://app.anotherai.com" # Replace with actual URL if different print(f"Experiment URL: {WEB_APP_URL}/experiments/{experiment_id}") ``` -------------------------------- ### Review Annotations and Update Prompt (CLI) Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/use-cases/fundamentals/building.mdx This command instructs the AI assistant to review annotations made in a specific AnotherAI experiment and update the agent's prompt based on the identified issues. It requires the experiment URL as an argument. ```bash Review the annotations I added in anotherai/experiment/01997ccb-643a-72e2-8dbd-accfb903f42b and update the prompt to address the issues I identified. ``` -------------------------------- ### Create Agent Experiment with Prompt Variation - AnotherAI CLI Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/use-cases/fundamentals/experiments.mdx This command initiates an experiment in AnotherAI to compare the current prompt of the 'anotherai/agent/email-rewriter' with a new prompt that emphasizes tone lists from the input. It's useful for fine-tuning agent responses by testing different prompt strategies. ```text Look at the prompt of anotherai/agent/email-rewriter and create an experiment in AnotherAI that compares the current prompt with a new prompt that better emphasizes adopting tone lists in the input ``` -------------------------------- ### POST /v1/chat/completions - HTTP Servers Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/use-cases/mcp.private.mdx Example of using the chat completions endpoint with streamable HTTP MCP servers configured via `extra_body.mcp_servers`. ```APIDOC ## POST /v1/chat/completions (HTTP MCP Servers) ### Description This example shows how to integrate streamable HTTP based MCP servers for chat completions. These servers are configured within the `extra_body.mcp_servers` parameter, suitable for high-performance data processing scenarios. ### Method POST ### Endpoint `https://run.anotherai.com/v1/chat/completions` ### Parameters #### Request Body - **model** (string) - Required - The model to use for generating completions. - **messages** (array) - Required - An array of message objects representing the conversation history. - **role** (string) - Required - The role of the author of the message (e.g., 'user', 'assistant'). - **content** (string) - Required - The content of the message. - **metadata** (object) - Optional - Additional metadata for the request, such as an agent ID. - **agent_id** (string) - Optional - The ID of the agent to use. - **extra_body** (object) - Optional - Additional parameters for extended functionality. - **mcp_servers** (array) - Required - A list of MCP servers to integrate. - **type** (string) - Required - Must be 'http' for streamable HTTP servers. - **name** (string) - Required - A unique name for the MCP server (e.g., 'analytics'). - **url** (string) - Required - The base URL of the HTTP MCP server. - **headers** (object) - Optional - Custom headers to be sent with HTTP requests to the server. - **Authorization** (string) - Example header for authentication. ### Request Example ```python # Note: This is a Python SDK example, not a direct curl command # The equivalent curl would involve constructing the JSON payload as shown in the previous examples. client.chat.completions.create( model="gemini-2.5-pro-preview", messages=[{"role": "user", "content": "Analyze sales data from Q4"}], metadata={"agent_id": "data-analyst"}, extra_body={ "mcp_servers": [{ "type": "http", "name": "analytics", "url": "https://api.example.com/mcp", "headers": {"Authorization": "Bearer token"} }] } ) ``` ### Response #### Success Response (200) - **id** (string) - Unique identifier for the response. - **object** (string) - Type of the object (e.g., 'chat.completion'). - **created** (integer) - Timestamp of creation. - **model** (string) - The model used for the response. - **choices** (array) - An array of completion choices. - **index** (integer) - Index of the choice. - **message** (object) - The generated message. - **role** (string) - The role of the assistant. - **content** (string) - The content of the assistant's message. - **finish_reason** (string) - The reason the model stopped generating. - **usage** (object) - Usage statistics for the request. - **prompt_tokens** (integer) - Number of tokens in the prompt. - **completion_tokens** (integer) - Number of tokens in the completion. - **total_tokens** (integer) - Total tokens used. #### Response Example (Response structure is similar to other chat completions, with content reflecting the analysis from the HTTP server.) ```json { "id": "chatcmpl-789", "object": "chat.completion", "created": 1677652290, "model": "gemini-2.5-pro-preview", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "The Q4 sales data analysis is complete. Key trends indicate a 15% increase in online sales." }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 70, "completion_tokens": 35, "total_tokens": 105 } } ``` ``` -------------------------------- ### End of Stream Marker (Text) Source: https://github.com/anotherai-dev/anotherai/blob/main/backend/tests/fixtures/mistralai/stream_completion_with_tools_1.txt This indicates the end of the streaming response from the API. It is a simple text marker signifying that no more data will be sent for the current request. ```text data: [DONE] ``` -------------------------------- ### Configure OpenAI Ruby SDK with AnotherAI Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/partials/openai-ruby-code.mdx This snippet shows how to initialize the OpenAI Ruby client to communicate with AnotherAI's compatible API. It requires setting the `api_base` to the provided API URL and using a valid `access_token`. The `require 'openai'` statement is necessary to use the SDK. ```ruby require "openai" # setup AnotherAI client client = OpenAI::Client.new( api_base: "{{API_URL}}/v1", access_token: "aai-***" # use create_api_key MCP tool ) response = client.chat.completions.create( # your existing code ) ``` -------------------------------- ### Initialize OpenAI Client for AnotherAI (Python) Source: https://github.com/anotherai-dev/anotherai/blob/main/docs/content/docs/foundations.mdx Initializes an OpenAI client compatible with AnotherAI's API. This involves setting the base URL to the AnotherAI endpoint and providing an API key. This allows using existing OpenAI SDKs with AnotherAI. ```Python import openai client = openai.OpenAI( base_url="{{API_URL}}/v1", api_key="aai-***", ) ```