### System Prompt Example Source: https://docs.requesty.ai/api-reference/endpoint/messages-create Demonstrates how to include a system prompt to guide the AI's behavior. This example sets the model and max tokens. ```json { "model": "anthropic/claude-sonnet-4-20250514", "max_tokens": 1024, "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "Who won the world series in 2020?" } ] } ``` -------------------------------- ### Setting System Instructions Source: https://docs.requesty.ai/llms-full.txt Include system instructions using the `system` parameter to define the AI's behavior. This example shows a basic setup for a helpful assistant. ```json { "model": "anthropic/claude-sonnet-4-20250514", "max_tokens": 1024, "system": "You are a helpful assistant that always responds in a friendly, professional manner.", "messages": [ { "role": "user", "content": "Hello!" } ] } ``` -------------------------------- ### OpenClaw Onboarding Wizard Source: https://docs.requesty.ai/llms-full.txt Initiates the guided setup process for Requesty AI. Follow the prompts to select API compatibility, enter base URLs, API keys, and model IDs. ```bash openclaw onboard ``` -------------------------------- ### Python Example for Chat Completions Source: https://docs.requesty.ai/api-reference/endpoint/chat-completions-create This Python script demonstrates how to use the OpenAI client library to interact with the chat completions endpoint. Install the library using 'pip install openai'. ```python from openai import OpenAI client = OpenAI( # This is the default and can be omitted api_key="YOUR_API_KEY", ) chat_completion = client.chat.completions.create( model="gpt-4", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Who won the world series in 2020?"}, {"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."}, {"role": "user", "content": "Where was it played?"} ] ) print(chat_completion.choices[0].message.content) ``` -------------------------------- ### Chat Completions Create Example Source: https://docs.requesty.ai/api-reference/endpoint/chat-completions-create An example demonstrating how to call the `chat.completions.create` method with a specified model, messages, and other parameters, and how to print the content of the response. ```APIDOC ## POST /chat/completions ### Description Creates a chat completion request. This endpoint allows you to send a series of messages to a chat model and receive a model-generated response. ### Method POST ### Endpoint /chat/completions ### Parameters #### Request Body - **model** (string) - Required - The ID of the model to use for completion (e.g., "openai/gpt-4o-mini"). - **messages** (array) - Required - A list of message objects, where each object has a `role` (system, user, or assistant) and `content`. - **role** (string) - Required - The role of the author of the message (e.g., "system", "user"). - **content** (string) - Required - The content of the message. - **max_tokens** (integer) - Optional - The maximum number of tokens to generate in the completion. - **temperature** (number) - Optional - Controls randomness. Lower values make the output more focused and deterministic. ### Request Example ```json { "model": "openai/gpt-4o-mini", "messages": [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "What is an LLM gateway?"} ], "max_tokens": 1024, "temperature": 0.7 } ``` ### Response #### Success Response (200) - **choices** (array) - A list of completion choices. Each choice contains a `message` object. - **message** (object) - The generated message. - **content** (string) - The content of the message. #### Response Example ```json { "choices": [ { "message": { "content": "An LLM gateway is a system that acts as an intermediary between users or applications and one or more Large Language Models (LLMs)." } } ] } ``` ``` -------------------------------- ### Create Messages Example Source: https://docs.requesty.ai/api-reference/endpoint/messages-create This example demonstrates how to use the Anthropic SDK to send a message and print the response. ```APIDOC ## POST /v1/messages ### Description Sends a message to the Anthropic API and returns a response. ### Method POST ### Endpoint /v1/messages ### Request Body - **max_tokens** (integer) - Required - The maximum number of tokens to generate in the response. - **messages** (array) - Required - An array of message objects, where each object has a 'role' and 'content'. - **role** (string) - Required - The role of the message sender (e.g., "user", "assistant"). - **content** (string) - Required - The content of the message. ### Request Example ```json { "max_tokens": 1024, "messages": [ { "role": "user", "content": "Hello, Claude!" } ] } ``` ### Response #### Success Response (200) - **content** (string) - The content of the assistant's response. #### Response Example ```json { "content": "Hello! How can I help you today?" } ``` ``` -------------------------------- ### Install Requesty AI SDK Source: https://docs.requesty.ai/llms-full.txt Install the Requesty AI SDK package for your project using pnpm, npm, or yarn. ```bash # For pnpm pnpm add @requesty/ai-sdk # For npm npm install @requesty/ai-sdk # For yarn yarn add @requesty/ai-sdk ``` -------------------------------- ### Install Requesty LlamaIndex TS Adapter Source: https://docs.requesty.ai/llms-full.txt Install the adapter using your preferred package manager. ```bash # For pnpm pnpm add @requesty/llamaindex # For npm npm install @requesty/llamaindex # For yarn yarn add @requesty/llamaindex ``` -------------------------------- ### TypeScript Example for Chat Completions Source: https://docs.requesty.ai/api-reference/endpoint/chat-completions-create This TypeScript example shows how to call the chat completions API using the OpenAI Node.js library. Make sure to install it with 'npm install openai'. ```typescript import OpenAI from "openai"; const openai = new OpenAI({ apiKey: "YOUR_API_KEY", // This is the default and can be omitted }); async function main() { const completion = await openai.chat.completions.create({ model: "gpt-4", messages: [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Who won the world series in 2020?"}, {"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."}, {"role": "user", "content": "Where was it played?"} ], }); console.log(completion.choices[0].message.content); } main(); ``` -------------------------------- ### Initialize Requesty Client Source: https://docs.requesty.ai/api-reference/endpoint/messages-create Set up the Requesty client with your API key and base URL. Ensure you have the `REQUESTY_API_KEY` environment variable set. ```javascript import Requesty from "requesty-api"; const client = new Requesty({ apiKey: process.env.REQUESTY_API_KEY, baseURL: "https://router.requesty.ai" }); ``` -------------------------------- ### TypeScript: Create Message Source: https://docs.requesty.ai/api-reference/endpoint/messages-create Example of creating a message using the Anthropic SDK in TypeScript. Ensure you have the SDK installed and your API key configured in environment variables. ```typescript import Anthropic from "@anthropic-ai/sdk"; const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY, }); async function main() { const message = await client.messages.create({ model: "claude-3-opus-20240229", max_tokens: 1000, messages: [ { role: "user", content: "Hello, Claude!" } ] }); console.log(message.content[0].text); } ``` -------------------------------- ### Go MCP Client Library Example Source: https://docs.requesty.ai/llms-full.txt Use the Go MCP client library to connect to the Requesty MCP endpoint, list available tools, and execute a tool. ```go package main import ( "github.com/mcp/client-go" ) func main() { client := mcp.NewClient(&mcp.Config{ URL: "https://router.requesty.ai/v1/mcp", Headers: map[string]string{ "Authorization": "Bearer YOUR_REQUESTY_API_KEY", }, }) // List available tools tools, err := client.ListTools() if err != nil { log.Fatal(err) } // Execute a tool result, err := client.CallTool("linear_create_issue", map[string]interface{}{ "title": "New feature request", "description": "Detailed description here", "team_id": "your-team-id", }) } ``` -------------------------------- ### Basic Chat Completion Request (Node.js) Source: https://docs.requesty.ai/api-reference/endpoint/chat-completions-create A simple example demonstrating how to create a chat completion request using Node.js. Ensure you have the 'openai' package installed. ```javascript import OpenAI from "openai"; const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY, }); async function main() { const completion = await openai.chat.completions.create({ messages: [{ role: "user", content: "Hello world" }], model: "gpt-3.5-turbo", }); console.log(completion.choices[0].message); } main(); ``` -------------------------------- ### Create Chat Completion with Fallback Policy Source: https://docs.requesty.ai/features/fallback-policies Example of creating a chat completion using a specific model with fallback policies. Ensure the 'openai' library is installed. ```javascript response = client.chat.completions.create( model="policy/sonnet", messages=["role": "user", "content": "Hello!" ] ) ``` -------------------------------- ### Initialize Requesty.ai OpenAI Client Source: https://docs.requesty.ai/features/auto-caching Set up the Requesty.ai client with your API key and the base URL for the Requesty.ai router. This is necessary to direct your requests through the Requesty.ai service. ```python import openai client = openai.OpenAI( api_key="YOUR_REQUESTY_API_KEY", base_url="https://router.requesty.ai/v1", ) system_prompt = "YOUR ENTIRE KNOWLEDGEBASE" response = client.chat.completions.create( model="anthropic/claude-sonnet-4-5", messages=[ { "role": "system", "content": system_prompt } ] ) ``` -------------------------------- ### Enabling Auto Caching for Responses API Source: https://docs.requesty.ai/features/auto-caching This example shows how to enable auto-caching for the /v1/responses endpoint. It requires the same setup as chat completions, including the 'requesty.auto_cache' flag. ```python import openai client = openai.OpenAI( api_key="YOUR_REQUESTY_API_KEY", base_url="https://router.requesty.ai/v1", ) response = client.chat.completions.create( model="gpt-4", messages=[ {"role": "user", "content": "What is the capital of France?"} ], requesty={ "auto_cache": True } ) ``` -------------------------------- ### Python Example with Request Metadata Source: https://docs.requesty.ai/features/request-metadata This Python snippet demonstrates how to set up the Requesty API key and prepare for sending requests with metadata. Ensure your API key is securely loaded. ```python requesty_api_key = "YOUR_REQUESTY_API_KEY" # Safely load your API key ``` -------------------------------- ### Image Edits API - Python Example Source: https://docs.requesty.ai/features/image-generation Use this snippet to perform image edits using the API. Ensure you have the necessary libraries installed and your API key configured. ```python from openai import OpenAI client = OpenAI() image_response = client.images.edit( model="dall-e-2", image=open("path/to/your/image.png", "rb"), prompt="A cute baby sea otter wearing a beret", n=1, size="1024x1024" ) image_url = image_response.data[0].url print(image_url) ``` -------------------------------- ### Load Balancing Policy Configuration Example Source: https://docs.requesty.ai/features/load-balancing-policies This example demonstrates how to configure a load balancing policy with fallback. It shows how to distribute traffic between different fallback policies based on weights. ```json { "policy": { "name": "policy/openai-fallback", "weights": [ { "policy": "policy/openai-fallback", "weight": 50 }, { "policy": "policy/anthropic-fallback", "weight": 50 } ] } } ``` -------------------------------- ### Basic Python Streaming Setup Source: https://docs.requesty.ai/llms-full.txt Enable streaming by setting `stream=True` in your request. This Python snippet shows how to create a client and process the streaming response chunk by chunk. ```python client = openai.OpenAI( api_key="your_requesty_api_key", base_url="https://router.requesty.ai/v1", ) response = client.chat.completions.create( model="openai/gpt-4", messages=[{"role": "user", "content": "Write a poem about the stars."}], stream=True ) # Process streaming response for chunk in response: if chunk.choices[0].delta.content is not None: content = chunk.choices[0].delta.content print(content, end="", flush=True) ``` -------------------------------- ### Configure Auto-Caching with Anthropic Claude Source: https://docs.requesty.ai/features/auto-caching Example of configuring auto-caching for an Anthropic Claude model. This setup is useful for scenarios where you want to cache responses from specific LLM providers. ```javascript const cache = await requesty.cache.set( { model: \"anthropic/claude-sonnet-4-5\", }, { instructions: \"YOUR ENTIRE KNOWLEDGEBASE\", }, [ { role: \"user\", content: \"What is the capital of France?\", }, { role: \"assistant\", content: \"The capital of France is Paris.\", }, { role: \"user\", content: \"What is the capital of Spain?\", }, ] ); console.log(cache); ``` -------------------------------- ### Load Balancing Policy Configuration Example Source: https://docs.requesty.ai/features/load-balancing-policies This example demonstrates how to configure a load balancing policy with specific weights for different models. The total weights are normalized to 100%. ```json { "model": "anthropic/claude-sonnet-4-5", "weight": 50 }, { "model": "bedrock/claude-sonnet-4-5@eu-central-1", "weight": 50 } ``` -------------------------------- ### Load Balancing Policy Configuration Source: https://docs.requesty.ai/features/load-balancing-policies Example of a load balancing policy configuration that distributes traffic between two fallback policies. This setup enables both load balancing and automatic failover. ```json { "policy": "policy/openai-fallback", "weight": 50% } { "policy": "policy/anthropic-fallback", "weight": 50% } ``` -------------------------------- ### Python Agent SDK with Tools Source: https://docs.requesty.ai/llms-full.txt Illustrates setting up the Python Agent SDK with custom tools and making a query. The ANTHROPIC_BASE_URL is set programmatically, while ANTHROPIC_AUTH_TOKEN should be an environment variable. This example defines a 'greet' tool and uses it. ```python """Minimal agent using Claude Agent SDK.""" from claude_agent_sdk import ( ClaudeSDKClient, ClaudeAgentOptions, tool, create_sdk_mcp_server, AssistantMessage, TextBlock, ) os.environ["ANTHROPIC_BASE_URL"] = "https://router.requesty.ai" # ANTHROPIC_AUTH_TOKEN should be set as an environment variable async def main(): @tool("greet", "Greet a user", {"name": str}) async def greet_user(args): return { "content": [ {"type": "text", "text": f"Hello, {args['name']}!"} ] } server = create_sdk_mcp_server( name="my-tools", version="1.0.0", tools=[greet_user] ) options = ClaudeAgentOptions( mcp_servers={"tools": server}, allowed_tools=["mcp__tools__greet"] ) async with ClaudeSDKClient(options=options) as client: await client.query("Greet World") last_assistant_message = None async for msg in client.receive_response(): if isinstance(msg, AssistantMessage): last_assistant_message = msg if last_assistant_message: print(last_assistant_message.content[0].text) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Load Environment Variables and Initialize OpenAI Client Source: https://docs.requesty.ai/features/request-metadata This snippet demonstrates how to load environment variables, specifically the API key, and initialize the OpenAI client. It also shows how to set a custom base URL for the router. ```javascript _jsx(_components.span, { style: { color: "#CE9178", "--shiki-dark": "#CE9178" }, children: " 'dotenv'" }), _jsx(_components.span, { style: { color: "#D4D4D4", "--shiki-dark": "#D4D4D4" }, children: ";" })]) }), "\n", _jsx(_components.span, { className: "line" }), "\n", _jsx(_components.span, { className: "line", children: _jsx(_components.span, { style: { color: "#6A9955", "--shiki-dark": "#6A9955" }, children: "// Load environment variables" }) }), "\n", _jsxs(_components.span, { className: "line", children: [_jsx(_components.span, { style: { color: "#9CDCFE", "--shiki-dark": "#9CDCFE" }, children: "dotenv" }), _jsx(_components.span, { style: { color: "#D4D4D4", "--shiki-dark": "#D4D4D4" }, children: "." }), _jsx(_components.span, { style: { color: "#DCDCAA", "--shiki-dark": "#DCDCAA" }, children: "config" }), _jsx(_components.span, { style: { color: "#D4D4D4", "--shiki-dark": "#D4D4D4" }, children: "();" })] }), "\n", _jsxs(_components.span, { className: "line", children: [_jsx(_components.span, { style: { color: "#569CD6", "--shiki-dark": "#569CD6" }, children: "const" }), _jsx(_components.span, { style: { color: "#4FC1FF", "--shiki-dark": "#4FC1FF" }, children: " REQUESTY_API_KEY" }), _jsx(_components.span, { style: { color: "#D4D4D4", "--shiki-dark": "#D4D4D4" }, children: " = " }), _jsx(_components.span, { style: { color: "#9CDCFE", "--shiki-dark": "#9CDCFE" }, children: "process" }), _jsx(_components.span, { style: { color: "#D4D4D4", "--shiki-dark": "#D4D4D4" }, children: "." }), _jsx(_components.span, { style: { color: "#9CDCFE", "--shiki-dark": "#9CDCFE" }, children: "env" }), _jsx(_components.span, { style: { color: "#D4D4D4", "--shiki-dark": "#D4D4D4" }, children: "." }), _jsx(_components.span, { style: { color: "#4FC1FF", "--shiki-dark": "#4FC1FF" }, children: "REQUESTY_API_KEY" }), _jsx(_components.span, { style: { color: "#D4D4D4", "--shiki-dark": "#D4D4D4" }, children: ";" })] }), "\n", _jsx(_components.span, { className: "line" }), "\n", _jsx(_components.span, { className: "line", children: _jsx(_components.span, { style: { color: "#6A9955", "--shiki-dark": "#6A9955" }, children: "// Initialize OpenAI client" }) }), "\n", _jsxs(_components.span, { className: "line", children: [_jsx(_components.span, { style: { color: "#569CD6", "--shiki-dark": "#569CD6" }, children: "const" }), _jsx(_components.span, { style: { color: "#4FC1FF", "--shiki-dark": "#4FC1FF" }, children: " openai" }), _jsx(_components.span, { style: { color: "#D4D4D4", "--shiki-dark": "#D4D4D4" }, children: " = " }), _jsx(_components.span, { style: { color: "#569CD6", "--shiki-dark": "#569CD6" }, children: "new" }), _jsx(_components.span, { style: { color: "#DCDCAA", "--shiki-dark": "#DCDCAA" }, children: " OpenAI" }), _jsx(_components.span, { style: { color: "#D4D4D4", "--shiki-dark": "#D4D4D4" }, children: "({" })] }), "\n", _jsxs(_components.span, { className: "line", children: [_jsx(_components.span, { style: { color: "#9CDCFE", "--shiki-dark": "#9CDCFE" }, children: " apiKey:" }), _jsx(_components.span, { style: { color: "#4FC1FF", "--shiki-dark": "#4FC1FF" }, children: " REQUESTY_API_KEY" }), _jsx(_components.span, { style: { color: "#D4D4D4", "--shiki-dark": "#D4D4D4" }, children: "," })] }), "\n", _jsxs(_components.span, { className: "line", children: [_jsx(_components.span, { style: { color: "#9CDCFE", "--shiki-dark": "#9CDCFE" }, children: " baseURL:" }), _jsx(_components.span, { style: { color: "#CE9178", "--shiki-dark": "#CE9178" }, children: " 'https://router.requesty.ai/v1'" }), _jsx(_components.span, { style: { color: "#D4D4D4", "--shiki-dark": "#D4D4D4" }, children: "," })] }), "\n", _jsx(_components.span, { className: "line", children: _jsx(_components.span, ``` -------------------------------- ### Python Example for Request Metadata Source: https://docs.requesty.ai/features/request-metadata This snippet demonstrates how to include core and custom metadata fields when making a request to the OpenAI API using Python. Ensure you have the openai library installed. ```python import openai openai.api_key = "YOUR_API_KEY" response = openai.chat.completions.create( model="gpt-4", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Who won the world series in 2020?"} ], tags=["sports", "baseball"], user_id="user_123", trace_id="trace_abc", extra={ "country": "USA", "prompt_title": "World Series Winner Query", "tier": "premium", "language": "en", "application": "web_app" } ) print(response.choices[0].message.content) ``` -------------------------------- ### Python Example: Adding Request Metadata Source: https://docs.requesty.ai/features/request-metadata This Python snippet demonstrates how to add custom metadata to an API call using the `extra_body` parameter. Ensure you have the necessary client library installed. ```python from openai import OpenAI client = OpenAI( api_key="YOUR_API_KEY", base_url="https://api.requesty.ai/v1" ) response = client.chat.completions.create( model="gpt-4o", messages=[ { "role": "user", "content": "Hello, world!" } ], extra_body={ "metadata": { "user_id": "user_123", "session_id": "session_abc", "workflow_id": "wf_xyz" } } ) print(response.choices[0].message.content) ``` -------------------------------- ### Node.js Example: OpenAI API Call Source: https://docs.requesty.ai/features/request-metadata This Node.js example shows how to initialize the OpenAI client and make an API call. It requires the 'openai' and 'dotenv' packages. Ensure your API key is set in the environment variables. ```javascript import OpenAI from 'openai'; import dotenv from 'dotenv'; dotenv.config(); const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY, }); async function main() { const completion = await openai.chat.completions.create({ messages: [{ role: 'user', content: 'Write a short poem about a cat.' }], model: 'gpt-3.5-turbo', }); console.log(completion.choices[0]); } main(); ``` -------------------------------- ### Configure Requesty Client Source: https://docs.requesty.ai/api-reference/endpoint/chat-completions-create Set up the Requesty client with your API key and base URL. Ensure the REQUESTY_API_KEY is set in your environment variables. ```javascript const { RequestyClient } = require("requesty"); const client = new RequestyClient({ apiKey: process.env.REQUESTY_API_KEY, baseURL: "https://router.requesty.ai/v1" }); ``` -------------------------------- ### Chat Completion Request with System Message (Node.js) Source: https://docs.requesty.ai/api-reference/endpoint/chat-completions-create This example shows how to include a system message in your chat completion request to guide the model's behavior. It's useful for setting context or instructions. ```javascript import OpenAI from "openai"; const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY, }); async function main() { const completion = await openai.chat.completions.create({ messages: [ { role: "system", content: "You are a helpful assistant." }, { role: "user", content: "Who won the world series in 2020?" }, ], model: "gpt-3.5-turbo", }); console.log(completion.choices[0].message); } ``` -------------------------------- ### Initialize OpenAI Client and Create Chat Completion Source: https://docs.requesty.ai/features/fallback-policies Demonstrates initializing the OpenAI client and making a chat completion request. Requires the 'openai' package to be installed. ```typescript import OpenAI from 'openai'; const client = new OpenAI ``` -------------------------------- ### Python Example for Web Search Source: https://docs.requesty.ai/llms-full.txt This Python snippet shows how to use the Requesty API with the OpenAI client library to perform a web search. Ensure you have the 'openai' library installed and replace 'YOUR_REQUESTY_API_KEY' with your actual key. ```python from openai import OpenAI client = OpenAI( api_key="YOUR_REQUESTY_API_KEY", base_url="https://router.requesty.ai/v1", ) response = client.chat.completions.create( model="anthropic/claude-sonnet-4-20250514", messages=[ { "role": "user", "content": "What are the latest developments in artificial intelligence?" } ], tools=[{"type": "web_search"}] ) print(response.choices[0].message.content) ``` -------------------------------- ### Python Example: Reasoning Budget Source: https://docs.requesty.ai/llms-full.txt Use this snippet to set a reasoning budget (in tokens) for an OpenAI model via the Requesty AI router. Ensure you have the OpenAI Python library installed and your API key configured. ```python # Safely load your API key requesty_api_key = "YOUR_REQUESTY_API_KEY" client = openai.OpenAI( api_key=requesty_api_key, base_url='https://router.requesty.ai/v1' ) def test_reasoning_budget(): try: prompt = """ Write a bash script that takes a matrix represented as a string with format '[1,2],[3,4],[5,6]' and prints the transpose in the same format. """.strip() print('Sending request to reasoning model...') completion = client.chat.completions.create( model="openai/o3-mini", reasoning_effort="10000", messages=[ { "role": "user", "content": prompt } ] ) # Log the completion details print(' Completion Response:') print('-------------------') if completion.choices[0].message.content: print(completion.choices[0].message.content) # Log token usage details print(' Token Usage Details:') print('-------------------') if completion.usage: usage_details = { "prompt_tokens": completion.usage.prompt_tokens, "completion_tokens": completion.usage.completion_tokens, "total_tokens": completion.usage.total_tokens } print(json.dumps(usage_details, indent=2)) # Log specific reasoning token details if available if completion.usage.completion_tokens_details: print(' Reasoning Token Details:') print('----------------------') print(completion.usage.completion_tokens_details) except Exception as error: print(f'Error: {str(error)}') if __name__ == '__main__': test_reasoning_budget() ``` -------------------------------- ### Initialize OpenAI Client Source: https://docs.requesty.ai/api-reference/endpoint/chat-completions-create Import the OpenAI library and initialize the client. Ensure you have the 'openai' package installed. ```typescript import OpenAI from "openai" ``` -------------------------------- ### Python Image Generation Example Source: https://docs.requesty.ai/features/image-generation This snippet shows how to initialize the Requesty AI client with your API key and base URL, and then generate an image. Ensure you replace 'YOUR_REQUESTY_API_KEY' with your actual key. ```python import base64 from io import BytesIO from PIL import Image from openai import OpenAI client = OpenAI( api_key="YOUR_REQUESTY_API_KEY", base_url="https://router.requesty.ai/v1", ) response = client.images.generate( model="dall-e-3", prompt="A cute baby sea otter floating on its back", size="1024x1024", quality="standard", n=1, ) image_url = response.data[0].url print(image_url) # To save the image locally: # import requests # img_data = requests.get(image_url).content # with open('otter.png', 'wb') as handler: # handler.write(img_data) ``` -------------------------------- ### Python Example for Chat Completions API with Auto Cache Source: https://docs.requesty.ai/features/auto-caching Demonstrates how to include the auto_cache flag in a Chat Completions API request using Python. Ensure you have the openai library installed and your API key configured. ```python import openai client = openai.OpenAI( api_key="YOUR_REQUESTY_API_KEY", base_url="https://router.requesty.ai/v1", ) system_prompt = "YOUR ``` -------------------------------- ### Enabling Web Search with Tools Source: https://docs.requesty.ai/api-reference/endpoint/chat-completions-create Demonstrates how to enable real-time web search by including a 'web_search' tool in the tools array. Requesty automatically translates this to provider-specific formats. ```json { "model": "anthropic/claude-sonnet-4-20250514", "messages": [ { "role": "user", "content": "What is the weather like today?" } ], "tools": [ { "type": "web_search" } ] } ``` -------------------------------- ### JavaScript Example: Reasoning Effort Source: https://docs.requesty.ai/llms-full.txt Use this snippet to set a specific reasoning effort level for an OpenAI model via the Requesty AI router. Ensure you have the OpenAI Node.js library installed and your API key configured. ```javascript const requesty_api_key = "YOUR_REQUESTY_API_KEY" // Safely load your API key const client = new OpenAI({ apiKey: requesty_api_key, baseURL: 'https://router.requesty.ai/v1', }); async function testReasoningEffort() { try { const prompt = ` Write a bash script that takes a matrix represented as a string with format '[1,2],[3,4],[5,6]' and prints the transpose in the same format. `.trim(); console.log('Sending request to reasoning model...'); const completion = await client.chat.completions.create({ model: "openai/o3-mini", reasoning_effort: "medium", messages: [ { role: "user", content: prompt } ] }); console.log(' Completion Response:'); console.log('-------------------'); if (completion.choices[0]?.message?.content) { console.log(completion.choices[0].message.content); } console.log(' Token Usage Details:'); console.log('-------------------'); if (completion.usage) { const usageDetails = { prompt_tokens: completion.usage.prompt_tokens, completion_tokens: completion.usage.completion_tokens, total_tokens: completion.usage.total_tokens }; console.log(JSON.stringify(usageDetails, null, 2)); // Log specific reasoning token details if available if ('completion_tokens_details' in completion.usage) { console.log(' Reasoning Token Details:'); console.log('----------------------'); console.log(JSON.stringify(completion.usage.completion_tokens_details, null, 2)); } } } catch (error) { console.error('Error:', error); } } testReasoningEffort(); ``` -------------------------------- ### Generate Image with JavaScript/TypeScript Source: https://docs.requesty.ai/features/image-generation Utilize the OpenAI JavaScript/TypeScript client to generate an image. This example demonstrates setting the model, prompt, aspect ratio, and image size, followed by saving the output. Ensure you have Node.js and the 'openai' package installed. ```javascript import OpenAI from 'openai'; import fs from 'fs'; const client = new OpenAI({ apiKey: 'YOUR_REQUESTY_API_KEY', baseURL: 'https://router.requesty.ai/v1', }); async function generateImage() { const response = await client.chat.completions.create({ model: 'vertex/google/gemini-2.5-flash-image-preview', messages: [ { role: 'user', content: 'Generate a serene landscape with a lake' } ], image_config: { aspect_ratio: '16:9', image_size: '2K' } }); const message = response.choices[0].message; // Handle generated images if (message.images && message.images.length > 0) { message.images.forEach((imageData, index) => { // Extract base64 data from data URL // Format: "data:image/png;base64,actual_base64_data" const base64Data = imageData.image_url.url.split(',')[1]; const imageBuffer = Buffer.from(base64Data, 'base64'); // Save to file fs.writeFileSync(`generated_image_${index}.png`, imageBuffer); console.log(`Image saved as generated_image_${index}.png`); }); } // Access the text response console.log(message.content); } generateImage(); ``` -------------------------------- ### Python Example with Request Metadata Source: https://docs.requesty.ai/features/request-metadata Demonstrates how to send a request with custom metadata using the 'requests' library in Python. Ensure the metadata is formatted as a dictionary. ```python import requests url = "https://api.example.com/data" headers = { "Content-Type": "application/json" } metadata = { "user_id": "12345", "request_id": "abcde", "source": "web_app" } payload = { "key1": "value1", "key2": "value2" } response = requests.post(url, headers=headers, json=payload, params=metadata) print(response.status_code) print(response.json()) ``` -------------------------------- ### Generate Image with Default Settings Source: https://docs.requesty.ai/features/image-generation This example shows how to generate an image using the default settings. No specific parameters are provided, so the API will use its predefined defaults for image size, quality, and style. ```javascript const requesty = require("requesty") requesty.images.generate({ prompt: "A futuristic cityscape at sunset, digital art" }).then(response => { console.log(response.data) }).catch(error => { console.error(error) }) ``` -------------------------------- ### Get Organization Source: https://docs.requesty.ai/features/bring-your-own-keys Get information about your organization. ```APIDOC ## GET /v1/manage/org ### Description Get information about your organization. ### Method GET ### Endpoint /v1/manage/org ```