# Headers & Auth Source: https://docs.sudoapp.dev/api-ref/auth API Authentication & Headers Sudo uses **Bearer token** authentication. Every request must include your secret API key in the `Authorization` header: ``` Authorization: Bearer ``` You can create and manage keys within apps from the **Developer Portal → My AI Apps** section. Treat your keys like passwords. Do **not** commit them to version-control or expose them in front-end code. *** ## Using an API key ```typescript title="JavaScript / TypeScript" theme={null} fetch('https://sudoapp.dev/api/v1/chat/completions', { method: 'POST', headers: { Authorization: 'Bearer ', 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'gpt-4o', messages: [{ role: 'user', content: 'Hello!' }], }), }); ``` ```python title="Python" theme={null} import requests, json url = 'https://sudoapp.dev/api/v1/chat/completions' headers = { 'Authorization': 'Bearer ', 'Content-Type': 'application/json', } payload = { 'model': 'gpt-4o', 'messages': [{ 'role': 'user', 'content': 'Hello!' }], } r = requests.post(url, headers=headers, data=json.dumps(payload)) print(r.json()) ``` ```shell title="curl" theme={null} curl https://sudoapp.dev/api/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $SUDO_API_KEY" \ -d '{"model":"gpt-4o","messages":[{"role":"user","content":"Hello!"}]}' ``` *** ### Rotating or revoking keys If a key is ever exposed you can disable or delete it from the portal and generate a new one immediately. Requests bearing a revoked key will receive a `401` error. *** ### Minimum headers Only two headers are required: | Header | Example | Notes | | --------------- | ------------------ | -------- | | `Authorization` | `Bearer sk-abc123` | Required | | `Content-Type` | `application/json` | Required | # Overview Source: https://docs.sudoapp.dev/api-ref/overview Overview of the Sudo developer API Sudo's REST API closely mirrors the [OpenAI Chat Completions](https://platform.openai.com/docs/api-reference/chat) specification.\ If you already integrate with OpenAI you can usually **swap the base URL, provide a Sudo API key, and you're done**. **Base URL**: `https://sudoapp.dev/api`\ **Completions endpoint**: `/v1/chat/completions` Some third-party model providers do **not** support every OpenAI feature (for example *tools* or *vision*). Refer to their individual documentation when in doubt. *** ## Requests The request body you `POST` to `/v1/chat/completions` accepts the same fields you're used to. Below is an **example** condensed TypeScript definition (non-exhaustive): ```typescript title="Request Schema" theme={null} export type ChatCompletionRequest = { /* Pick **one** */ messages: Message[]; /** Full model identifier – e.g. `gpt-4o` or `claude-4-sonnet` */ model: string; /** Format enforcement – OpenAI-style */ response_format?: { type: 'json_object' }; /* Common generation params */ max_completion_tokens?: number; parallel_tool_calls?: boolean; tools?: Tool[]; temperature?: number; top_p?: number; stop_sequences?: string[]; stream?: boolean; }; export type Message = { role: 'system' | 'user' | 'assistant' | 'tool'; content: string | ContentPart[]; name?: string; /** Only for tool role */ tool_call_id?: string; }; export type ContentPart = | { type: 'text'; text: string } | { type: 'image_url'; image_url: { url: string; detail?: string } }; ``` For a more exhaustive spec of supported request parameters, see the endpoints in the next section. ### Headers Only two headers are required: | Header | Value | | --------------- | ----------------------- | | `Authorization` | `Bearer ` | | `Content-Type` | `application/json` | ### Example ```shell title="curl" theme={null} curl https://sudoapp.dev/api/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $SUDO_API_KEY" \ -d '{ "model": "gpt-4o", "messages": [{"role":"user","content":"Hello!"}] }' ``` *** ## Responses Sudo **normalises** provider responses to match the OpenAI schema. A non-streaming response looks like this: ```json title="Example Response" theme={null} { "id": "chatcmpl-abc123", "object": "chat.completion", "created": 1710000000, "model": "gpt-4o", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "Hello there!" }, "finish_reason": "stop", "native_finish_reason": "stop" } ], "usage": { "prompt_tokens": 5, "completion_tokens": 4, "total_tokens": 9 } } ``` ### Finish reasons `finish_reason` is one of `stop`, `length`, `tool_calls`, `content_filter`, or `error` – mirroring OpenAI's values. ### Error handling Errors follow the shape: ```json title="Error" theme={null} { "error": { "message": "Invalid API key", "type": "api_error" } } ``` *** ## Next steps Read about authenticating requests See **Streaming** to deliver tokens to your UI in real-time. # Rate Limits & Overload Handling Source: https://docs.sudoapp.dev/api-ref/rate_limits Understand Sudo API rate limits, headers, and retry guidance Sudo enforces request rate limits to ensure fair usage and platform stability. This page describes the limits, response headers, and error codes you may encounter so you can implement appropriate backoff and retry logic. ## Rate Limits Sudo applies a general request rate of approximately 600 requests per minute (RPM) with short burst capacity. When you exceed the allowed rate, requests may be rejected. ### What you’ll see when limited * **HTTP status**: `429 Too Many Requests` * **Headers**: Standard rate-limiting headers are returned, including `RateLimit-*` headers when applicable, and a `Retry-After` header in some cases. Use these to determine when to retry. * **Body**: A brief message indicating the request was rate limited. Example handling pattern: ```bash theme={null} # Pseudocode logic for client retries if status == 429: wait = response.headers.get('Retry-After') or derive_from_rate_limit_headers() sleep(wait_seconds) retry() ``` ### Provider-level throttling In addition to general request limits, upstream model providers (OpenAI, Anthropic, Google, xAI, etc.) may enforce their own quotas. When Sudo temporarily exhausts a provider’s budget, you may receive a response instructing you to retry later. * **HTTP status**: `503 Service Unavailable` * **Header**: `Retry-After: ` — indicates when it is safe to retry * **Body** (JSON): ```json theme={null} { "error": { "type": "upstream_rate_limited", "scope": "provider:", "detail": "Provider budget temporarily exhausted" } } ``` Implement exponential backoff and respect `Retry-After` before retrying. ## Overload: HTTP 503 If the platform is temporarily overloaded (e.g., too many concurrent users or requests), you may receive: * **HTTP status**: `503 Service Unavailable` * **Header**: `Retry-After: ` — how long to wait before retrying Recommended handling: 1. Read the `Retry-After` header. 2. Wait the indicated number of seconds. 3. Retry with exponential backoff if needed. ## Best Practices * Prefer exponential backoff with jitter for retries. * Always honor `Retry-After` when present. * Keep requests within reasonable volumes to avoid throttling. * Consider queuing or batching non-urgent work. Some SDK methods include built-in retry mechanics. If you implement your own, make sure to cap maximum retries and total wait time to provide a responsive user experience. # Responses API Source: https://docs.sudoapp.dev/api-ref/responses_api OpenAI Responses API via Sudo Sudo exposes the [OpenAI Responses API](https://platform.openai.com/docs/api-reference/responses/create) at the `v1/responses` endpoint.\ If you're already using OpenAI's Responses API you can usually **swap the base URL, provide a Sudo API key, and you're done**. **Base URL**: `https://sudoapp.dev/api`\ **Responses endpoint**: `/v1/responses` This interface **only supports OpenAI models** (for example `gpt-4.1`, `gpt-4.1-mini`, `o3-mini`, etc.).\ Sudo **forwards requests directly to OpenAI's Responses API** with one-to-one parity, which makes it ideal for **agent-style workflows, tools-heavy orchestration, and modern OpenAI-first features** that go beyond classic chat completions. As with `/v1/chat/completions`, **rate limiting and error handling are managed by Sudo's AI router** – behavior is identical to the canonical `/v1/chat/completions` endpoint. *** ## Requests You `POST` to `/v1/responses` with the same shape OpenAI expects.\ Below is an **example** condensed TypeScript definition (non-exhaustive) that highlights the most commonly used fields: ```typescript title="Request Schema" theme={null} export type ResponsesRequest = { /** Required: OpenAI model identifier, e.g. `gpt-4.1-mini` */ model: string; /** * Core input to the model. * Can be a simple string, or an array of structured items (messages, tool calls, etc.). */ input?: ResponsesInput; /** High-level instructions / system prompt for the model. */ instructions?: string | ResponseInstructionItem[]; /** Enable or disable automatic tool calling. */ tool_choice?: 'none' | 'auto' | 'required' | ToolChoiceObject; /** Tools (functions, file search, code interpreter, etc.) available to the model. */ tools?: Tool[]; /** Common generation params */ temperature?: number; top_p?: number; max_output_tokens?: number; /** Agent / orchestration features */ reasoning?: unknown; service_tier?: 'auto' | 'default' | string; metadata?: Record; store?: boolean; conversation?: string | ConversationConfig; previous_response_id?: string; /** Streaming */ stream?: boolean; stream_options?: unknown; /** Other advanced options from OpenAI are also supported 1:1 */ truncation?: string; max_tool_calls?: number; top_logprobs?: number; prompt_cache_key?: string; }; export type ResponsesInput = | string | InputItem[]; export type InputItem = | { role: 'user' | 'assistant' | 'system'; content: MessageContent; } | StructuredItem | ItemReference; export type MessageContent = | string | Array< | { type: 'input_text'; text: string } | { type: 'input_image'; image_url?: string; file_id?: string; detail?: 'low' | 'high' | 'auto'; } | { type: 'input_file'; file_id?: string; file_url?: string; filename?: string; } | { type: 'input_audio'; input_audio: { data: string; format: string }; } >; ``` For a fully detailed schema (including the richer `Item` types for tools, MCP, computer use, etc.), see the official [OpenAI Responses API reference](https://platform.openai.com/docs/api-reference/responses/create). ### Headers Only two headers are required: | Header | Value | | --------------- | ----------------------- | | `Authorization` | `Bearer ` | | `Content-Type` | `application/json` | ### Minimal JSON example The smallest useful request can be just a model and a string input: ```json title="Minimal Request" theme={null} { "model": "gpt-4.1-mini", "input": "Say hello from the Sudo Responses API." } ``` For richer agent-style prompts you typically send an array of input items: ```json title="Structured Input Request" theme={null} { "model": "gpt-4.1-mini", "input": [ { "role": "system", "content": [ { "type": "input_text", "text": "You are an assistant that answers in JSON." } ] }, { "role": "user", "content": [ { "type": "input_text", "text": "Return a todo list for moving apartments." } ] } ], "tool_choice": "auto", "tools": [ { "type": "function", "name": "create_task", "description": "Create a task in the user's task manager", "parameters": { "type": "object", "properties": { "title": { "type": "string" }, "due_date": { "type": "string", "format": "date-time" } }, "required": ["title"] } } ] } ``` ### Example: non‑streaming `curl` ```shell title="curl" theme={null} curl https://sudoapp.dev/api/v1/responses \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $SUDO_API_KEY" \ -d '{ "model": "gpt-4.1-mini", "input": "Say hello from the Sudo Responses API." }' ``` *** ## Responses Sudo **returns the same schema as the OpenAI Responses API**, including the `response` object and `output` items. ```typescript title="Response Schema (simplified)" theme={null} export type Response = { id: string; object: 'response'; created_at: number; model: string; /** Overall status of the response */ status: | 'in_progress' | 'completed' | 'failed' | 'cancelled' | 'incomplete'; /** Generated output items (messages, tool calls, reasoning, etc.) */ output?: Item[]; /** Conversation information (if stored) */ conversation?: { id: string }; /** Token usage */ usage?: { input_tokens: number; output_tokens: number; total_tokens: number; }; /** Optional configuration echoes and metadata */ metadata?: Record; background?: boolean; instructions?: string | unknown[]; max_output_tokens?: number; max_tool_calls?: number; parallel_tool_calls?: boolean; previous_response_id?: string; prompt?: unknown; prompt_cache_key?: string; reasoning?: unknown; safety_identifier?: string; service_tier?: string; temperature?: number; text?: unknown; tool_choice?: unknown; tools?: unknown[]; truncation?: string; top_p?: number; top_logprobs?: number; }; export type Item = | OutputMessageItem | ToolCallItem | ToolCallOutputItem | ReasoningItem | FileSearchItem | CodeInterpreterItem | MCPItem | CustomToolItem; export type OutputMessageItem = { id: string; type: 'output_message'; role: 'assistant'; status: string; content: Array< | { type: 'output_text'; text: string; annotations: unknown[]; logprobs?: unknown[]; } | { type: 'refusal'; refusal: string } >; }; ``` ### Example response ```json title="Example Response" theme={null} { "id": "resp_abc123", "object": "response", "created_at": 1710000000, "model": "gpt-4.1-mini", "status": "completed", "output": [ { "id": "msg_1", "type": "output_message", "role": "assistant", "status": "completed", "content": [ { "type": "output_text", "text": "Hello from the Sudo Responses API!", "annotations": [], "logprobs": null } ] } ], "usage": { "input_tokens": 12, "output_tokens": 8, "total_tokens": 20 } } ``` ### Errors Error envelopes are **identical** to the rest of the Sudo AI router (including `/v1/chat/completions`), for example: ```json title="Error" theme={null} { "error": { "message": "Invalid API key", "type": "api_error" } } ``` You can expect OpenAI-originated errors (for example invalid model, bad tools schema) to be surfaced through the same structure with appropriate HTTP status codes. *** ## Streaming When you set `"stream": true` in the request body, Sudo will stream **Server‑Sent Events (SSE)** that mirror the [OpenAI Responses streaming format](https://platform.openai.com/docs/api-reference/responses-streaming/response). Unlike `/v1/chat/completions` streaming, which sends **delta chunks for `choices[].delta`**, the Responses API streams **typed events** such as: * **`response.created`**: the response object has been created. * **`response.output_text.delta`**: incremental text tokens being generated. * **`response.output_text.done`**: the final text segment for an output item. * **`response.completed`**: the entire response has finished. * **`error`**: an error occurred while generating the response. Each SSE event is a JSON object with a top-level `type` field. A typical stream might start like: ```text title="SSE events (truncated)" theme={null} data: {"type":"response.created","response":{"id":"resp_abc123","status":"in_progress", ...}} data: { "type": "response.output_text.delta", "delta": { "content": [ { "type": "output_text_delta", "text": { "value": "Hello from the " } } ] } } data: {"type":"response.output_text.done", ...} data: {"type":"response.completed","response":{"id":"resp_abc123","status":"completed", ...}} data: [DONE] ``` ### Example: streaming `curl` ```shell title="curl (streaming)" theme={null} curl https://sudoapp.dev/api/v1/responses \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $SUDO_API_KEY" \ -N \ -d '{ "model": "gpt-4.1-mini", "input": [ { "role": "user", "content": [ { "type": "input_text", "text": "Write a short haiku about the Sudo Responses API." } ] } ], "stream": true }' ``` The SSE stream can be consumed using any EventSource/SSE client or your own HTTP streaming logic. *** ## Rate limiting & behavior * **Rate limits**: The Responses API is subject to the same Sudo-side rate limiting as `/v1/chat/completions` (per‑app, per‑developer, and provider‑level throttling). * **Error handling**: Errors are normalized and returned using the same `ErrorResponse` shape as the rest of the AI router. Because Sudo simply forwards to OpenAI's Responses API under the hood, you automatically benefit from the **latest OpenAI agent and orchestration features**, while keeping a single Sudo integration (API key, billing, and monitoring) across all your AI usage. # Streaming Source: https://docs.sudoapp.dev/api-ref/streaming Streaming responses from the Sudo API. All Sudo models support **server-sent event (SSE) streaming**.\ Add `"stream": true` to your request body and consume the event-stream as it arrives. *** ## Example – Python ```python Python theme={null} import requests, json url = "https://sudoapp.dev/api/v1/chat/completions" headers = { "Authorization": "Bearer ", "Content-Type": "application/json", } payload = { "model": "gpt-4o", "messages": [{"role": "user", "content": "Tell me a joke"}], "stream": True, } buffer = "" with requests.post(url, headers=headers, json=payload, stream=True) as r: for chunk in r.iter_content(chunk_size=1024, decode_unicode=True): buffer += chunk while "\n" in buffer: line, buffer = buffer.split("\n", 1) line = line.strip() if not line.startswith("data: "): # Comments (begin with :) can be ignored per the SSE spec continue data = line[6:] if data == "[DONE]": break message = json.loads(data) content_delta = message["choices"][0]["delta"].get("content") if content_delta: print(content_delta, end="", flush=True) ``` *** ## Example – TypeScript / browser fetch ```typescript TypeScript theme={null} const response = await fetch('https://sudoapp.dev/api/v1/chat/completions', { method: 'POST', headers: { Authorization: `Bearer ${SUDO_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'gpt-4o', messages: [{ role: 'user', content: 'Tell me a joke' }], stream: true, }), }); const reader = response.body?.getReader(); if (!reader) throw new Error('Streaming unsupported'); const decoder = new TextDecoder(); let buffer = ''; while (true) { const { value, done } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream: true }); while (true) { const nl = buffer.indexOf('\n'); if (nl === -1) break; const line = buffer.slice(0, nl).trim(); buffer = buffer.slice(nl + 1); if (!line.startsWith('data: ')) continue; // Ignore comments const data = line.slice(6); if (data === '[DONE]') break; const parsed = JSON.parse(data); const delta = parsed.choices[0].delta.content; if (delta) { console.log(delta); } } } ``` *** ### About the SSE payload 1. Each line that begins with `data: ` contains a JSON chunk. 2. Lines beginning with `:` are **comments** and can be safely ignored. 3. A final line `data: [DONE]` signals the end of the stream. *** ### Cancelling streams Simply abort or close the underlying HTTP connection (e.g. via `AbortController` in the browser). The request will stop; however, you may be billed for the tokens of the full stream. # Chat Completion Messages Source: https://docs.sudoapp.dev/api-reference/ai-routing/chat-completion-messages https://sudoapp.dev/api/openapi.json get /v1/chat/completions/{completion_id}/messages # Create Chat Completion Source: https://docs.sudoapp.dev/api-reference/ai-routing/create-chat-completion https://sudoapp.dev/api/openapi.json post /v1/chat/completions # Create Response Source: https://docs.sudoapp.dev/api-reference/ai-routing/create-response https://sudoapp.dev/api/openapi.json post /v1/responses # Delete Chat Completion Source: https://docs.sudoapp.dev/api-reference/ai-routing/delete-chat-completion https://sudoapp.dev/api/openapi.json delete /v1/chat/completions/{completion_id} # Generate Image Source: https://docs.sudoapp.dev/api-reference/ai-routing/generate-image https://sudoapp.dev/api/openapi.json post /v1/images/generations # Get a Chat Completion Source: https://docs.sudoapp.dev/api-reference/ai-routing/get-a-chat-completion https://sudoapp.dev/api/openapi.json get /v1/chat/completions/{completion_id} # List Chat Completions Source: https://docs.sudoapp.dev/api-reference/ai-routing/list-chat-completions https://sudoapp.dev/api/openapi.json get /v1/chat/completions # Update Chat Completion Source: https://docs.sudoapp.dev/api-reference/ai-routing/update-chat-completion https://sudoapp.dev/api/openapi.json post /v1/chat/completions/{completion_id} # Get supported models list (for devs to use) Source: https://docs.sudoapp.dev/api-reference/system/get-supported-models-list-for-devs-to-use https://sudoapp.dev/api/openapi.json get /v1/models # System Health Source: https://docs.sudoapp.dev/api-reference/system/system-health https://sudoapp.dev/api/openapi.json get /system/health # Introduction Source: https://docs.sudoapp.dev/overview/introduction Welcome to the Sudo developer platform # Sudo: One API for All Models ## What is Sudo? Sudo is a unified API for large language models. We make it simple for developers to route across different LLMs while getting better performance, lower cost, and higher uptime than going direct. ### Sudo Developer Platform With Sudo, developers can build AI apps without worrying about vendor lock-in or juggling multiple integrations. **One API gives you seamless access to models from OpenAI, Anthropic, Google, and more** — while our router optimizes every call for speed and price. Sudo’s mission is to be the most reliable and cost-efficient LLM router, so you can focus on building great products instead of managing infrastructure. ### What's Next: Context & Monetization We’re extending Sudo beyond routing into context engineering and monetization features. With one single API endpoint, developers will be able to: * **Feed context into apps seamlessly** — attach documents, links, or instructions once, and Sudo will automatically **manage and optimize context** across every model call, without manually rewriting system prompts. * **Monetize end users directly** — unlock revenue streams through built-in **contextual ad placement and usage-based billing**, so you can focus on growing your product while Sudo handles payments and optimization. By combining **routing, context, and monetization** in one place, Sudo moves closer to being the all-in-one developer platform for building and scaling AI apps. ## Getting Started Get onboarded to the Sudo Developer Platform by using our quickstart guide. Get up and running in minutes # Supported AI Models Source: https://docs.sudoapp.dev/overview/models Sudo supports dozens of models from top providers # Fetching the Latest Models via API [The models endpoint](/api-reference/system/get-supported-models) is the source of ground truth for supported models in our API. As soon as we confirm support of a model or model provider, it will be added to the API. The models endpoint returns supported models, identified by their canonical model ID that the original provider operates with. There is also an internal Sudo model ID, which is separate of the provider model ID and is used internally: ```json theme={null} { "data": [ /* Array of model objects */ { "created_at": "2025-02-19T00:00:00Z", "sudo_model_id": 52, "model_name": "claude-3-7-sonnet-20250219", "model_provider": "Anthropic" }, ], "first_id": "", "has_more": false, "last_id": "" } ``` ## Model Obect Fields | **Field** | **Type** | **Description** | | ---------------- | -------- | ------------------------------------------------------------------------------------------- | | `created_at` | String | DateTime representation of when the model was added to the Sudo API support . | | `sudo_model_id` | int | Internal model ID used for identification by the Sudo API, in the form of a serial integer. | | `model_name` | String | Canonical model ID, as assigned by the original model provider. e.g. "gpt-4.1-mini" | | `model_provider` | String | The model provider's name, e.g. "OpenAI" | # Table of Suppported Models | **Model Provider** | **Model ID** | **Display Name** | | ------------------ | ------------------------------------- | :-----------------------------------: | | OpenAI | gpt-5 | GPT-5 | | | gpt-5-nano | GPT-5 nano | | | gpt-5-mini | GPT-5 mini | | | gpt-5-chat-latest | GPT-5 chat | | | o4-mini | o4 | | | o3 | o3 | | | o3-mini | o3 | | | o1 | o1 | | | gpt-4.1 | GPT-4.1 | | | gpt-4.1-mini | GPT-4.1 mini | | | gpt-4.1-nano | GPT-4.1 nano | | | gpt-4o | GPT-4o | | | gpt-4o-mini | GPT-4o Mini | | | gpt-4o-audio-preview | GPT-4o Audio Preview | | | gpt-4o-search-preview | GPT-4o Search Preview | | | gpt-4o-mini-search-preview | GPT-4o Mini Search Preview | | | gpt-4o-mini-audio-preview | GPT-4o Mini Audio Preview | | | gpt-4-turbo-preview | GPT-4 Turbo Preview | | | gpt-4-turbo | GPT-4 Turbo | | | gpt-4-0613 | GPT-4 (0613) | | | gpt-4 | GPT-4 | | | gpt-3.5-turbo-16k | GPT-3.5 Turbo 16k | | | gpt-3.5-turbo-0125 | GPT-3.5 Turbo (0125) | | | gpt-3.5-turbo | GPT-3.5 Turbo | | | chatgpt-4o-latest | ChatGPT-4o Latest | | | gpt-image-1 | GPT Image | | | dall-e-3 | DALL-E 3 | | | dall-e-2 | DALL-E 2 | | Anthropic | claude-sonnet-4-5-20250929 | Claude Sonnet 4.5 | | | claude-opus-4-1-20250805 | Claude Opus 4.1 (2025-08-05) | | | claude-opus-4-20250514 | Claude Opus 4 (2025-05-22) | | | claude-sonnet-4-20250514 | Claude Sonnet 4 (2025-05-22) | | | claude-3-7-sonnet-20250219 | Claude 3.7 Sonnet (2025-02-19) | | | claude-3-7-sonnet-latest | Claude 3.7 Sonnet | | | claude-3-5-haiku-20241022 | Claude 3.5 Haiku (2024-10-22) | | | claude-3-5-haiku-latest | Claude 3.5 Haiku | | | claude-3-haiku-20240307 | Claude 3 Haiku (2024-03-07) | | DeepSeek | deepseek-chat | DeepSeek Chat (DeepSeek V3) | | | deepseek-reasoner | DeepSeek Reasoner (DeepSeek R1) | | XAI | grok-4-0709 | Grok-4 | | | grok-4-fast-reasoning | Grok-4 Fast Reasoning | | | grok-4-fast-non-reasoning | Grok-4 Fast Non-Reasoning | | | grok-code-fast-1 | Grok Code Fast | | | grok-3 | Grok-3 | | | grok-3-mini | Grok-3 Mini | | | grok-2-image-1212 | Grok-2 Image | | | grok-2-vision-1212 | Grok-2 Vision | | Gemini | gemini-2.5-pro | Gemini 2.5 Pro | | | gemini-2.5-flash | Gemini 2.5 Flash | | | gemini-2.5-flash-lite | Gemini 2.5 Flash Lite | | | gemini-2.5-flash-preview-04-17 | Gemini 2.5 Flash Preview (04-17) | | | gemini-2.5-flash-preview-09-2025 | Gemini 2.5 Flash Preview (09-25) | | | gemini-2.5-flash-lite-preview-06-17 | Gemini 2.5 Flash-Lite Preview (06-17) | | | gemini-2.5-flash-lite-preview-09-2025 | Gemini 2.5 Flash Lite Preview (09-25) | | | gemini-2.0-flash | Gemini 2.0 Flash | | | gemini-2.0-flash-lite | Gemini 2.0 Flash-Lite | | | imagen-4.0-generate-001 | Imagen 4.0 | | | imagen-4.0-fast-generate-001 | Imagen 4.0 Fast | | | imagen-4.0-ultra-generate-001 | Imagen 4.0 Ultra | | | imagen-3.0-generate-002 | Imagen 3.0 | # Quickstart Source: https://docs.sudoapp.dev/overview/quickstart-api Getting started with the Sudo developer platform. The Sudo developer platform gives you access to 100+ AI models with a single API key. To obtain an API key, use the[ Sudo developer portal](https://sudoapp.dev/dev/ai-apps/new) to create a simple dev app with an API key, then fill your account with credits using your Stripe payment method, which you can connect on the [billing settings page](https://sudoapp.dev/dev/settings/billing). # Using the Sudo API ```python Python theme={null} import requests import json response = requests.post( url="https://sudoapp.dev/api/v1/chat/completions", headers={ "Authorization": "Bearer ", }, data=json.dumps({ "model": "gpt-4o", "messages": [ { "role": "developer", "content": "You are a helpful assistant." }, { "role": "user", "content": "Hello! Give me a study plan to learn Python." } ], "store": true }) ) ``` ```typescript TypeScript theme={null} fetch('https://sudoapp.dev/api/v1/chat/completions', { method: 'POST', headers: { Authorization: 'Bearer ', 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'gpt-4o', messages: [ { role: 'developer', content: 'You are a helpful assistant.', }, { role: 'user', content: 'Hello! Give me a study plan to learn Python.', }, ], store: true }), }); ``` ```shellscript Shell theme={null} curl https://sudoapp.dev/api/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $SUDO_API_KEY" \ -d '{ "model": "gpt-4o", "messages": [ { "role": "developer", "content": "You are a helpful assistant." }, { "role": "user", "content": "Hello! Give me a study plan to learn Python." } ], "store": true }' ``` The API also supports streaming. ## Next Steps Explore the API capabilities and available models: # OpenAI SDK Compatability Source: https://docs.sudoapp.dev/sdk/openai-sdk The Sudo developer platform maintains parity with the OpenAI *Chat Completions* API, allowing you to use the **OpenAI SDK** to access Sudo's AI routing. By changing just two parameters, you can use the OpenAI SDK to build with Sudo today. This compatability is not suitable for future-proof and production use cases, and is better for testing and validation. Recall that each model provider has different degrees of support for OpenAI features (e.g. Anthropic models do not support `response_format` parameter). You must refer to their documentation of OpenAI compatability when in doubt # Using the OpenAI SDK Using an official SDK by OpenAI, do the following: 1. Change the base URL to Sudo's chat API URL: [https://sudoapp.dev/api/v1/](https://sudoapp.dev/api/v1/) 2. Change the API key to your **Sudo API key**, which you can get from the [dev dashboard](https://staging.sudoapp.dev/dev/dashboard). Now, you can call Sudo's chat API with **any** supported AI model of your choice. ```python Python theme={null} import openai # Replace with your Sudo API key openai.api_key = "your-sudo-api-key" # Set the custom base URL openai.base_url = "https://sudoapp.dev/api/v1/" # Make a test call to the chat endpoint response = openai.chat.completions.create( model="claude-sonnet-4-20250514", # or "gpt-4", "gemini-2.0-flash", etc. messages=[ {"role": "user", "content": "Hello! What is the capital of France?"} ], temperature=0.7, ) print("Response:") print(response.choices[0].message.content) ``` ```typescript TypeScript theme={null} import OpenAI from "openai"; // Initialize the OpenAI client with Sudo config const openai = new OpenAI({ apiKey: "your-sudo-api-key", // Replace with your Sudo API key baseURL: "http://sudoapp.dev/api/v1/", }); async function testChat() { const response = await openai.chat.completions.create({ model: "claude-sonnet-4-20250514", // or any model string messages: [{ role: "user", content: "Hello! What is the capital of France?" }], temperature: 0.7, }); console.log("Response:"); console.log(response.choices[0].message?.content); } testChat().catch(console.error); ``` ## Next Steps Explore the API capabilities and available models: # Introduction Source: https://docs.sudoapp.dev/sdk/sudo-sdk Official SDK for the Sudo AI platform - developer-friendly, type-safe, and feature-complete The official SDK for Sudo provides a developer-friendly and type-safe way to integrate with the Sudo AI platform. Available in both Python and TypeScript, it offers comprehensive support for all Sudo features including AI responses with streaming, tool calling, structured outputs, and more. ## Key Features Simple installation with pip, npm, or your preferred package manager. Get started in minutes with intuitive APIs. Built-in connection pooling, retry logic, and async support for optimal performance. Server-sent events for real-time streaming responses with proper context management. Native support for function calling and parallel tool execution. JSON schema validation and structured data extraction capabilities. Support for images, audio, and other modalities beyond text. ## Quick Start ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); async function main() { const response = await sudo.router.create({ model: "claude-sonnet-4-20250514", messages: [ { role: "user", content: "Hello! How are you?" } ] }); console.log(response.choices[0].message.content); } main(); ``` ```python Python theme={null} import os from sudo import Sudo # Initialize the client with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: # Create a chat completion response = client.router.create( model="claude-sonnet-4-20250514", messages=[ {"role": "user", "content": "Hello! How are you?"} ] ) print(response.choices[0].message.content) ``` ## Documentation Sections Get started with installation, authentication, and basic configuration. Health checks and model information endpoints. Basic AI responses with various models and parameters. Real-time streaming responses with server-sent events. Function calling and tool execution capabilities. JSON schema validation and structured data extraction. Working with images and multimodal inputs. Generate images with multiple providers and formats. Add audio input and output to Chat Completions. Advanced reasoning capabilities with o1 models. Managing stored Chat Completions (OpenAI only). ## SDK Benefits ### Type Safety Both SDKs are fully typed - Python with Pydantic models and TypeScript with native types, providing excellent IDE support and compile-time error checking. ### Error Handling Comprehensive error handling with specific error types and detailed error information in both languages. ### Resource Management Automatic connection pooling and resource cleanup with context manager support (Python) and proper resource management (TypeScript). ### Performance Built-in retry logic, connection reuse, and async support for high-performance applications in both languages. ## Next Steps 1. **[Install the SDK](/sdk/sudo-sdk/installation)** - Get started with installation and setup 2. **[Try Chat Completion](/sdk/sudo-sdk/ai-responses)** - Create your first AI response 3. **[Explore Streaming](/sdk/sudo-sdk/streaming)** - Add real-time capabilities 4. **[Advanced Features](/sdk/sudo-sdk/tool-calling)** - Tool calling, structured output, and more The Sudo SDK follows semantic versioning in both languages. For Python, check the [PyPI page](https://pypi.org/project/sudo-sudo-ai/) and for TypeScript, check the [npm page](https://www.npmjs.com/package/sudo-ai) for the latest release information. **Python**: Compatible with Python 3.9+\ **TypeScript**: Compatible with Node.js 14+ and modern browsers # AI Router Source: https://docs.sudoapp.dev/sdk/sudo-sdk/ai-responses Create AI responses with various models and parameters AI responses are the core functionality of the Sudo platform, allowing you to generate chat completions from a wide variety of models including GPT, Claude, Gemini, and more. ## Basic Usage ### Simple AI Response ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); async function simpleResponse() { const response = await sudo.router.create({ model: "claude-sonnet-4-20250514", messages: [ { role: "user", content: "Hello! How are you?" } ] }); console.log(response.choices[0].message.content); } simpleResponse(); ``` ```python Python theme={null} import os from sudo import Sudo with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: response = client.router.create( model="claude-sonnet-4-20250514", messages=[ {"role": "user", "content": "Hello! How are you?"} ] ) print(response.choices[0].message.content) ``` ### Conversation with System Message ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); async function conversationWithSystem() { const response = await sudo.router.create({ model: "gpt-4o", messages: [ { role: "system", content: "You are a helpful programming assistant specialized in TypeScript." }, { role: "user", content: "How do I create a type-safe object from two arrays?" } ] }); console.log(response.choices[0].message.content); } conversationWithSystem(); ``` ```python Python theme={null} import os from sudo import Sudo with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: response = client.router.create( model="gpt-4o", messages=[ { "role": "system", "content": "You are a helpful programming assistant specialized in Python." }, { "role": "user", "content": "How do I create a dictionary from two lists?" } ] ) print(response.choices[0].message.content) ``` ### Multi-turn Conversation ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; import * as readline from 'readline'; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); async function chatConversation() { // Conversation history const messages = [ { role: "system", content: "You are a helpful assistant." } ]; const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); const askQuestion = (query: string): Promise => new Promise(resolve => rl.question(query, resolve)); console.log("Chat started! Type 'quit' or 'exit' to end."); while (true) { try { // Get user input const userInput = await askQuestion("You: "); if (userInput.toLowerCase() === 'quit' || userInput.toLowerCase() === 'exit') { break; } // Add user message messages.push({ role: "user", content: userInput }); // Get AI response const response = await sudo.router.create({ model: "claude-sonnet-4-20250514", messages: messages }); const aiMessage = response.choices[0].message.content; console.log(`AI: ${aiMessage}`); // Add AI response to conversation history messages.push({ role: "assistant", content: aiMessage }); } catch (error) { console.error("Error:", error); } } rl.close(); } chatConversation(); ``` ```python Python theme={null} import os from sudo import Sudo def chat_conversation(): with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: # Conversation history messages = [ {"role": "system", "content": "You are a helpful assistant."} ] while True: # Get user input user_input = input("You: ") if user_input.lower() in ['quit', 'exit']: break # Add user message messages.append({"role": "user", "content": user_input}) # Get AI response response = client.router.create( model="claude-sonnet-4-20250514", messages=messages ) ai_message = response.choices[0].message.content print(f"AI: {ai_message}") # Add AI response to conversation history messages.append({"role": "assistant", "content": ai_message}) chat_conversation() ``` ## Parameters and Configuration ### Temperature and Randomness ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); async function temperatureExamples() { // Deterministic output (low temperature) const deterministic = await sudo.router.create({ model: "gpt-4o", messages: [{ role: "user", content: "Explain quantum computing" }], temperature: 0.1 // Very focused, consistent responses }); // Creative output (high temperature) const creative = await sudo.router.create({ model: "gpt-4o", messages: [{ role: "user", content: "Write a creative story" }], temperature: 0.9 // More random and creative }); console.log("Deterministic:", deterministic.choices[0].message.content.substring(0, 100)); console.log("Creative:", creative.choices[0].message.content.substring(0, 100)); } temperatureExamples(); ``` ```python Python theme={null} import os from sudo import Sudo with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: # Deterministic output (low temperature) deterministic = client.router.create( model="gpt-4o", messages=[{"role": "user", "content": "Explain quantum computing"}], temperature=0.1 # Very focused, consistent responses ) # Creative output (high temperature) creative = client.router.create( model="gpt-4o", messages=[{"role": "user", "content": "Write a creative story"}], temperature=0.9 # More random and creative ) print("Deterministic:", deterministic.choices[0].message.content[:100]) print("Creative:", creative.choices[0].message.content[:100]) ``` ### Token Limits ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); async function tokenLimitsExample() { const response = await sudo.router.create({ model: "gpt-4o", messages: [{ role: "user", content: "Write a summary of machine learning" }], maxCompletionTokens: 150 // Limit response length }); console.log(`Tokens used: ${response.usage.totalTokens}`); console.log(`Response: ${response.choices[0].message.content}`); } tokenLimitsExample(); ``` ```python Python theme={null} import os from sudo import Sudo with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: response = client.router.create( model="gpt-4o", messages=[{"role": "user", "content": "Write a summary of machine learning"}], max_completion_tokens=150 # Limit response length ) print(f"Tokens used: {response.usage.total_tokens}") print(f"Response: {response.choices[0].message.content}") ``` ### Frequency and Presence Penalties ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); async function penaltiesExample() { const response = await sudo.router.create({ model: "gpt-4o", messages: [{ role: "user", content: "List programming languages" }], frequencyPenalty: 0.5, // Reduce repetition of frequent words presencePenalty: 0.5 // Encourage diverse vocabulary }); console.log(response.choices[0].message.content); } penaltiesExample(); ``` ```python Python theme={null} import os from sudo import Sudo with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: response = client.router.create( model="gpt-4o", messages=[{"role": "user", "content": "List programming languages"}], frequency_penalty=0.5, # Reduce repetition of frequent words presence_penalty=0.5 # Encourage diverse vocabulary ) print(response.choices[0].message.content) ``` ### Stop Sequences ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); async function stopSequencesExample() { const response = await sudo.router.create({ model: "gpt-4o", messages: [{ role: "user", content: "Count from 1 to 10" }], stop: ["5", "---"] // Stop generation at these sequences }); console.log(response.choices[0].message.content); } stopSequencesExample(); ``` ```python Python theme={null} import os from sudo import Sudo with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: response = client.router.create( model="gpt-4o", messages=[{"role": "user", "content": "Count from 1 to 10"}], stop=["5", "---"] # Stop generation at these sequences ) print(response.choices[0].message.content) ``` ## Response Format Options ### Multiple Choices ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); async function multipleChoicesExample() { const response = await sudo.router.create({ model: "gpt-4o", messages: [{ role: "user", content: "Give me a creative business idea" }], n: 3 // Generate 3 different responses }); response.choices.forEach((choice, index) => { console.log(`Idea ${index + 1}: ${choice.message.content}`); console.log("-".repeat(50)); }); } multipleChoicesExample(); ``` ```python Python theme={null} import os from sudo import Sudo with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: response = client.router.create( model="gpt-4o", messages=[{"role": "user", "content": "Give me a creative business idea"}], n=3 # Generate 3 different responses ) for i, choice in enumerate(response.choices, 1): print(f"Idea {i}: {choice.message.content}") print("-" * 50) ``` ### Log Probabilities ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); async function logProbsExample() { const response = await sudo.router.create({ model: "gpt-4o", messages: [{ role: "user", content: "The capital of France is" }], logprobs: true, topLogprobs: 3 // Show top 3 token probabilities }); const choice = response.choices[0]; if (choice.logprobs) { choice.logprobs.content.forEach(tokenInfo => { console.log(`Token: ${tokenInfo.token}`); console.log(`Probability: ${tokenInfo.logprob}`); console.log("Top alternatives:"); tokenInfo.topLogprobs.forEach(alt => { console.log(` ${alt.token}: ${alt.logprob}`); }); }); } } logProbsExample(); ``` ```python Python theme={null} import os from sudo import Sudo with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: response = client.router.create( model="gpt-4o", messages=[{"role": "user", "content": "The capital of France is"}], logprobs=True, top_logprobs=3 # Show top 3 token probabilities ) choice = response.choices[0] if choice.logprobs: for token_info in choice.logprobs.content: print(f"Token: {token_info.token}") print(f"Probability: {token_info.logprob}") print("Top alternatives:") for alt in token_info.top_logprobs: print(f" {alt.token}: {alt.logprob}") ``` ## Metadata and Storage ### Adding Metadata ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); async function metadataExample() { const response = await sudo.router.create({ model: "gpt-4o", messages: [{ role: "user", content: "Explain TypeScript decorators" }], metadata: { userId: "user_123", sessionId: "session_456", feature: "code_explanation", version: "1.0" }, store: true // Store for later retrieval (OpenAI compatible) }); console.log(`Completion ID: ${response.id}`); console.log(`Response: ${response.choices[0].message.content}`); } metadataExample(); ``` ```python Python theme={null} import os from sudo import Sudo with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: response = client.router.create( model="gpt-4o", messages=[{"role": "user", "content": "Explain Python decorators"}], metadata={ "user_id": "user_123", "session_id": "session_456", "feature": "code_explanation", "version": "1.0" }, store=True # Store for later retrieval (OpenAI compatible) ) print(f"Completion ID: {response.id}") print(f"Response: {response.choices[0].message.content}") ``` ## Async Usage ### Basic Async ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); async function asyncChat() { try { const response = await sudo.router.create({ model: "claude-sonnet-4-20250514", messages: [{ role: "user", content: "Hello async world!" }] }); return response.choices[0].message.content; } catch (error) { console.error("Error in async chat:", error); throw error; } } // Usage asyncChat() .then(result => console.log(result)) .catch(error => console.error("Failed:", error)); ``` ```python Python theme={null} import asyncio import os from sudo import Sudo async def async_chat(): async with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: response = await client.router.create_async( model="claude-sonnet-4-20250514", messages=[{"role": "user", "content": "Hello async world!"}] ) return response.choices[0].message.content # Run async function result = asyncio.run(async_chat()) print(result) ``` ### Concurrent Requests ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); async function processMultipleQueries() { const queries = [ "What is machine learning?", "Explain neural networks", "What is deep learning?", "How do transformers work?" ]; try { // Process all queries concurrently const promises = queries.map(query => sudo.router.create({ model: "gpt-4o", messages: [{ role: "user", content: query }], maxCompletionTokens: 100 }) ); const responses = await Promise.all(promises); // Display results responses.forEach((response, index) => { console.log(`Q: ${queries[index]}`); console.log(`A: ${response.choices[0].message.content}`); console.log(`Tokens: ${response.usage.totalTokens}`); console.log("---"); }); } catch (error) { console.error("Error processing queries:", error); } } processMultipleQueries(); ``` ```python Python theme={null} import asyncio import os from sudo import Sudo async def process_multiple_queries(): async with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: queries = [ "What is machine learning?", "Explain neural networks", "What is deep learning?", "How do transformers work?" ] # Create tasks for concurrent execution tasks = [ client.router.create_async( model="gpt-4o", messages=[{"role": "user", "content": query}], max_completion_tokens=100 ) for query in queries ] # Wait for all responses responses = await asyncio.gather(*tasks) # Display results for query, response in zip(queries, responses): print(f"Q: {query}") print(f"A: {response.choices[0].message.content}") print(f"Tokens: {response.usage.total_tokens}") print("---") # Run the async function asyncio.run(process_multiple_queries()) ``` ## Error Handling ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; import * as errors from "sudo-ai/models/errors"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); async function errorHandlingExample() { try { const response = await sudo.router.create({ model: "non-existent-model", // This will cause an error messages: [{ role: "user", content: "Hello" }] }); console.log(response.choices[0].message.content); } catch (error) { if (error instanceof errors.SudoError) { console.log(`SDK Error: ${error.message}`); console.log(`Status Code: ${error.statusCode}`); console.log(`Response Body: ${error.body}`); // Handle specific error types if (error instanceof errors.ErrorResponse) { console.log(`Error Details: ${error.data$.error}`); } } else { console.log(`Unexpected error: ${error}`); } } } errorHandlingExample(); ``` ```python Python theme={null} import os from sudo import Sudo, errors with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: try: response = client.router.create( model="non-existent-model", # This will cause an error messages=[{"role": "user", "content": "Hello"}] ) print(response.choices[0].message.content) except errors.ErrorResponse as e: print(f"API Error: {e.message}") print(f"Status Code: {e.status_code}") print(f"Error Details: {e.data.error}") except errors.SudoError as e: print(f"SDK Error: {e.message}") print(f"Status Code: {e.status_code}") except Exception as e: print(f"Unexpected error: {str(e)}") ``` ## Advanced Examples ### Chat Bot with Context Management ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; import * as readline from 'readline'; interface ChatResponse { response?: string; tokensUsed?: number; model?: string; error?: string; } class ChatBot { private sudo: Sudo; private model: string; private maxHistory: number; private conversationHistory: Array<{role: string; content: string}>; constructor(model: string = "claude-sonnet-4-20250514", maxHistory: number = 10) { this.sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); this.model = model; this.maxHistory = maxHistory; this.conversationHistory = [ { role: "system", content: `You are a helpful assistant. Current time: ${new Date().toISOString()}` } ]; } async chat(message: string): Promise { try { // Add user message this.conversationHistory.push({ role: "user", content: message }); // Trim history if too long if (this.conversationHistory.length > this.maxHistory) { // Keep system message and recent messages this.conversationHistory = [ this.conversationHistory[0] // System message ].concat(this.conversationHistory.slice(-(this.maxHistory - 1))); } const response = await this.sudo.router.create({ model: this.model, messages: this.conversationHistory, temperature: 0.7 }); const aiResponse = response.choices[0].message.content; // Add AI response to history this.conversationHistory.push({ role: "assistant", content: aiResponse }); return { response: aiResponse, tokensUsed: response.usage.totalTokens, model: response.model }; } catch (error) { return { error: `Failed to get response: ${error}` }; } } resetConversation(): void { // Reset the conversation history, keeping only the system message this.conversationHistory = [this.conversationHistory[0]]; } getHistorySummary(): { totalMessages: number; userMessages: number; aiMessages: number } { const userMessages = this.conversationHistory.filter(m => m.role === "user").length; const aiMessages = this.conversationHistory.filter(m => m.role === "assistant").length; return { totalMessages: this.conversationHistory.length, userMessages, aiMessages }; } } // Usage async function runChatBot() { const bot = new ChatBot(); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); const askQuestion = (query: string): Promise => new Promise(resolve => rl.question(query, resolve)); console.log("Chat started! Type 'quit', 'exit', 'reset', or 'summary'"); while (true) { try { const userInput = await askQuestion("You: "); if (userInput.toLowerCase() === 'quit' || userInput.toLowerCase() === 'exit') { break; } else if (userInput.toLowerCase() === 'reset') { bot.resetConversation(); console.log("Conversation reset!"); continue; } else if (userInput.toLowerCase() === 'summary') { const summary = bot.getHistorySummary(); console.log(`Conversation summary: ${JSON.stringify(summary)}`); continue; } const result = await bot.chat(userInput); if (result.error) { console.log(`Error: ${result.error}`); } else { console.log(`AI: ${result.response}`); console.log(`(Tokens: ${result.tokensUsed}, Model: ${result.model})`); } } catch (error) { console.error("Unexpected error:", error); } } rl.close(); } runChatBot(); ``` ```python Python theme={null} import os from datetime import datetime from sudo import Sudo class ChatBot: def __init__(self, model="claude-sonnet-4-20250514", max_history=10): self.client = Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) self.model = model self.max_history = max_history self.conversation_history = [ { "role": "system", "content": f"You are a helpful assistant. Current time: {datetime.now()}" } ] def chat(self, message): """Send a message and get a response""" # Add user message self.conversation_history.append({"role": "user", "content": message}) # Trim history if too long if len(self.conversation_history) > self.max_history: # Keep system message and recent messages self.conversation_history = [ self.conversation_history[0] # System message ] + self.conversation_history[-(self.max_history-1):] try: response = self.client.router.create( model=self.model, messages=self.conversation_history, temperature=0.7 ) ai_response = response.choices[0].message.content # Add AI response to history self.conversation_history.append({"role": "assistant", "content": ai_response}) return { "response": ai_response, "tokens_used": response.usage.total_tokens, "model": response.model } except Exception as e: return {"error": f"Failed to get response: {str(e)}"} def reset_conversation(self): """Reset the conversation history""" self.conversation_history = [self.conversation_history[0]] # Keep system message def get_history_summary(self): """Get a summary of the conversation""" user_messages = len([m for m in self.conversation_history if m["role"] == "user"]) ai_messages = len([m for m in self.conversation_history if m["role"] == "assistant"]) return { "total_messages": len(self.conversation_history), "user_messages": user_messages, "ai_messages": ai_messages } # Usage bot = ChatBot() # Interactive chat while True: user_input = input("You: ") if user_input.lower() in ['quit', 'exit']: break elif user_input.lower() == 'reset': bot.reset_conversation() print("Conversation reset!") continue elif user_input.lower() == 'summary': summary = bot.get_history_summary() print(f"Conversation summary: {summary}") continue result = bot.chat(user_input) if "error" in result: print(f"Error: {result['error']}") else: print(f"AI: {result['response']}") print(f"(Tokens: {result['tokens_used']}, Model: {result['model']})") ``` ## Next Steps Now that you understand AI responses: 1. **[Explore Streaming](/sdk/sudo-sdk/streaming)** - Add real-time streaming responses 2. **[Try Tool Calling](/sdk/sudo-sdk/tool-calling)** - Enable function calling capabilities 3. **[Structured Output](/sdk/sudo-sdk/structured-output)** - Generate JSON and structured data 4. **[Image Input](/sdk/sudo-sdk/image-input)** - Work with multimodal inputs Start with simple use cases and gradually add complexity. Use appropriate models for your needs - faster models for simple tasks, more capable models for complex reasoning. Both Python and TypeScript SDKs offer the same powerful capabilities with language-specific optimizations. # Audio Chat Completions Source: https://docs.sudoapp.dev/sdk/sudo-sdk/audio_chat_completions Add audio input and output to Chat Completions (OpenAI) Models like GPT-4o can handle audio modalities. With Sudo, you can call OpenAI-compatible audio models to produce audio output and optionally send audio input alongside text. Only certain providers currently support audio input/output with Chat Completions in this format (notably OpenAI). Before using audio, confirm your chosen model provider’s API accepts `modalities` and `input_audio` as shown here, and adjust parameters accordingly. ## Audio Output from Text Generate spoken audio from a text prompt using an audio-capable model. ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); async function textToSpeech() { const response = await sudo.router.create({ model: "gpt-4o-audio-preview", modalities: ["text", "audio"], audio: { voice: "alloy", format: "wav" }, messages: [ { role: "user", content: "Is a golden retriever a good family dog?", }, ], }); // The response may include both text and audio. Inspect the structure as providers evolve. console.log("Text:", response.choices[0].message.content); // Optionally check for audio fields if present in your provider’s response shape // console.log("Audio (base64):", response.choices[0].message.audio?.data); } textToSpeech(); ``` ```python Python theme={null} import os from sudo import Sudo with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: response = client.router.create( model="gpt-4o-audio-preview", modalities=["text", "audio"], audio={"voice": "alloy", "format": "wav"}, messages=[ { "role": "user", "content": "Is a golden retriever a good family dog?", } ], ) # The response may include both text and audio. Inspect the structure as providers evolve. print("Text:", response.choices[0].message.content) # Optionally check for audio fields if present in your provider’s response shape # print("Audio (base64):", getattr(response.choices[0].message, "audio", {}).get("data")) ``` ## Audio Input + Text Send user audio together with a text prompt. Encode your audio file as base64 and include it using `type: "input_audio"`. ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; import * as fs from "fs"; import * as path from "path"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); function encodeAudioToBase64(audioPath: string): { data: string; format: string } { const ext = path.extname(audioPath).toLowerCase(); const format = ext.replace(".", "") || "wav"; // e.g. .wav -> wav const audioBuffer = fs.readFileSync(audioPath); return { data: audioBuffer.toString("base64"), format }; } async function analyzeAudioWithText() { const { data, format } = encodeAudioToBase64("path/to/recording.wav"); const response = await sudo.router.create({ model: "gpt-4o-audio-preview", modalities: ["text", "audio"], audio: { voice: "alloy", format: "wav" }, messages: [ { role: "user", content: [ { type: "text", text: "What is in this recording?" }, { type: "input_audio", inputAudio: { data, format, }, }, ], }, ], }); console.log("Text:", response.choices[0].message.content); } analyzeAudioWithText(); ``` ```python Python theme={null} import os import base64 from sudo import Sudo def encode_audio_to_base64(audio_path: str): with open(audio_path, "rb") as f: data = base64.b64encode(f.read()).decode("utf-8") # Infer format from file extension (e.g., .wav -> wav) format = audio_path.split(".")[-1].lower() if "." in audio_path else "wav" return {"data": data, "format": format} with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: audio_b64 = encode_audio_to_base64("path/to/recording.wav") response = client.router.create( model="gpt-4o-audio-preview", modalities=["text", "audio"], audio={"voice": "alloy", "format": "wav"}, messages=[ { "role": "user", "content": [ {"type": "text", "text": "What is in this recording?"}, { "type": "input_audio", "input_audio": { "data": audio_b64["data"], "format": audio_b64["format"], }, }, ], } ], ) print("Text:", response.choices[0].message.content) ``` ## Tips * Prefer lossless or high-quality input formats for best transcription/understanding. * Keep requests small; very long audio can increase latency and cost. * Verify your chosen model supports audio input/output and the requested `format`. # CRUD Operations Source: https://docs.sudoapp.dev/sdk/sudo-sdk/crud-operations Managing stored chat completions (OpenAI only) CRUD operations allow you to store, retrieve, update, and delete OpenAI Chat Completions for analysis, caching, and model improvement. ## Storing Completions ### Basic Storage ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); async function basicStorage() { try { // Create and store a completion const response = await sudo.router.create({ model: "gpt-4o", messages: [ { role: "user", content: "Explain machine learning" } ], store: true, // Enable storage metadata: { userId: "user_123", topic: "education", session: "learning_session_1" } }); const completionId = response.id; console.log(`Stored completion with ID: ${completionId}`); console.log(`Response: ${response.choices[0].message.content}`); } catch (error) { console.error("Storage error:", error); } } basicStorage(); ``` ```python Python theme={null} import os from sudo import Sudo with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: # Create and store a completion response = client.router.create( model="gpt-4o", messages=[ {"role": "user", "content": "Explain machine learning"} ], store=True, # Enable storage metadata={ "user_id": "user_123", "topic": "education", "session": "learning_session_1" } ) completion_id = response.id print(f"Stored completion with ID: {completion_id}") print(f"Response: {response.choices[0].message.content}") ``` ## Retrieving Completions ### List Stored Completions ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); async function listStoredCompletions() { try { // List all stored completions const completions = await sudo.router.listChatCompletions({ limit: 10, order: "desc" // Most recent first }); console.log(`Found ${completions.data.length} stored completions:`); completions.data.forEach(completion => { console.log(`- ID: ${completion.id}`); console.log(` Model: ${completion.model}`); console.log(` Created: ${completion.created}`); if (completion.metadata) { console.log(` Metadata: ${JSON.stringify(completion.metadata)}`); } }); } catch (error) { console.error("List completions error:", error); } } listStoredCompletions(); ``` ```python Python theme={null} import os from sudo import Sudo with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: # List all stored completions completions = client.router.list_chat_completions( limit=10, order="desc" # Most recent first ) print(f"Found {len(completions.data)} stored completions:") for completion in completions.data: print(f"- ID: {completion.id}") print(f" Model: {completion.model}") print(f" Created: {completion.created}") if completion.metadata: print(f" Metadata: {completion.metadata}") ``` ### Filter by Metadata ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); async function filterByMetadata() { try { // Filter completions by metadata const completions = await sudo.router.listChatCompletions({ metadata: { userId: "user_123", topic: "education" }, limit: 5 }); console.log("Education-related completions:"); completions.data.forEach(completion => { console.log(`- ${completion.id}: ${completion.model}`); }); } catch (error) { console.error("Filter by metadata error:", error); } } filterByMetadata(); ``` ```python Python theme={null} import os from sudo import Sudo with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: # Filter completions by metadata completions = client.router.list_chat_completions( metadata={ "user_id": "user_123", "topic": "education" }, limit=5 ) print("Education-related completions:") for completion in completions.data: print(f"- {completion.id}: {completion.model}") ``` ### Get Specific Completion ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); async function getCompletionDetails(completionId: string) { try { // Get completion metadata const completion = await sudo.router.getChatCompletion(completionId); // Get completion messages const messages = await sudo.router.getChatCompletionMessages(completionId); return { completion, messages }; } catch (error) { console.error("Get completion details error:", error); return null; } } // Usage async function completionDetailsExample() { const completionId = "chatcmpl-abc123"; // Replace with actual ID const details = await getCompletionDetails(completionId); if (details) { console.log(`Completion ID: ${details.completion.id}`); console.log(`Model: ${details.completion.model}`); console.log(`Created: ${details.completion.created}`); console.log("\nMessages:"); details.messages.data.forEach(message => { console.log(`- ${message.role}: ${message.content}`); }); } } completionDetailsExample(); ``` ```python Python theme={null} import os from sudo import Sudo def get_completion_details(completion_id): """Get detailed information about a specific completion""" with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: # Get completion metadata completion = client.router.get_chat_completion(completion_id) # Get completion messages messages = client.router.get_chat_completion_messages(completion_id) return { "completion": completion, "messages": messages } # Usage completion_id = "chatcmpl-abc123" # Replace with actual ID details = get_completion_details(completion_id) print(f"Completion ID: {details['completion'].id}") print(f"Model: {details['completion'].model}") print(f"Created: {details['completion'].created}") print("\nMessages:") for message in details['messages'].data: print(f"- {message.role}: {message.content}") ``` ## Updating Completions ### Update Metadata ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); async function updateCompletionMetadata(completionId: string, newMetadata: Record) { try { const updatedCompletion = await sudo.router.updateChatCompletion({ completionId: completionId, metadata: newMetadata }); return updatedCompletion; } catch (error) { console.error("Update completion metadata error:", error); return null; } } // Example: Add rating and feedback async function updateMetadataExample() { const newMetadata = { userId: "user_123", topic: "education", rating: "5", feedback: "very_helpful", reviewed: "true" }; const updated = await updateCompletionMetadata("chatcmpl-abc123", newMetadata); if (updated) { console.log(`Updated completion ${updated.id}`); console.log(`New metadata: ${JSON.stringify(updated.metadata)}`); } } updateMetadataExample(); ``` ```python Python theme={null} import os from sudo import Sudo def update_completion_metadata(completion_id, new_metadata): """Update metadata for a stored completion""" with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: updated_completion = client.router.update_chat_completion( completion_id=completion_id, metadata=new_metadata ) return updated_completion # Example: Add rating and feedback new_metadata = { "user_id": "user_123", "topic": "education", "rating": "5", "feedback": "very_helpful", "reviewed": "true" } updated = update_completion_metadata("chatcmpl-abc123", new_metadata) print(f"Updated completion {updated.id}") print(f"New metadata: {updated.metadata}") ``` ## Deleting Completions ### Delete Single Completion ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); async function deleteCompletion(completionId: string) { try { const result = await sudo.router.deleteChatCompletion(completionId); return result; } catch (error) { console.error("Delete completion error:", error); return null; } } // Delete a completion async function deleteCompletionExample() { const result = await deleteCompletion("chatcmpl-abc123"); if (result) { console.log(`Deletion result: ${JSON.stringify(result)}`); } } deleteCompletionExample(); ``` ```python Python theme={null} import os from sudo import Sudo def delete_completion(completion_id): """Delete a stored completion""" with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: result = client.router.delete_chat_completion(completion_id) return result # Delete a completion result = delete_completion("chatcmpl-abc123") print(f"Deletion result: {result}") ``` CRUD operations are only available for completions created with `store=True`. This feature is designed for OpenAI API compatibility and works with both Python and TypeScript SDKs. ## Summary The Sudo SDK provides comprehensive functionality for building AI-powered applications in both Python and TypeScript: * **System Endpoints**: Monitor API health and discover available models * **Chat Completion**: Generate responses from various AI models with extensive customization * **Streaming**: Real-time response generation for interactive applications * **Tool Calling**: Enable AI models to execute functions and interact with external systems * **Structured Output**: Generate validated JSON responses for reliable data extraction * **Image Input**: Process images and multimodal content with vision-capable models * **Reasoning**: Access advanced reasoning capabilities for complex problem-solving * **CRUD Operations**: Manage stored completions for analysis and improvement Both SDKs are designed for production use with comprehensive error handling, async support, and best practices built-in. Start with basic chat completions and gradually add advanced features as needed. **Resources:** * **Python**: [GitHub Repository](https://github.com/sudoappai/sudo-python) | [PyPI Package](https://pypi.org/project/sudo-ai/) * **TypeScript**: [GitHub Repository](https://github.com/sudoappai/sudo-typescript) | [npm Package](https://www.npmjs.com/package/sudo-ai) # Image Generation Source: https://docs.sudoapp.dev/sdk/sudo-sdk/image-generation Generate images with Sudo SDKs (TypeScript and Python) Use Sudo SDKs to generate images with models like DALL·E, GPT-Image, Imagen, and others. This page shows basic usage and common parameters. Not all parameters are supported across providers. For example, `quality` may be supported by DALL·E 3 but not by Grok or Imagen. Always consult the respective provider’s model documentation to construct the request body correctly. ## Basic Image Generation ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); async function generateBasicImage() { const response = await sudo.router.generateImage({ prompt: "A beautiful sunset over a mountain landscape", model: "dall-e-3", size: "1024x1024", quality: "standard", }); // Response can include URLs or base64, depending on provider/params const first = response.data?.[0]; if (first?.url) { console.log("Image URL:", first.url); } else if (first?.b64Json) { console.log("Image base64 length:", first.b64Json.length); } } generateBasicImage(); ``` ```python Python theme={null} import os from sudo import Sudo with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: response = client.router.generate_image( model="gpt-image-1", prompt="A beautiful sunset over a mountain landscape", n=1, size="1024x1024" ) first = response.data[0] if hasattr(first, 'url') and first.url: print("Image URL:", first.url) elif hasattr(first, 'b64_json') and first.b64_json: print("Image base64 length:", len(first.b64_json)) ``` ## Response Formats Request either a hosted URL or base64 data. ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); async function generateWithFormats() { // URL format const urlResp = await sudo.router.generateImage({ prompt: "A simple geometric pattern", model: "dall-e-2", n: 1, size: "512x512", responseFormat: "url", }); console.log("URL:", urlResp.data?.[0]?.url); // Base64 format const b64Resp = await sudo.router.generateImage({ prompt: "A simple geometric pattern", model: "dall-e-2", n: 1, size: "512x512", responseFormat: "b64_json", }); console.log("b64 length:", b64Resp.data?.[0]?.b64Json?.length); } generateWithFormats(); ``` ```python Python theme={null} import os from sudo import Sudo with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: # URL format url_response = client.router.generate_image( model="dall-e-3", prompt="A simple geometric pattern in blue and white", response_format="url", n=1, size="1024x1024" ) print("URL:", url_response.data[0].url) # Base64 format b64_response = client.router.generate_image( model="dall-e-3", prompt="A simple geometric pattern", response_format="b64_json", n=1, size="512x512" ) print("b64 length:", len(b64_response.data[0].b64_json)) ``` ## Parameters * **model**: The image model to use (e.g., `dall-e-3`, `gpt-image-1`, provider-specific models). See `Overview → Models` for availability. * **prompt**: Text description of the image to generate. * **n**: Number of images to generate. * **size**: Output image size, e.g., `256x256`, `512x512`, `1024x1024` (availability varies by model/provider). * **responseFormat / response\_format**: `url` or `b64_json`. * **quality**: Optional quality preset (e.g., `standard`, `hd`) for providers that support it (often OpenAI/DALL·E only). If a parameter isn’t supported by your chosen model/provider, remove it or adjust to a supported value per provider documentation. ## Notes * Image generation capabilities and parameters vary across providers and model versions. * If a request fails due to unsupported options, check the error message and consult the provider’s docs. # Image Input Source: https://docs.sudoapp.dev/sdk/sudo-sdk/image-input Working with images and multimodal inputs Image input capabilities allow you to send images to vision-enabled AI models for analysis, description, and understanding. ## Basic Image Input ### Image from URL ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); async function analyzeImageFromUrl() { try { const response = await sudo.router.create({ model: "gpt-4o", // Vision-capable model messages: [ { role: "user", content: [ { type: "text", text: "What do you see in this image?" }, { type: "image_url", imageUrl: { url: "https://example.com/image.jpg" } } ] } ] }); console.log(response.choices[0].message.content); } catch (error) { console.error("Image analysis error:", error); } } analyzeImageFromUrl(); ``` ```python Python theme={null} import os from sudo import Sudo with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: response = client.router.create( model="gpt-4o", # Vision-capable model messages=[ { "role": "user", "content": [ { "type": "text", "text": "What do you see in this image?" }, { "type": "image_url", "image_url": { "url": "https://example.com/image.jpg" } } ] } ] ) print(response.choices[0].message.content) ``` ### Image from Local File ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; import * as fs from 'fs'; import * as path from 'path'; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); function encodeImageToBase64(imagePath: string): string { try { const imageBuffer = fs.readFileSync(imagePath); return imageBuffer.toString('base64'); } catch (error) { throw new Error(`Failed to read image file: ${error}`); } } async function analyzeLocalImage(imagePath: string, prompt: string = "Describe this image"): Promise { try { // Encode image to base64 const base64Image = encodeImageToBase64(imagePath); // Determine image type from file extension const ext = path.extname(imagePath).toLowerCase(); const mimeType = ext === '.png' ? 'image/png' : ext === '.webp' ? 'image/webp' : 'image/jpeg'; const response = await sudo.router.create({ model: "gpt-4o", messages: [ { role: "user", content: [ { type: "text", text: prompt }, { type: "image_url", imageUrl: { url: `data:${mimeType};base64,${base64Image}` } } ] } ] }); return response.choices[0].message.content; } catch (error) { console.error("Local image analysis error:", error); return null; } } // Usage async function example() { const description = await analyzeLocalImage("path/to/your/image.jpg", "What objects can you identify in this image?"); if (description) { console.log(description); } } example(); ``` ```python Python theme={null} import os import base64 from sudo import Sudo def encode_image_to_base64(image_path): """Encode local image to base64""" with open(image_path, "rb") as image_file: return base64.b64encode(image_file.read()).decode('utf-8') def analyze_local_image(image_path, prompt="Describe this image"): """Analyze a local image file""" # Encode image to base64 base64_image = encode_image_to_base64(image_path) with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: response = client.router.create( model="gpt-4o", messages=[ { "role": "user", "content": [ { "type": "text", "text": prompt }, { "type": "image_url", "image_url": { "url": f"data:image/jpeg;base64,{base64_image}" } } ] } ] ) return response.choices[0].message.content # Usage description = analyze_local_image("path/to/your/image.jpg", "What objects can you identify in this image?") print(description) ``` ## Advanced Image Analysis ### Multiple Images ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; import * as fs from 'fs'; import * as path from 'path'; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); function encodeImage(imagePath: string): string { const imageBuffer = fs.readFileSync(imagePath); return imageBuffer.toString('base64'); } function getMimeType(imagePath: string): string { const ext = path.extname(imagePath).toLowerCase(); switch (ext) { case '.png': return 'image/png'; case '.webp': return 'image/webp'; case '.gif': return 'image/gif'; default: return 'image/jpeg'; } } async function compareImages(imagePaths: string[], prompt: string = "Compare these images"): Promise { try { // Build content with text and multiple images const content: any[] = [{ type: "text", text: prompt }]; for (const imagePath of imagePaths) { const base64Image = encodeImage(imagePath); const mimeType = getMimeType(imagePath); content.push({ type: "image_url", imageUrl: { url: `data:${mimeType};base64,${base64Image}` } }); } const response = await sudo.router.create({ model: "gpt-4o", messages: [{ role: "user", content: content }] }); return response.choices[0].message.content; } catch (error) { console.error("Image comparison error:", error); return null; } } // Compare two images async function imageComparisonExample() { const comparison = await compareImages( ["image1.jpg", "image2.jpg"], "What are the main differences between these two images?" ); if (comparison) { console.log(comparison); } } imageComparisonExample(); ``` ```python Python theme={null} import os import base64 from sudo import Sudo def compare_images(image_paths, prompt="Compare these images"): """Compare multiple images""" def encode_image(path): with open(path, "rb") as f: return base64.b64encode(f.read()).decode('utf-8') # Build content with text and multiple images content = [{"type": "text", "text": prompt}] for i, path in enumerate(image_paths): base64_image = encode_image(path) content.append({ "type": "image_url", "image_url": { "url": f"data:image/jpeg;base64,{base64_image}" } }) with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: response = client.router.create( model="gpt-4o", messages=[{"role": "user", "content": content}] ) return response.choices[0].message.content # Compare two images comparison = compare_images( ["image1.jpg", "image2.jpg"], "What are the main differences between these two images?" ) print(comparison) ``` ## Next Steps 1. **[Reasoning](/sdk/sudo-sdk/reasoning)** - Advanced reasoning capabilities 2. **[CRUD Operations](/sdk/sudo-sdk/crud-operations)** - Manage stored completions Image input requires vision-capable models like GPT-4o, Claude Sonnet-4, or Gemini Pro Vision. Ensure your images are in supported formats (JPEG, PNG, WebP). Both TypeScript and Python SDKs provide comprehensive support for image analysis with proper error handling and type safety. # Installation & Setup Source: https://docs.sudoapp.dev/sdk/sudo-sdk/installation Install and configure the Sudo SDK ## Installation The Sudo SDK is available for both Python and TypeScript/JavaScript. Choose your preferred language and package manager below. ```bash npm theme={null} npm add sudo-ai ``` ```bash pnpm theme={null} pnpm add sudo-ai ``` ```bash yarn theme={null} yarn add sudo-ai zod # Note that Yarn does not install peer dependencies automatically. You will need # to install zod as shown above. ``` ```bash bun theme={null} bun add sudo-ai ``` ```bash pip theme={null} pip install sudo-ai ``` ```bash poetry theme={null} poetry add sudo-ai ``` ```bash uv theme={null} uv add sudo-ai ``` **Python**: Requires Python 3.9 or later\ **TypeScript/JavaScript**: Requires Node.js 14+ and supports both CommonJS and ES Modules ## Authentication The SDK uses API key authentication. You can obtain your API key from the [Sudo Developer Portal](https://sudoapp.dev/dev/login). ### Environment Variable (Recommended) Set your API key as an environment variable: ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); // Your code here ``` ```python Python theme={null} import os from sudo import Sudo with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: # Your code here pass ``` ### Direct Configuration Alternatively, you can pass the API key directly: ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: "your-api-key-here", }); // Your code here ``` ```python Python theme={null} from sudo import Sudo with Sudo( server_url="https://sudoapp.dev/api", api_key="your-api-key-here", ) as client: # Your code here pass ``` Never hardcode your API key in your source code, especially in code that will be committed to version control. Always use environment variables or secure configuration management. ## Basic Configuration ### Server URL By default, the SDK points to the production Sudo API. You can customize this: ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; // Production (default) const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: "your-api-key" }); // Custom endpoint const customSudo = new Sudo({ serverURL: "https://your-custom-endpoint.com/api", apiKey: "your-api-key" }); ``` ```python Python theme={null} from sudo import Sudo # Production (default) client = Sudo( server_url="https://sudoapp.dev/api", api_key="your-api-key" ) # Custom endpoint client = Sudo( server_url="https://your-custom-endpoint.com/api", api_key="your-api-key" ) ``` ### Retry Configuration Configure retry behavior for failed requests: ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: "your-api-key", retryConfig: { strategy: "backoff", backoff: { initialInterval: 1, maxInterval: 50, exponent: 1.1, maxElapsedTime: 100 }, retryConnectionErrors: false } }); // Client will use custom retry configuration ``` ```python Python theme={null} from sudo import Sudo from sudo.utils import BackoffStrategy, RetryConfig retry_config = RetryConfig( strategy="backoff", backoff=BackoffStrategy( initial_interval=1, max_interval=50, exponent=1.1, max_elapsed_time=100 ), retry_connection_errors=False ) with Sudo( server_url="https://sudoapp.dev/api", api_key="your-api-key", retry_config=retry_config ) as client: # Client will use custom retry configuration pass ``` ### Custom HTTP Client For advanced use cases, you can provide a custom HTTP client: ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; import { HTTPClient } from "sudo-ai/lib/http"; const httpClient = new HTTPClient({ fetcher: (request) => { return fetch(request); } }); httpClient.addHook("beforeRequest", (request) => { const nextRequest = new Request(request, { signal: request.signal || AbortSignal.timeout(5000) }); nextRequest.headers.set("x-custom-header", "value"); return nextRequest; }); const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: "your-api-key", httpClient }); ``` ```python Python theme={null} from sudo import Sudo import httpx # Custom headers for all requests http_client = httpx.Client(headers={"x-custom-header": "value"}) client = Sudo( server_url="https://sudoapp.dev/api", api_key="your-api-key", client=http_client ) ``` ## Async Support Both SDKs support asynchronous operations: ### Async/Await ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); async function main() { try { const result = await sudo.system.healthCheck(); console.log(result); } catch (error) { console.error("Error:", error); } } main(); ``` ```python Python theme={null} import asyncio import os from sudo import Sudo async def main(): async with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: response = await client.system.health_check_async() print(response) asyncio.run(main()) ``` ### Synchronous Usage (Python Only) ```python theme={null} import os from sudo import Sudo with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: response = client.system.health_check() print(response) ``` ## Error Handling Both SDKs provide comprehensive error handling: ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; import * as errors from "sudo-ai/models/errors"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); try { const result = await sudo.system.getSupportedModels(); console.log(result); } catch (error) { if (error instanceof errors.SudoError) { console.log(`SDK Error: ${error.message}`); console.log(`Status Code: ${error.statusCode}`); if (error instanceof errors.ErrorResponse) { console.log(`Error Details: ${error.data$.error}`); } } } ``` ```python Python theme={null} import os from sudo import Sudo, errors with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: try: response = client.system.get_supported_models() print(response) except errors.ErrorResponse as e: print(f"API Error: {e.message}") print(f"Status Code: {e.status_code}") print(f"Error Details: {e.data.error}") except errors.SudoError as e: print(f"SDK Error: {e.message}") print(f"Status Code: {e.status_code}") ``` ## Debugging Enable debug logging to troubleshoot issues: ### Using Environment Variable ```bash theme={null} export SUDO_DEBUG=true ``` ### Language-Specific Debug Configuration ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", debugLogger: console }); // Warning: This will reveal secrets like API tokens in console output // Only use during local development ``` ```python Python theme={null} import logging from sudo import Sudo logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger("sudo") client = Sudo( server_url="https://sudoapp.dev/api", api_key="your-api-key", debug_logger=logger ) ``` ## IDE Support ### VS Code Both SDKs work well with VS Code out of the box. For enhanced type checking: **TypeScript:** ```json theme={null} { "typescript.preferences.includePackageJsonAutoImports": "on" } ``` **Python:** ```json theme={null} { "python.analysis.typeCheckingMode": "strict" } ``` ### Other IDEs **PyCharm (Python):** * Install the [PyCharm Pydantic Plugin](https://docs.pydantic.dev/latest/integrations/pycharm/) * Enable Pydantic support in project settings **WebStorm (TypeScript):** * TypeScript support is built-in * Enable TypeScript language service ## Next Steps Now that you have the SDK installed and configured: 1. **[Try System Endpoints](/sdk/sudo-sdk/system-endpoints)** - Test your setup with health checks 2. **[Create AI Responses](/sdk/sudo-sdk/ai-responses)** - Start building AI-powered features 3. **[Explore Streaming](/sdk/sudo-sdk/streaming)** - Add real-time capabilities Both SDKs follow semantic versioning. Pin to a specific version in production to ensure stability: **Python:** ```bash theme={null} pip install sudo-ai==0.1.0 ``` **TypeScript:** ```bash theme={null} npm install sudo-ai@0.1.1 ``` # Reasoning Source: https://docs.sudoapp.dev/sdk/sudo-sdk/reasoning Advanced reasoning capabilities The reasoning capabilities in Sudo allow you to access advanced reasoning models like o3 for complex problem-solving tasks. ## Basic Reasoning `reasoning_effort` parameter is mainly supported for OpenAI models. While other providers have reasoning models as well, not all providers support `reasoning_effort` ### Simple Reasoning Task ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); async function simpleReasoningTask() { try { const response = await sudo.router.create({ model: "o3", // Reasoning model messages: [ { role: "user", content: "Solve this step by step: If a train travels 120 km in 2 hours, and then 180 km in 3 hours, what is its average speed for the entire journey?" } ] }); console.log("Reasoning Response:"); console.log(response.choices[0].message.content); } catch (error) { console.error("Reasoning error:", error); } } simpleReasoningTask(); ``` ```python Python theme={null} import os from sudo import Sudo with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: response = client.router.create( model="o3", # Reasoning model messages=[ { "role": "user", "content": "Solve this step by step: If a train travels 120 km in 2 hours, and then 180 km in 3 hours, what is its average speed for the entire journey?" } ] ) print("Reasoning Response:") print(response.choices[0].message.content) ``` ### Reasoning Effort Levels (OpenAI models) ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); async function solveWithDifferentEfforts(problem: string): Promise { // Effort levels to control reasoning depth const efforts: Array<"low" | "medium" | "high"> = ["low", "medium", "high"]; try { for (const effort of efforts) { console.log(`\n--- Reasoning Effort: ${effort.toUpperCase()} ---`); const response = await sudo.router.create({ model: "o3", messages: [ { role: "user", content: problem } ], reasoningEffort: effort }); console.log(response.choices[0].message.content); // Show token usage for different efforts if (response.usage) { console.log(`Tokens used: ${response.usage.totalTokens}`); } } } catch (error) { console.error("Reasoning with efforts error:", error); } } // Example complex problem const problem = ` A company has 3 departments. Department A has 15 employees with an average salary of $60,000. Department B has 20 employees with an average salary of $75,000. Department C has 10 employees with an average salary of $90,000. If the company wants to give everyone a 8% raise, but needs to keep the total payroll increase under $50,000, what should they do? `; solveWithDifferentEfforts(problem); ``` ```python Python theme={null} import os from sudo import Sudo def solve_with_different_efforts(problem): """Solve the same problem with different reasoning efforts""" efforts = ["low", "medium", "high"] # Effort levels to control reasoning depth with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: for effort in efforts: print(f"\n--- Reasoning Effort: {effort.upper()} ---") response = client.router.create( model="o3", messages=[ {"role": "user", "content": problem} ], reasoning_effort=effort ) print(response.choices[0].message.content) # Show token usage for different efforts if response.usage: print(f"Tokens used: {response.usage.total_tokens}") # Example complex problem problem = """ A company has 3 departments. Department A has 15 employees with an average salary of $60,000. Department B has 20 employees with an average salary of $75,000. Department C has 10 employees with an average salary of $90,000. If the company wants to give everyone a 8% raise, but needs to keep the total payroll increase under $50,000, what should they do? """ solve_with_different_efforts(problem) ``` ## Next Steps 1. **[CRUD Operations](/sdk/sudo-sdk/crud-operations)** - Manage stored completions Reasoning models like o3 excel at complex problem-solving, mathematical reasoning, and multi-step analysis. Use higher reasoning effort levels for more complex problems, but be aware they consume more tokens. Both TypeScript and Python SDKs provide full support for reasoning capabilities with proper error handling. # Streaming Source: https://docs.sudoapp.dev/sdk/sudo-sdk/streaming Real-time streaming responses with server-sent events Streaming allows you to receive AI responses in real-time as they're generated, providing a better user experience for long-form content generation and interactive applications. ## Basic Streaming ### Simple Streaming Example ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); async function simpleStreaming() { try { // Create a streaming response const stream = await sudo.router.createStreaming({ model: "claude-sonnet-4-20250514", messages: [ { role: "user", content: "Write a short story about a robot" } ] }); // Process the stream console.log("AI Response:"); for await (const chunk of stream) { if (chunk.data?.choices) { for (const choice of chunk.data.choices) { if (choice.delta?.content) { process.stdout.write(choice.delta.content); } } } } console.log(); // New line at the end } catch (error) { console.error("Streaming error:", error); } } simpleStreaming(); ``` ```python Python theme={null} import os from sudo import Sudo with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: # Create a streaming response stream = client.router.create_streaming( model="claude-sonnet-4-20250514", messages=[ {"role": "user", "content": "Write a short story about a robot"} ] ) # Process the stream print("AI Response:") with stream as event_stream: for chunk in event_stream: if chunk.data and chunk.data.choices: for choice in chunk.data.choices: if choice.delta and choice.delta.content: print(choice.delta.content, end="", flush=True) print() # New line at the end ``` ## Stream Event Processing ### Detailed Event Handling ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); async function detailedStreamProcessing() { try { const stream = await sudo.router.createStreaming({ model: "gpt-4o", messages: [ { role: "user", content: "Explain machine learning algorithms" } ], streamOptions: { includeUsage: true } // Include usage information }); let fullResponse = ""; let totalTokens = 0; for await (const chunk of stream) { // Check for data if (chunk.data) { // Process choices if (chunk.data.choices) { for (const choice of chunk.data.choices) { // Content delta if (choice.delta?.content) { const content = choice.delta.content; process.stdout.write(content); fullResponse += content; } // Finish reason if (choice.finishReason) { console.log(`\n[Finished: ${choice.finishReason}]`); } } } // Usage information (if available) if (chunk.data.usage) { totalTokens = chunk.data.usage.totalTokens; console.log(`\n[Tokens used: ${totalTokens}]`); } } } return { content: fullResponse, tokens: totalTokens }; } catch (error) { console.error("Streaming error:", error); return null; } } detailedStreamProcessing().then(result => { if (result) { console.log(`\nCompleted. Total length: ${result.content.length} chars, ${result.tokens} tokens`); } }); ``` ```python Python theme={null} import os import json from sudo import Sudo def detailed_stream_processing(): with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: stream = client.router.create_streaming( model="gpt-4o", messages=[ {"role": "user", "content": "Explain machine learning algorithms"} ], stream_options={"include_usage": True} # Include usage information ) full_response = "" total_tokens = 0 with stream as event_stream: for chunk in event_stream: # Check for data if chunk.data: # Process choices if chunk.data.choices: for choice in chunk.data.choices: # Content delta if choice.delta and choice.delta.content: content = choice.delta.content print(content, end="", flush=True) full_response += content # Finish reason if choice.finish_reason: print(f"\n[Finished: {choice.finish_reason}]") # Usage information (if available) if chunk.data.usage: total_tokens = chunk.data.usage.total_tokens print(f"\n[Tokens used: {total_tokens}]") return { "content": full_response, "tokens": total_tokens } result = detailed_stream_processing() print(f"\nCompleted. Total length: {len(result['content'])} chars, {result['tokens']} tokens") ``` ### Handling Different Event Types ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); async function comprehensiveStreamHandler() { try { const stream = await sudo.router.createStreaming({ model: "gpt-4o", messages: [{ role: "user", content: "Write a poem about programming" }] }); for await (const chunk of stream) { if (chunk.data) { // Model information if (chunk.data.model) { console.log(`[Model: ${chunk.data.model}]`); } // Process each choice if (chunk.data.choices) { chunk.data.choices.forEach((choice, i) => { if (choice.delta) { // Role information if (choice.delta.role) { console.log(`\n[Role: ${choice.delta.role}]`); } // Content if (choice.delta.content) { process.stdout.write(choice.delta.content); } // Tool calls (if any) if (choice.delta.toolCalls) { console.log(`\n[Tool calls: ${JSON.stringify(choice.delta.toolCalls)}]`); } } // Finish information if (choice.finishReason) { console.log(`\n[Choice ${i} finished: ${choice.finishReason}]`); } }); } } } } catch (error) { console.error("Streaming error:", error); } } comprehensiveStreamHandler(); ``` ```python Python theme={null} import os from sudo import Sudo def comprehensive_stream_handler(): with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: stream = client.router.create_streaming( model="gpt-4o", messages=[{"role": "user", "content": "Write a poem about programming"}] ) with stream as event_stream: for chunk in event_stream: if chunk.data: # Model information if hasattr(chunk.data, 'model') and chunk.data.model: print(f"[Model: {chunk.data.model}]") # Process each choice if chunk.data.choices: for i, choice in enumerate(chunk.data.choices): if choice.delta: # Role information if choice.delta.role: print(f"\n[Role: {choice.delta.role}]") # Content if choice.delta.content: print(choice.delta.content, end="", flush=True) # Tool calls (if any) if choice.delta.tool_calls: print(f"\n[Tool calls: {choice.delta.tool_calls}]") # Finish information if choice.finish_reason: print(f"\n[Choice {i} finished: {choice.finish_reason}]") comprehensive_stream_handler() ``` ## Async Streaming ### Basic Python Async Streaming ```python Python theme={null} import asyncio import os from sudo import Sudo async def async_stream_chat(): async with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: stream = await client.router.create_streaming_async( model="claude-sonnet-4-20250514", messages=[ {"role": "user", "content": "Explain the benefits of async programming"} ] ) print("Async streaming response:") full_response = "" async with stream as event_stream: async for chunk in event_stream: if chunk.data and chunk.data.choices: for choice in chunk.data.choices: if choice.delta and choice.delta.content: content = choice.delta.content print(content, end="", flush=True) full_response += content print() # New line return full_response # Run async streaming response = asyncio.run(async_stream_chat()) print(f"Response length: {len(response)} characters") ``` ### Concurrent Streaming ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); async function streamSingleQuery(query: string, queryId: number): Promise { try { console.log(`\n[Query ${queryId}] Starting: ${query}`); const stream = await sudo.router.createStreaming({ model: "gpt-4o-mini", messages: [{ role: "user", content: query }] }); let response = ""; for await (const chunk of stream) { if (chunk.data?.choices) { for (const choice of chunk.data.choices) { if (choice.delta?.content) { const content = choice.delta.content; response += content; // Print with query ID prefix process.stdout.write(`[Q${queryId}] ${content}`); } } } } console.log(`\n[Query ${queryId}] Completed`); return response; } catch (error) { console.error(`[Query ${queryId}] Error:`, error); return ""; } } async function streamMultipleQueries(): Promise { try { const queries = [ "What is TypeScript?", "Explain JavaScript", "What is machine learning?" ]; // Start all streams concurrently const promises = queries.map((query, index) => streamSingleQuery(query, index + 1) ); const responses = await Promise.all(promises); console.log("\n\nAll queries completed!"); responses.forEach((response, index) => { console.log(`Query ${index + 1} length: ${response.length} characters`); }); } catch (error) { console.error("Concurrent streaming error:", error); } } streamMultipleQueries(); ``` ```python Python theme={null} import asyncio import os from sudo import Sudo async def stream_multiple_queries(): """Stream responses to multiple queries concurrently""" async def stream_single_query(client, query, query_id): """Stream a single query""" print(f"\n[Query {query_id}] Starting: {query}") stream = await client.router.create_streaming_async( model="gpt-4o-mini", messages=[{"role": "user", "content": query}] ) response = "" async with stream as event_stream: async for chunk in event_stream: if chunk.data and chunk.data.choices: for choice in chunk.data.choices: if choice.delta and choice.delta.content: content = choice.delta.content response += content # Print with query ID prefix print(f"[Q{query_id}] {content}", end="", flush=True) print(f"\n[Query {query_id}] Completed") return response async with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: queries = [ "What is Python?", "Explain JavaScript", "What is machine learning?" ] # Start all streams concurrently tasks = [ stream_single_query(client, query, i+1) for i, query in enumerate(queries) ] responses = await asyncio.gather(*tasks) print("\n\nAll queries completed!") for i, response in enumerate(responses): print(f"Query {i+1} length: {len(response)} characters") asyncio.run(stream_multiple_queries()) ``` ## Error Handling and Recovery ### Robust Streaming with Retry ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); async function robustStreamingWithRetry( query: string, maxRetries: number = 3, backoffMs: number = 1000 ): Promise { for (let attempt = 1; attempt <= maxRetries; attempt++) { try { console.log(`Attempt ${attempt}: Starting stream for "${query}"`); const stream = await sudo.router.createStreaming({ model: "gpt-4o", messages: [{ role: "user", content: query }], maxCompletionTokens: 150 }); let response = ""; let lastChunkTime = Date.now(); const timeoutMs = 30000; // 30 second timeout for await (const chunk of stream) { lastChunkTime = Date.now(); if (chunk.data?.choices) { for (const choice of chunk.data.choices) { if (choice.delta?.content) { const content = choice.delta.content; response += content; process.stdout.write(content); } if (choice.finishReason) { console.log(`\nStream completed with reason: ${choice.finishReason}`); return response; } } } // Check for timeout if (Date.now() - lastChunkTime > timeoutMs) { throw new Error("Stream timeout - no data received"); } } return response; } catch (error) { console.error(`\nAttempt ${attempt} failed:`, error); if (attempt === maxRetries) { console.error("All retry attempts exhausted"); return null; } // Exponential backoff const delay = backoffMs * Math.pow(2, attempt - 1); console.log(`Retrying in ${delay}ms...`); await new Promise(resolve => setTimeout(resolve, delay)); } } return null; } // Usage async function robustStreamingExample() { const response = await robustStreamingWithRetry( "Explain the theory of relativity in simple terms" ); if (response) { console.log(`\nSuccessfully received response: ${response.length} characters`); } else { console.log("Failed to get response after all retry attempts"); } } robustStreamingExample(); ``` ```python Python theme={null} import os import asyncio import time from sudo import Sudo async def robust_streaming_with_retry(query, max_retries=3, backoff_seconds=1): """Stream with automatic retry and exponential backoff""" for attempt in range(1, max_retries + 1): try: print(f"Attempt {attempt}: Starting stream for '{query}'") async with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: stream = await client.router.create_streaming_async( model="gpt-4o", messages=[{"role": "user", "content": query}], max_completion_tokens=150 ) response = "" last_chunk_time = time.time() timeout_seconds = 30 # 30 second timeout async with stream as event_stream: async for chunk in event_stream: last_chunk_time = time.time() if chunk.data and chunk.data.choices: for choice in chunk.data.choices: if choice.delta and choice.delta.content: content = choice.delta.content response += content print(content, end="", flush=True) if choice.finish_reason: print(f"\nStream completed with reason: {choice.finish_reason}") return response # Check for timeout if time.time() - last_chunk_time > timeout_seconds: raise Exception("Stream timeout - no data received") return response except Exception as e: print(f"\nAttempt {attempt} failed: {e}") if attempt == max_retries: print("All retry attempts exhausted") return None # Exponential backoff delay = backoff_seconds * (2 ** (attempt - 1)) print(f"Retrying in {delay} seconds...") await asyncio.sleep(delay) return None # Usage response = asyncio.run(robust_streaming_with_retry( "Explain the theory of relativity in simple terms" )) if response: print(f"\nSuccessfully received response: {len(response)} characters") else: print("Failed to get response after all retry attempts") ``` ## Best Practices ### Optimized Streaming Setup ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; class OptimizedStreaming { private sudo: Sudo; private currentStream: any = null; private isShuttingDown = false; constructor() { this.sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); this.setupSignalHandlers(); } private setupSignalHandlers(): void { // Handle graceful shutdown process.on('SIGINT', () => this.signalHandler('SIGINT')); process.on('SIGTERM', () => this.signalHandler('SIGTERM')); } private signalHandler(signal: string): void { if (this.isShuttingDown) return; console.log(`\nReceived ${signal}. Shutting down gracefully...`); this.isShuttingDown = true; if (this.currentStream) { try { // Note: Actual stream cancellation depends on the specific implementation this.currentStream = null; } catch (error) { console.error("Error during stream cleanup:", error); } } process.exit(0); } async streamWithContext(message: string, model: string = "gpt-4o"): Promise { if (this.isShuttingDown) { console.log("Cannot start stream: shutting down"); return null; } try { const stream = await this.sudo.router.createStreaming({ model, messages: [{ role: "user", content: message }], streamOptions: { includeUsage: true } }); this.currentStream = stream; const responseParts: string[] = []; for await (const chunk of stream) { if (this.isShuttingDown) { console.log("\nStreaming interrupted by shutdown signal"); break; } if (chunk.data?.choices) { for (const choice of chunk.data.choices) { if (choice.delta?.content) { const content = choice.delta.content; responseParts.push(content); process.stdout.write(content); } } } } console.log(); return responseParts.join(''); } catch (error) { if (error instanceof Error && error.name === 'AbortError') { console.log("\nStreaming interrupted by user"); return null; } console.error(`\nStreaming error: ${error}`); return null; } finally { this.currentStream = null; } } // Graceful shutdown method async shutdown(): Promise { this.isShuttingDown = true; if (this.currentStream) { this.currentStream = null; } } } // Usage async function optimizedStreamingExample() { const streamer = new OptimizedStreaming(); try { const result = await streamer.streamWithContext( "Write a comprehensive guide to TypeScript decorators" ); if (result) { console.log(`\nStreaming completed. Response length: ${result.length} characters`); } } catch (error) { console.error("Streaming example error:", error); } } optimizedStreamingExample(); ``` ```python Python theme={null} import os import signal import sys from sudo import Sudo class OptimizedStreaming: def __init__(self): self.client = None self.current_stream = None self.setup_signal_handlers() def setup_signal_handlers(self): """Handle graceful shutdown""" signal.signal(signal.SIGINT, self.signal_handler) signal.signal(signal.SIGTERM, self.signal_handler) def signal_handler(self, sig, frame): """Clean up on signal""" print("\nShutting down gracefully...") if self.current_stream: try: self.current_stream.close() except: pass sys.exit(0) def stream_with_context(self, message, model="gpt-4o"): """Stream with proper context management""" try: with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: self.client = client stream = client.router.create_streaming( model=model, messages=[{"role": "user", "content": message}], stream_options={"include_usage": True} ) self.current_stream = stream response_parts = [] with stream as event_stream: for chunk in event_stream: if chunk.data and chunk.data.choices: for choice in chunk.data.choices: if choice.delta and choice.delta.content: content = choice.delta.content response_parts.append(content) print(content, end="", flush=True) print() return ''.join(response_parts) except KeyboardInterrupt: print("\nStreaming interrupted by user") return None except Exception as e: print(f"\nStreaming error: {e}") return None finally: self.current_stream = None # Usage streamer = OptimizedStreaming() result = streamer.stream_with_context( "Write a comprehensive guide to Python decorators" ) if result: print(f"\nStreaming completed. Response length: {len(result)} characters") ``` ## Next Steps Now that you understand streaming: 1. **[Try Tool Calling](/sdk/sudo-sdk/tool-calling)** - Combine streaming with function calls 2. **[Structured Output](/sdk/sudo-sdk/structured-output)** - Generate structured data 3. **[CRUD Operations](/sdk/sudo-sdk/crud-operations)** - Manage stored completions Use streaming for long-form content generation and interactive applications. Remember to implement proper error handling and user interruption capabilities for the best user experience. Both TypeScript and Python SDKs provide excellent streaming support with robust error handling and async capabilities. # Structured Output Source: https://docs.sudoapp.dev/sdk/sudo-sdk/structured-output JSON schema validation and structured data extraction Structured output ensures AI responses conform to specific JSON schemas, enabling reliable data extraction and integration with applications. ## Basic Structured Output ### Simple JSON Schema ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); // Define a JSON schema for a person const personSchema = { type: "object", properties: { name: { type: "string" }, age: { type: "integer" }, email: { type: "string", format: "email" }, skills: { type: "array", items: { type: "string" } } }, required: ["name", "age", "email"] }; // Define TypeScript interface for type safety interface Person { name: string; age: number; email: string; skills: string[]; } async function basicStructuredOutput() { try { const response = await sudo.router.create({ model: "gpt-4o", messages: [ { role: "user", content: "Create a person profile for a software engineer named Alice" } ], responseFormat: { type: "json_schema", jsonSchema: { name: "person", schema: personSchema, strict: true } } }); // Parse the structured response const personData: Person = JSON.parse(response.choices[0].message.content); console.log(`Name: ${personData.name}`); console.log(`Age: ${personData.age}`); console.log(`Email: ${personData.email}`); console.log(`Skills: ${personData.skills.join(', ')}`); } catch (error) { console.error("Structured output error:", error); } } basicStructuredOutput(); ``` ```python Python theme={null} import os import json from sudo import Sudo # Define a JSON schema for a person person_schema = { "type": "object", "properties": { "name": {"type": "string"}, "age": {"type": "integer"}, "email": {"type": "string", "format": "email"}, "skills": { "type": "array", "items": {"type": "string"} } }, "required": ["name", "age", "email"] } with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: response = client.router.create( model="gpt-4o", messages=[ { "role": "user", "content": "Create a person profile for a software engineer named Alice" } ], response_format={ "type": "json_schema", "json_schema": { "name": "person", "schema": person_schema, "strict": True } } ) # Parse the structured response person_data = json.loads(response.choices[0].message.content) print(f"Name: {person_data['name']}") print(f"Age: {person_data['age']}") print(f"Email: {person_data['email']}") print(f"Skills: {', '.join(person_data['skills'])}") ``` ## Complex Data Extraction ### Product Information Extraction ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); // Complex schema for product data const productSchema = { type: "object", properties: { products: { type: "array", items: { type: "object", properties: { name: { type: "string" }, price: { type: "number" }, category: { type: "string" }, features: { type: "array", items: { type: "string" } }, rating: { type: "number", minimum: 0, maximum: 5 }, inStock: { type: "boolean" } }, required: ["name", "price", "category", "inStock"] } }, totalCount: { type: "integer" }, averagePrice: { type: "number" } }, required: ["products", "totalCount"] }; // Define TypeScript interfaces for type safety interface Product { name: string; price: number; category: string; features?: string[]; rating?: number; inStock: boolean; } interface ProductExtraction { products: Product[]; totalCount: number; averagePrice?: number; } async function extractProductData(text: string): Promise { try { const response = await sudo.router.create({ model: "gpt-4o", messages: [ { role: "system", content: "Extract product information from the given text and format it according to the specified schema." }, { role: "user", content: `Extract product data from this text: ${text}` } ], responseFormat: { type: "json_schema", jsonSchema: { name: "product_extraction", schema: productSchema, strict: true } } }); return JSON.parse(response.choices[0].message.content) as ProductExtraction; } catch (error) { console.error("Product extraction error:", error); return null; } } // Example usage async function productExtractionExample() { const productText = ` We have several laptops available: 1. MacBook Pro 16" - $2499, excellent performance, 16GB RAM, M2 chip, in stock 2. Dell XPS 13 - $1299, ultraportable, 8GB RAM, Intel i7, limited stock 3. ThinkPad X1 - $1899, business laptop, 16GB RAM, excellent keyboard, in stock `; const result = await extractProductData(productText); if (result) { console.log(`Found ${result.totalCount} products:`); result.products.forEach(product => { console.log(`- ${product.name}: $${product.price} (${product.inStock ? 'In Stock' : 'Limited Stock'})`); }); } } productExtractionExample(); ``` ```python Python theme={null} import os import json from sudo import Sudo # Complex schema for product data product_schema = { "type": "object", "properties": { "products": { "type": "array", "items": { "type": "object", "properties": { "name": {"type": "string"}, "price": {"type": "number"}, "category": {"type": "string"}, "features": { "type": "array", "items": {"type": "string"} }, "rating": {"type": "number", "minimum": 0, "maximum": 5}, "in_stock": {"type": "boolean"} }, "required": ["name", "price", "category", "in_stock"] } }, "total_count": {"type": "integer"}, "average_price": {"type": "number"} }, "required": ["products", "total_count"] } def extract_product_data(text): """Extract structured product data from text""" with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: response = client.router.create( model="gpt-4o", messages=[ { "role": "system", "content": "Extract product information from the given text and format it according to the specified schema." }, { "role": "user", "content": f"Extract product data from this text: {text}" } ], response_format={ "type": "json_schema", "json_schema": { "name": "product_extraction", "schema": product_schema, "strict": True } } ) return json.loads(response.choices[0].message.content) # Example usage product_text = """ We have several laptops available: 1. MacBook Pro 16" - $2499, excellent performance, 16GB RAM, M2 chip, in stock 2. Dell XPS 13 - $1299, ultraportable, 8GB RAM, Intel i7, limited stock 3. ThinkPad X1 - $1899, business laptop, 16GB RAM, excellent keyboard, in stock """ result = extract_product_data(product_text) print(f"Found {result['total_count']} products:") for product in result['products']: print(f"- {product['name']}: ${product['price']} ({'In Stock' if product['in_stock'] else 'Limited Stock'})") ``` ## Next Steps 1. **[Image Input](/sdk/sudo-sdk/image-input)** - Work with multimodal inputs 2. **[Reasoning](/sdk/sudo-sdk/reasoning)** - Advanced reasoning capabilities 3. **[CRUD Operations](/sdk/sudo-sdk/crud-operations)** - Manage stored completions Structured output works best with models that support JSON schema validation like GPT-4o, Claude Sonnet-4, and other recent models. Both TypeScript and Python SDKs provide excellent type safety and validation capabilities for structured data extraction. # System Endpoints Source: https://docs.sudoapp.dev/sdk/sudo-sdk/system-endpoints Health checks and model information endpoints The system endpoints provide information about the Sudo API status and available models. These are typically used for health monitoring and discovering available AI models. ## Health Check Check if the Sudo API and backend infrastructure are healthy and ready to accept connections. ### Basic Usage ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); async function checkHealth() { try { // Check API health const healthStatus = await sudo.system.healthCheck(); console.log(`API Status: ${JSON.stringify(healthStatus)}`); } catch (error) { console.error("Health check failed:", error); } } checkHealth(); ``` ```python Python theme={null} import os from sudo import Sudo with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: # Check API health health_status = client.system.health_check() print(f"API Status: {health_status}") ``` ### Python Async Usage ```python Python theme={null} import asyncio import os from sudo import Sudo async def check_health(): async with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: health_status = await client.system.health_check_async() return health_status # Run the async function health = asyncio.run(check_health()) print(f"API Status: {health}") ``` ## Get Supported Models Retrieve a list of all AI models supported by the Sudo API, including their capabilities and pricing information. ### Basic Usage ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY, }); async function getSupportedModels() { try { const models = await sudo.system.getSupportedModels(); console.log(`Available models: ${models.data.length}`); models.data.forEach(m => { console.log(`- ${m.modelName} (${m.modelProvider})`); }); } catch (error) { console.error("Failed to get models:", error); } } getSupportedModels(); ``` ```python Python theme={null} import os from sudo import Sudo with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: # Get all supported models models = client.system.get_supported_models() print(f"Available models: {len(models.data)}") for model in models.data: print(f"- {model.model_name}: {model.model_provider}") ``` ### Python Async Usage ```python Python theme={null} import asyncio import os from sudo import Sudo async def get_models_info(): async with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: models = await client.system.get_supported_models_async() return models # Get models asynchronously models = asyncio.run(get_models_info()) print(f"Found {len(models.data)} models") ``` ## Error Handling Both system endpoints can encounter various errors. Here's how to handle them: ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; import * as errors from "sudo-ai/models/errors"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); async function systemEndpointsWithErrorHandling() { try { // Try health check const health = await sudo.system.healthCheck(); console.log("✅ Health check passed"); // Try getting models const models = await sudo.system.getSupportedModels(); console.log(`✅ Retrieved ${models.data.length} models`); } catch (error) { if (error instanceof errors.SudoError) { if (error.statusCode === 401) { console.log("❌ Authentication failed - check your API key"); } else if (error.statusCode >= 500) { console.log("❌ Server error - the API may be experiencing issues"); } else { console.log(`❌ API error: ${error.message}`); console.log(`Status: ${error.statusCode}`); } if (error instanceof errors.ErrorResponse) { console.log(`Error details: ${error.data$.error}`); } } else { console.log(`❌ Unexpected error: ${error}`); } } } systemEndpointsWithErrorHandling(); ``` ```python Python theme={null} import os from sudo import Sudo, errors with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: try: # Try health check health = client.system.health_check() print("✅ Health check passed") # Try getting models models = client.system.get_supported_models() print(f"✅ Retrieved {len(models.data)} models") except errors.ErrorResponse as e: if e.status_code == 401: print("❌ Authentication failed - check your API key") elif e.status_code >= 500: print("❌ Server error - the API may be experiencing issues") else: print(f"❌ API error: {e.message}") print(f"Status: {e.status_code}") except errors.SudoError as e: print(f"❌ SDK error: {e.message}") except Exception as e: print(f"❌ Unexpected error: {e}") ``` ## Next Steps Now that you understand the system endpoints: 1. **[Try AI Responses](/sdk/sudo-sdk/ai-responses)** - Start creating AI responses 2. **[Explore Streaming](/sdk/sudo-sdk/streaming)** - Add real-time capabilities 3. **[Advanced Features](/sdk/sudo-sdk/tool-calling)** - Function calling and more Use the health check endpoint in your application's readiness probes and the models endpoint to dynamically discover available AI models. Both TypeScript and Python SDKs provide the same system information with language-appropriate handling. # Tool Calling Source: https://docs.sudoapp.dev/sdk/sudo-sdk/tool-calling Function calling and tool execution capabilities Tool calling allows AI models to execute functions and interact with external systems, enabling more dynamic and powerful applications. ## Basic Tool Calling ### Simple Function Definition Define a tool within your application that the AI model can call. ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); function getWeather(location: string): string { // This would normally call a real weather API return `The weather in ${location} is sunny and 75°F`; } // Define the tool for the AI const tools = [ { type: "function" as const, function: { name: "get_weather", description: "Get current weather information for a location", parameters: { type: "object", properties: { location: { type: "string", description: "The city and state, e.g. San Francisco, CA" } }, required: ["location"] } } } ]; async function basicToolCalling() { try { const response = await sudo.router.create({ model: "gpt-4o", messages: [ { role: "user", content: "What's the weather like in New York?" } ], tools: tools, toolChoice: "auto" }); const message = response.choices[0].message; // Check if the model wants to call a function if (message.toolCalls) { for (const toolCall of message.toolCalls) { if (toolCall.function.name === "get_weather") { const args = JSON.parse(toolCall.function.arguments); const weatherResult = getWeather(args.location); console.log(`Weather result: ${weatherResult}`); } } } else { console.log(`Response: ${message.content}`); } } catch (error) { console.error("Tool calling error:", error); } } basicToolCalling(); ``` ```python Python theme={null} import os import json from sudo import Sudo def get_weather(location): """Get current weather for a location""" # This would normally call a real weather API return f"The weather in {location} is sunny and 75°F" # Define the tool for the AI tools = [ { "type": "function", "function": { "name": "get_weather", "description": "Get current weather information for a location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA" } }, "required": ["location"] } } } ] with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: response = client.router.create( model="gpt-4o", messages=[ {"role": "user", "content": "What's the weather like in New York?"} ], tools=tools, tool_choice="auto" ) message = response.choices[0].message # Check if the model wants to call a function if message.tool_calls: for tool_call in message.tool_calls: if tool_call.function.name == "get_weather": args = json.loads(tool_call.function.arguments) weather_result = get_weather(args["location"]) print(f"Weather result: {weather_result}") else: print(f"Response: {message.content}") ``` ## Streaming with Tools ```typescript TypeScript theme={null} import { Sudo } from "sudo-ai"; const sudo = new Sudo({ serverURL: "https://sudoapp.dev/api", apiKey: process.env.SUDO_API_KEY ?? "", }); async function streamWithToolCalls() { const tools = [ { type: "function" as const, function: { name: "search_database", description: "Search for information in the database", parameters: { type: "object", properties: { query: { type: "string", description: "Search query" } }, required: ["query"] } } } ]; try { const stream = await sudo.router.createStreaming({ model: "gpt-4o", messages: [ { role: "user", content: "Find information about TypeScript frameworks" } ], tools: tools, toolChoice: "auto" }); const toolCalls: any[] = []; const contentParts: string[] = []; for await (const chunk of stream) { if (chunk.data?.choices) { for (const choice of chunk.data.choices) { if (choice.delta) { // Regular content if (choice.delta.content) { const content = choice.delta.content; contentParts.push(content); process.stdout.write(content); } // Tool calls if (choice.delta.toolCalls) { for (const toolCallDelta of choice.delta.toolCalls) { // Handle streaming tool calls console.log(`\n[Tool Call: ${toolCallDelta.function?.name}]`); if (toolCallDelta.function?.arguments) { console.log(`[Args: ${toolCallDelta.function.arguments}]`); } } } } } } } console.log(); } catch (error) { console.error("Streaming tool calling error:", error); } } streamWithToolCalls(); ``` ```python Python theme={null} import os import json from sudo import Sudo def stream_with_tool_calls(): tools = [ { "type": "function", "function": { "name": "search_database", "description": "Search for information in the database", "parameters": { "type": "object", "properties": { "query": {"type": "string", "description": "Search query"} }, "required": ["query"] } } } ] with Sudo( server_url="https://sudoapp.dev/api", api_key=os.getenv("SUDO_API_KEY"), ) as client: stream = client.router.create_streaming( model="gpt-4o", messages=[ {"role": "user", "content": "Find information about Python frameworks"} ], tools=tools, tool_choice="auto" ) tool_calls = [] content_parts = [] with stream as event_stream: for chunk in event_stream: if chunk.data and chunk.data.choices: for choice in chunk.data.choices: if choice.delta: # Regular content if choice.delta.content: content = choice.delta.content content_parts.append(content) print(content, end="", flush=True) # Tool calls if choice.delta.tool_calls: for tool_call_delta in choice.delta.tool_calls: # Handle streaming tool calls print(f"\n[Tool Call: {tool_call_delta.function.name}]") if tool_call_delta.function.arguments: print(f"[Args: {tool_call_delta.function.arguments}]") print() stream_with_tool_calls() ``` ## Next Steps 1. **[Structured Output](/sdk/sudo-sdk/structured-output)** - Generate JSON and structured data 2. **[Image Input](/sdk/sudo-sdk/image-input)** - Work with multimodal inputs 3. **[Reasoning](/sdk/sudo-sdk/reasoning)** - Advanced reasoning capabilities Tool calling works best with models like GPT-4o, Claude Sonnet-4, and other function-calling capable models. Always validate tool inputs and handle errors gracefully. Both TypeScript and Python SDKs provide the same powerful tool calling capabilities with language-appropriate patterns.