### Install OpenAI SDK for TypeScript Source: https://docs.onlysq.ru/docs/api Installs the OpenAI SDK for TypeScript (Node.js), enabling interaction with the OnlySq API. This is a prerequisite for using the TypeScript code example. ```shell npm install openai ``` -------------------------------- ### Install OpenAI SDK for Python Source: https://docs.onlysq.ru/docs/api Installs the OpenAI SDK for Python, which is used to interact with the OnlySq API. This is the first step before making API calls. ```shell pip install -U openai ``` -------------------------------- ### Install OpenAI SDK (Python) Source: https://docs.onlysq.ru/docs/openaisdk Installs the OpenAI Python package using pip. This is a prerequisite for using the OpenAI SDK with OnlySq AI models in Python projects. ```shell pip install openai ``` -------------------------------- ### OpenAI SDK Integration Source: https://docs.onlysq.ru/getstarted This section provides guidance on using the OnlySq SDK to access API models. It encourages developers to explore code examples for building applications. ```text SDK is the primary way of accessing OnlySq API models. Look at the code examples and build something cool! Get started → ``` -------------------------------- ### Streaming Tool Calls Example (Python) Source: https://docs.onlysq.ru/docs/toolcall This Python example shows how to handle streaming tool calls from the API. It includes a function to get weather data and demonstrates processing partial 'tool_calls' data received in chunks during a streaming response. ```python import json import requests from openai import OpenAI def get_weather(latitude: float, longitude: float): response = requests.get( f"https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}¤t=temperature_2m,wind_speed_10m&hourly=temperature_2m,relative_humidity_2m,wind_speed_10m" ) data = response.json() return data['current']['temperature_2m'] client = OpenAI(base_url="https://api.onlysq.ru/ai/openai", api_key="openai") tools = [ { "type": "function", "function": { "name": "get_weather", "description": "Get the current weather for a given location", "parameters": { "type": "object", "properties": { "latitude": { "type": "number" }, "longitude": { "type": "number" }, }, "required": ["latitude", "longitude"], }, }, } ] input_messages = [{"role": "user", "content": "What's the weather like in Paris today? 48°51′24″N 2°21′8″E"}] ``` -------------------------------- ### Initialize OpenAI Client (Python) Source: https://docs.onlysq.ru/docs/openaisdk Initializes the OpenAI client for Python, configuring it with the OnlySq API base URL and an API key. This setup is necessary to make requests to OnlySq's AI models. ```python from openai import OpenAI client = OpenAI( base_url="https://api.onlysq.ru/ai/openai/", api_key="openai" # or your valid key ) ``` -------------------------------- ### Weather Function and Tool Example (Python) Source: https://docs.onlysq.ru/docs/tools Demonstrates how to define an external function (get_weather) and its corresponding tool definition for the OpenAI SDK. It includes making an API call and processing the tool's response. ```python import json import requests from openai import OpenAI # 1. Define the external function def get_weather(latitude: float, longitude: float) -> float: """Get current temperature for provided coordinates in celsius.""" response = requests.get( f"https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}¤t=temperature_2m,wind_speed_10m&hourly=temperature_2m,relative_humidity_2m,wind_speed_10m" ) data = response.json() return data['current']['temperature_2m'] # 2. Define the tool for the model tools = [ { "type": "function", "function": { "name": "get_weather", "description": "Get the current weather for a given location", "parameters": { "type": "object", "properties": { "latitude": { "type": "number" }, "longitude": { "type": "number" }, }, "required": ["latitude", "longitude"], }, }, } ] client = OpenAI(base_url="https://api.onlysq.ru/ai/openai", api_key="openai") # 3. Initial user message input_messages = [{"role": "user", "content": "What's the weather like in Paris today? 48°51′24″N 2°21′8″E"}] # 4. First API call: The model will "call" the tool response = client.chat.completions.create( model="gemini-2.0-flash", messages=input_messages, tools=tools, tool_choice="auto" ) # 5. Extract and execute the tool call tool_call = response.choices[0].message.tool_calls[0] function_name = tool_call.function.name function_args = json.loads(tool_call.function.arguments) if function_name == "get_weather": result = get_weather( latitude=function_args.get("latitude"), longitude=function_args.get("longitude") ) else: result = "Unknown function called." ``` -------------------------------- ### Install OpenAI SDK (TypeScript/JavaScript) Source: https://docs.onlysq.ru/docs/openaisdk Installs the OpenAI Node.js package using npm. This is required for integrating OnlySq AI models via the OpenAI SDK in TypeScript or JavaScript projects. ```shell npm install openai ``` -------------------------------- ### OnlySq API ImaGen Response Example Source: https://docs.onlysq.ru/docs/imagen This is an example of a successful response from the OnlySq API's POST /ai/imagen endpoint. It includes the generated image's ID, creation timestamp, model used, base64 encoded file data, aspect ratio, generation time, usage tokens, and user ID. ```json { 'id': 'imagen_u1nW43V9wAaWenrHifdqkzxSLNWIpXLVBMzJ4fnBsyNMx94w', 'created': 1753881206, 'model': 'flux', 'files': ['base64'], 'ratio': '16:9', 'elapsed-time': 3.20550274848938, 'usage': 1, 'user': 0 } ``` -------------------------------- ### Example tool_calls Response (JSON) Source: https://docs.onlysq.ru/docs/toolcall This JSON object demonstrates the structure of a 'tool_calls' response from the API. It includes the call ID, type, and function details like name and arguments, which are crucial for subsequent tool message processing. ```json { "id": "chat_XBt6z670WKm7L9BVoCcLZLzTNZ03UJhD6sWqAEUyTgaJvhJA", "choices": [ { "index": 0, "message": { "role": "assistant", "tool_calls": [ { "id": "call_abc123", "type": "function", "function": { "name": "get_weather", "arguments": "{\"latitude\":48.8566,\"longitude\":2.3522}" } } ] }, "finish_reason": "tool_calls" } ], "//": "... other fields" } ``` -------------------------------- ### Streaming Chat Completion Chunk Example Source: https://docs.onlysq.ru/docs/openaisdk Provides an example of a single chunk received during a streaming chat completion. This JSON structure shows the format of incremental data, including the content and role, as well as metadata like ID and model. ```JSON { "id": "chatcmpl_lQdhTfXn4yKoDlyCjuBpL0GfPZNonZufGqOyGl3wVpMhJRwP", "object": "chat.completion.chunk", "created": 1750612428, "model": "gpt-4o-mini", "choices": [ { "index": 0, "delta": { "content": "te", "role": "assistant" }, "finish_reason": null } ], "usage": null } ``` -------------------------------- ### Retrieve OnlySq Models List Source: https://docs.onlysq.ru/docs/models This snippet shows how to retrieve a JSON list of all available models from the OnlySq API. It's a GET request to the specified endpoint. ```HTTP GET https://api.onlysq.ru/ai/models ``` -------------------------------- ### Chat Completions (cURL) Source: https://docs.onlysq.ru/docs/openaisdk Provides a cURL command to perform a chat completion request to the OnlySq API. This example demonstrates the raw HTTP request structure, including headers and JSON payload. ```bash curl --request POST \ --url https://api.onlysq.ru/ai/openai/chat/completions \ --header 'Authorization: Bearer openai' \ --header 'Content-Type: application/json' \ --data '{ \ "model": "gpt-4o-mini", \ "messages": [ \ { \ "role": "user", "content": "Say 5 short facts about AI." \ } \ ] \ }' ``` -------------------------------- ### Python: Second API Call with Updated Messages Source: https://docs.onlysq.ru/docs/tools Makes a second API call to the chat completions endpoint using an updated list of messages that includes tool outputs. The model generates a final response based on the conversation history and tool results. The example uses the 'gemini-2.0-flash' model and prints the content of the final message. ```python response_2 = client.chat.completions.create( model="gemini-2.0-flash", messages=input_messages, tools=tools, ) print(response_2.choices[0].message.content) ``` -------------------------------- ### Streaming AI Text Generation Request (Python) Source: https://docs.onlysq.ru/docs/endpoint2 Provides a Python example for making a streaming POST request to the OnlySq AI API. This allows for receiving the AI's response in chunks as it's generated, which is useful for real-time applications. The code iterates through the streamed response, decodes, parses JSON chunks, and prints the content. ```Python import requests, json url = "http://api.onlysq.ru/ai/v2" data = { "model": "gpt-4o-mini", "request": { "messages": [ { "role": "user", "content": "Write a one-line story about AI." } ], "stream": True } } with requests.post(url, json=data, stream=True) as response: if response.status_code == 200: for line in response.iter_lines(): if line: try: decoded_line = line.decode('utf-8').strip() if decoded_line.startswith("data: "): decoded_line = decoded_line[len("data: "):] if decoded_line == "[DONE]": break chunk = json.loads(decoded_line) content = chunk["choices"][0]["delta"].get("content") if content: print(content, end="", flush=True) except Exception as e: print(e) else: print(response.status_code, response.text) ``` -------------------------------- ### Python Implementation: Search Products Tool Source: https://docs.onlysq.ru/docs/toolbuild Provides a Python implementation for the 'search_products' tool using the OpenAI SDK. It demonstrates how to define the tool's structure, including its name, description, and parameters, within a list of tools. ```python import json from openai import OpenAI # 1. Define the tool tools = [ { "type": "function", "function": { "name": "search_products", "description": "Searches the product database for items matching a specific query. Can filter by price range and category.", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "The search term for the product, e.g., 'smartphone'." }, "min_price": { "type": "number", "description": "The minimum price of the product." }, "max_price": { "type": "number", "description": "The maximum price of the product." }, "category": { "type": "string", "description": "The product category, e.g., 'electronics' or 'clothing'." } }, "required": ["query"] } } } ] ``` -------------------------------- ### Python OpenAI Client Initialization and Tool Calling Source: https://docs.onlysq.ru/docs/toolbuild Demonstrates initializing the OpenAI client with a custom `base_url` for a specific API endpoint and making a chat completion request. It shows how to include `tools` in the request and how to handle the response, specifically extracting function calls and their arguments. The code then simulates executing the called function and appending the result back into the conversation history for a subsequent AI response. ```python client = OpenAI(base_url="https://api.onlysq.ru/ai/openai", api_key="openai") # 3. User prompt input_messages = [{"role": "user", "content": "I'm looking for an electronic device that costs less than $1000."}] # 4. First API call response = client.chat.completions.create( model="gemini-2.0-flash", messages=input_messages, tools=tools, tool_choice="auto" ) # 5. Execute the tool call tool_call = response.choices[0].message.tool_calls[0] function_name = tool_call.function.name function_args = json.loads(tool_call.function.arguments) if function_name == "search_products": search_results = search_products( query=function_args.get("query", ""), min_price=function_args.get("min_price"), max_price=function_args.get("max_price"), category=function_args.get("category") ) result_content = json.dumps(search_results) else: result_content = "Unknown function called." # 6. Append the tool's output input_messages.append(response.choices[0].message) input_messages.append( { "role": "tool", "tool_call_id": tool_call.id, "name": function_name, "content": result_content, } ) # 7. Final response response_2 = client.chat.completions.create( model="gemini-2.0-flash", messages=input_messages, tools=tools, ) print(response_2.choices[0].message.content) ``` -------------------------------- ### Access Qwen Models via OpenAI SDK Source: https://docs.onlysq.ru/docs/models Demonstrates how to access Qwen models, developed by Alibaba Cloud, using the OpenAI SDK. This allows for integration into applications requiring advanced natural language processing, code generation, and multi-modal capabilities. ```Python from openai import OpenAI client = OpenAI( base_url="https://api.example.com/v1", # Replace with actual base URL if needed api_key="YOUR_API_KEY", # Replace with your actual API key ) # Example for qwen3-235b-a22b completion = client.chat.completions.create( model="qwen3-235b-a22b", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "What are the key features of the Qwen3-235b-a22b model?"} ] ) print(completion.choices[0].message.content) # Example for qwen-max-latest completion = client.chat.completions.create( model="qwen-max-latest", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Explain the capabilities of the Qwen-max-latest model."} ] ) print(completion.choices[0].message.content) # Example for qwen2.5-coder-32b-instruct completion = client.chat.completions.create( model="qwen2.5-coder-32b-instruct", messages=[ {"role": "system", "content": "You are a helpful assistant that generates code."}, {"role": "user", "content": "Write a Python function to calculate factorial."} ] ) print(completion.choices[0].message.content) ``` -------------------------------- ### Submit Project for OnlySq Second Line (English) Source: https://docs.onlysq.ru/about Template for submitting a project to join the OnlySq 'Second Line' community developers. It requires personal information, project details, and GitHub repository link. ```English I, [name], want to get into OnlySq Second Line My IP addresses from which requests came (Find IP): ... My projects: Project name - where the project is used; Project IP My GitHub: https://github.com/username ``` -------------------------------- ### Interact with OnlySq API using Python SDK Source: https://docs.onlysq.ru/docs/api Demonstrates how to initialize the OpenAI client with OnlySq's base URL and API key, and then make a chat completion request. It prints the content of the AI's response. ```python from openai import OpenAI client = OpenAI( base_url="https://api.onlysq.ru/ai/openai", api_key="openai", ) completion = client.chat.completions.create( model="gpt-4o-mini", messages=[ { "role": "user", "content": "Say 5 short facts about AI.", }, ], ) print(completion.choices[0].message.content) ``` -------------------------------- ### Tool Definition: Search Products Source: https://docs.onlysq.ru/docs/toolbuild Defines a 'search_products' tool using JSON Schema. This tool searches a product database and accepts a required 'query' parameter along with optional 'min_price', 'max_price', and 'category' filters. ```json { "type": "function", "function": { "name": "search_products", "description": "Searches the product database for items matching a specific query. Can filter by price range and category.", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "The search term for the product, e.g., 'smartphone'." }, "min_price": { "type": "number", "description": "The minimum price of the product." }, "max_price": { "type": "number", "description": "The maximum price of the product." }, "category": { "type": "string", "description": "The product category, e.g., 'electronics' or 'clothing'." } }, "required": ["query"] } } } ``` -------------------------------- ### Python Mock Product Search Function Source: https://docs.onlysq.ru/docs/toolbuild Defines a Python function `search_products` that simulates searching a product database. It accepts a query string and optional price and category filters. The function returns a list of matching products from a predefined mock dataset. This is useful for testing or demonstrating search functionality without a real database. ```python def search_products(query: str, min_price: float = None, max_price: float = None, category: str = None) -> list: """A mock function to simulate a product search.""" # In a real application, this would query a database mock_db = [ {"name": "Laptop Pro", "price": 1200, "category": "electronics"}, {"name": "Gaming Mouse", "price": 75, "category": "electronics"}, {"name": "T-shirt", "price": 25, "category": "clothing"}, {"name": "Fancy Phone", "price": 950, "category": "electronics"} ] results = [p for p in mock_db if query.lower() in p["name"].lower()] if min_price: results = [p for p in results if p["price"] >= min_price] if max_price: results = [p for p in results if p["price"] <= max_price] if category: results = [p for p in results if p["category"].lower() == category.lower()] return results ``` -------------------------------- ### Submit Project for OnlySq Second Line (Russian) Source: https://docs.onlysq.ru/about Template for submitting a project to join the OnlySq 'Second Line' community developers in Russian. It requires personal information, project details, and GitHub repository link. ```Russian Я, [имя], хочу попасть в OnlySq Second Line Мои IP адреса с которых приходили запросы (Узнать IP): ... Мои проекты: Имя проекта - где используется проект; IP проекта Мой GitHub: https://github.com/username ``` -------------------------------- ### Access Google Gemini Models via OpenAI SDK Source: https://docs.onlysq.ru/docs/models Demonstrates how to access Google's Gemini models, such as Gemini 2.5 Flash and Gemini 1.5 Pro, using the OpenAI SDK. This enables leveraging Google's advanced reasoning and multimodal capabilities within a familiar SDK structure. ```Python from openai import OpenAI client = OpenAI( base_url="https://api.example.com/v1", # Replace with actual base URL if needed api_key="YOUR_API_KEY", # Replace with your actual API key ) # Example for gemini-2.5-flash completion = client.chat.completions.create( model="gemini-2.5-flash", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "What are the benefits of using Gemini 2.5 Flash?"} ] ) print(completion.choices[0].message.content) # Example for gemini-1.5-pro completion = client.chat.completions.create( model="gemini-1.5-pro", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Describe the advanced reasoning capabilities of Gemini 1.5 Pro."} ] ) print(completion.choices[0].message.content) # Example for gemma-3-4b-it completion = client.chat.completions.create( model="gemma-3-4b-it", messages=[ {"role": "system", "content": "You are a helpful assistant for instructional tasks."}, {"role": "user", "content": "Explain the concept of recursion."} ] ) print(completion.choices[0].message.content) ``` -------------------------------- ### API Reference - Natural Language Processing Source: https://docs.onlysq.ru/getstarted Integrate natural language processing and generation into your projects using the OnlySq API. Requires an internet connection and minimal code. ```text Integrate natural language processing and generation into your projects with a few lines of code and internet connection Get started → ``` -------------------------------- ### OpenAI SDK - ChatGPT Models Source: https://docs.onlysq.ru/docs/models This section details various ChatGPT models available through the OpenAI SDK. It includes models like gpt-4o-mini, gpt-4o, gpt-4, o3-mini, and gpt-3.5-turbo, highlighting their features such as multimodal reasoning, function calling, and cost-effectiveness. ```OpenAI SDK # Example usage for gpt-4o-mini (requires OpenAI SDK setup) # from openai import OpenAI # client = OpenAI() # response = client.chat.completions.create( # model="gpt-4o-mini", # messages=[ # {"role": "system", "content": "You are a helpful assistant."}, # {"role": "user", "content": "Who won the world series in 2020?"} # ] # ) # print(response.choices[0].message.content) ``` -------------------------------- ### Interact with OnlySq API using TypeScript SDK Source: https://docs.onlysq.ru/docs/api Shows how to set up the OpenAI client for TypeScript with OnlySq's base URL and API key, and then perform a chat completion. The AI's response content is logged to the console. ```typescript import OpenAI from "openai"; const openai = new OpenAI({ baseURL: "https://api.onlysq.ru/ai/openai", apiKey: "openai", }); const completion = await openai.chat.completions.create({ model: "gpt-4o-mini", messages: [ { role: "user", content: "Say 5 short facts about AI.", }, ] }); console.log(completion.choices[0].message.content); ``` -------------------------------- ### OpenAI SDK - Llama Models Source: https://docs.onlysq.ru/docs/models This section details Llama models available through the OpenAI SDK. It includes Llama-3.3 and Llama-3.1, highlighting their strengths in reasoning, multilingual support, and code generation. ```OpenAI SDK # Example usage for Llama-3.1 (requires OpenAI SDK setup) # from openai import OpenAI # client = OpenAI() # response = client.chat.completions.create( # model="llama-3.1", # messages=[ # {"role": "system", "content": "You are a multilingual assistant."}, # {"role": "user", "content": "Translate 'hello world' to French."} # ] # ) # print(response.choices[0].message.content) ``` -------------------------------- ### Initialize OpenAI Client (TypeScript) Source: https://docs.onlysq.ru/docs/openaisdk Initializes the OpenAI client for TypeScript/JavaScript, setting the OnlySq API base URL and API key. This client instance is used to interact with OnlySq's AI services. ```typescript import OpenAI from "openai"; const openai = new OpenAI({ baseURL: "https://api.onlysq.ru/ai/openai/", apiKey: "openai" // or your valid key }); ``` -------------------------------- ### OpenAI SDK - DeepSeek Models Source: https://docs.onlysq.ru/docs/models This section covers DeepSeek models accessible via the OpenAI SDK. It features DeepSeek-R1, optimized for reasoning and code generation, and DeepSeek-V3, known for advanced reasoning and efficiency in complex tasks. ```OpenAI SDK # Example usage for DeepSeek-R1 (requires OpenAI SDK setup) # from openai import OpenAI # client = OpenAI() # response = client.chat.completions.create( # model="deepseek-r1", # messages=[ # {"role": "system", "content": "You are a coding assistant."}, # {"role": "user", "content": "Write a Python function to calculate factorial."} # ] # ) # print(response.choices[0].message.content) ``` -------------------------------- ### OpenAI SDK - Claude Models Source: https://docs.onlysq.ru/docs/models This section covers Claude models accessible via the OpenAI SDK. It features Claude-3.5-Sonnet, known for its powerful natural language and reasoning capabilities, and Claude-3-Haiku, a fast and cost-efficient option. ```OpenAI SDK # Example usage for Claude-3.5-Sonnet (requires OpenAI SDK setup) # from openai import OpenAI # client = OpenAI() # response = client.chat.completions.create( # model="claude-3.5-sonnet", # messages=[ # {"role": "system", "content": "You are an analytical assistant."}, # {"role": "user", "content": "Summarize the main points of this article."} # ] # ) # print(response.choices[0].message.content) ``` -------------------------------- ### Tool Object Structure (JSON) Source: https://docs.onlysq.ru/docs/tools Defines the standard structure for creating a tool object that the model can understand. It includes the tool type, function name, description, and parameter schema. ```json { "type": "function", "function": { "name": "your_function_name", "description": "A description of what your function does.", "parameters": { "type": "object", "properties": { "parameter1": { "type": "string", "description": "Description of the first parameter." }, "parameter2": { "type": "number", "description": "Description of the second parameter." } }, "required": ["parameter1"] } } } ``` -------------------------------- ### OpenAI SDK - Le Chat Models Source: https://docs.onlysq.ru/docs/models This section details Le Chat models, specifically Mistral-Small-3.1, available through the OpenAI SDK. It emphasizes its efficiency, scalability, and strong performance in language tasks and reasoning. ```OpenAI SDK # Example usage for Mistral-Small-3.1 (requires OpenAI SDK setup) # from openai import OpenAI # client = OpenAI() # response = client.chat.completions.create( # model="mistral-small-3.1", # messages=[ # {"role": "system", "content": "You are a concise assistant."}, # {"role": "user", "content": "Explain the concept of recursion in simple terms."} # ] # ) # print(response.choices[0].message.content) ``` -------------------------------- ### Using OpenAI SDK for Cohere Models Source: https://docs.onlysq.ru/docs/models Demonstrates how to interact with Cohere's models using the OpenAI SDK. This snippet highlights the common practice of using the SDK for API calls to various Cohere models, as indicated by the 'OpenAI SDK' endpoint for most listed models. ```Python from openai import OpenAI client = OpenAI( api_key="YOUR_API_KEY", base_url="COHERE_API_BASE_URL" ) # Example for a Command model response_command = client.chat.completions.create( model="command-r", messages=[ {"role": "user", "content": "Explain the concept of recursion."} ] ) print(response_command.choices[0].message.content) # Example for an Image model (if applicable via SDK) # Note: Image generation might require a different client or method depending on SDK version and provider integration. # response_image = client.images.generate( # prompt="A futuristic cityscape", # model="flux", # Assuming flux is supported via this SDK interface # size="1024x1024" # ) # print(response_image.data[0].url) ``` -------------------------------- ### Chat Completions (Python) Source: https://docs.onlysq.ru/docs/openaisdk Demonstrates how to perform a chat completion request using the OpenAI SDK in Python with OnlySq's API. It sends a user message and prints the AI's response. ```python from openai import OpenAI client = OpenAI( base_url="https://api.onlysq.ru/ai/openai", api_key="openai", ) completion = client.chat.completions.create( model="gpt-4o-mini", messages=[ { "role": "user", "content": "Say 5 short facts about AI.", }, ], ) print(completion.choices[0].message.content) ``` -------------------------------- ### Chat Completions (TypeScript) Source: https://docs.onlysq.ru/docs/openaisdk Shows how to make a chat completion request using the OpenAI SDK in TypeScript/JavaScript with OnlySq's API. It sends a user query and logs the AI's generated content. ```typescript import OpenAI from "openai"; const openai = new OpenAI({ baseURL: "https://api.onlysq.ru/ai/openai", apiKey: "openai", }); const completion = await openai.chat.completions.create({ model: "gpt-4o-mini", messages: [ { role: "user", content: "Say 5 short facts about AI.", }, ] }); console.log(completion.choices[0].message.content); ``` -------------------------------- ### Python State Management Chat Completion Source: https://docs.onlysq.ru/docs/openaisdk Demonstrates how to use the OpenAI Python SDK to send a conversation history, including system, user, and assistant messages, to the OnlySQ AI API for chat completion. It initializes the client with a custom base URL and API key. ```Python from openai import OpenAI client = OpenAI( base_url="https://api.onlysq.ru/ai/openai", api_key="openai", ) completion = client.chat.completions.create( model="gpt-4o-mini" messages=[ { "role": "system", "content": "You are a neko-helper.", }, { "role": "user", "content": "What's 5 + 5?", }, { "role": "assistant", "content":"Nya~! 5 + 5 is 10, purr-fectly simple! 😸✨" }, { "role": "user", "content": "Say what do you like", }, ], ) print(completion.choices[0].message.content) ``` -------------------------------- ### Python API Call for Tool Execution and Streaming Source: https://docs.onlysq.ru/docs/toolcall This Python code snippet demonstrates how to make an initial API call to a chat completion model, parse tool calls from the response, execute a specific function ('get_weather') with arguments extracted from the tool call, and then make a subsequent streaming API call to display the results. It handles cases where unknown functions are called or no tool calls are present. ```Python response = client.chat.completions.create( model="gemini-2.0-flash", messages=input_messages, tools=tools, tool_choice="auto" ) if response.choices[0].message.tool_calls: tool_call = response.choices[0].message.tool_calls[0] function_name = tool_call.function.name function_args = json.loads(tool_call.function.arguments) if function_name == "get_weather": # Execute the tool result = get_weather( latitude=function_args.get("latitude"), longitude=function_args.get("longitude") ) # Append the tool's output to messages input_messages.append(response.choices[0].message) input_messages.append( { "role": "tool", "tool_call_id": tool_call.id, "name": function_name, "content": str(result), } ) # Second API call with streaming enabled stream = client.chat.completions.create( model="gemini-2.0-flash", messages=input_messages, tools=tools, stream=True ) # Process and print the streaming response for chunk in stream: content = chunk.choices[0].delta.content if content: print(content, end="", flush=True) print() else: print("Unknown function called.") else: print(response.choices[0].message.content) ``` -------------------------------- ### TypeScript State Management Chat Completion Source: https://docs.onlysq.ru/docs/openaisdk Shows how to perform chat completions using the OpenAI TypeScript SDK with the OnlySQ AI API. It includes setting up the client with a custom base URL and API key, and sending a structured conversation history. ```TypeScript import OpenAI from "openai"; const openai = new OpenAI({ baseURL: "https://api.onlysq.ru/ai/openai", apiKey: "openai", }); const completion = await openai.chat.completions.create({ model: "gpt-4o-mini", messages: [ { role: "system", content: "You are a neko-helper.", }, { role: "user", content: "What's 5 + 5?", }, { role: "assistant", content:"Nya~! 5 + 5 is 10, purr-fectly simple! 😸✨" }, { role: "user", content: "Say what do you like", }, ] }); console.log(completion.choices[0].message.content) ``` -------------------------------- ### Python Streaming Chat Completion Source: https://docs.onlysq.ru/docs/openaisdk Illustrates how to make a streaming chat completion request using the OpenAI Python SDK to the OnlySQ AI API. It iterates over the response chunks to print the content as it arrives. ```Python from openai import OpenAI client = OpenAI(api_key="openai", base_url="https://api.onlysq.ru/ai/openai/") messages = [ { "role":"user", "content":"Write a one-line story about AI." } ] r = client.chat.completions.create( model = "gpt-4o-mini", messages = messages, stream = True ) for chunk in r: print(chunk.choices[0].delta.content, end="") ``` -------------------------------- ### Generate Image with OnlySq API (Python) Source: https://docs.onlysq.ru/docs/imagen This Python script demonstrates how to use the OnlySq API to generate an image. It sends a POST request with a JSON payload containing the model, prompt, and desired aspect ratio. The response, containing the image data encoded in base64, is then decoded and saved to a file named 'pic.png'. ```python import requests, base64 j = { "model": "flux", "prompt": "cat on a blue water wave", "ratio":"16:9" } r = requests.post("https://api.onlysq.ru/ai/imagen", json=j) r.raise_for_status() c = r.json() with open('pic.png', 'wb') as f: f.write(base64.b64decode(c["files"][0])) print("Image saved successfully") ``` -------------------------------- ### Synchronous AI Text Generation Request (Python) Source: https://docs.onlysq.ru/docs/endpoint2 Demonstrates how to make a synchronous POST request to the OnlySq AI API to generate a text response. It includes setting up the request payload with model and message details, sending the request using the `requests` library, and printing the generated content from the response. ```Python import requests send = { "model": "gpt-4o-mini", "request": { "messages": [ { "role": "user", "content": "Hi! Write a short one-line story" } ] } } request = requests.post('http://api.onlysq.ru/ai/v2', json=send) response = request.json() print(response["choices"][0]["message"]["content"]) ``` -------------------------------- ### Using tool_choice Parameter (Python) Source: https://docs.onlysq.ru/docs/toolcall This Python code snippet illustrates how to set the 'tool_choice' parameter in an API request to control the model's function calling behavior. Options include 'auto', 'none', and 'required'. ```python # Example of using tool_choice response = client.chat.completions.create( model="gemini-2.0-flash", messages=input_messages, tools=tools, tool_choice="auto" # or "none", or "required" ) ``` -------------------------------- ### Python: Append Tool Output to Messages Source: https://docs.onlysq.ru/docs/tools Appends the model's tool call and the tool's output to the messages list. This involves creating a new message dictionary with 'role' set to 'tool', including the 'tool_call_id', 'name', and 'content' of the tool's result. This updated list is then used for a subsequent API call. ```python input_messages.append(response.choices[0].message) input_messages.append({ "role": "tool", "tool_call_id": tool_call.id, "name": function_name, "content": str(result), }) ``` -------------------------------- ### AI API Response Structure Source: https://docs.onlysq.ru/docs/endpoint2 Illustrates the JSON structure of a typical response from the OnlySq AI API for a text generation request. It includes fields like `id`, `object`, `created`, `model`, `choices` (with message content and finish reason), and `usage` statistics. ```JSON { "id": "chat_XBt6z670WKm7L9BVoCcLZLzTNZ03UJhD6sWqAEUyTgaJvhJA", "object": "chat.completion", "created": 1745146202, "model": "gpt-4o-mini", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "\"Under the full moon, the werewolf realized he'd forgotten his keys—again.\"", "refusal": null, "annotations": [] }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 11, "completion_tokens": 19, "total_tokens": 30 }, "user": 0 } ``` -------------------------------- ### Streaming Chat Completion Chunk (JSON) Source: https://docs.onlysq.ru/docs/endpoint2 This JSON object represents a single chunk of data in a streaming API response, typically used for chat completions. It includes an ID, object type, creation timestamp, model information, and a list of choices containing incremental content updates. The `delta` object within `choices` holds the actual new content. The `finish_reason` indicates if this is the end of the stream. ```json { "id": "chatcmpl_lQdhTfXn4yKoDlyCjuBpL0GfPZNonZufGqOyGl3wVpMhJRwP", "object": "chat.completion.chunk", "created": 1750612428, "model": "gpt-4o-mini", "choices": [ { "index": 0, "delta": { "content": "te", "role": "assistant" }, "finish_reason": null } ], "usage": null } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.