Overview
SilkDock API — one endpoint, every AI capability.
SilkDock provides a single unified endpoint that routes gateway capabilities via the action field. When action is omitted, /v1/responses keeps the native OpenAI Responses request format. Standard OpenAI-compatible paths are also supported.
Endpoint
POST https://silkdock.ai/v1/responsesEndpoints
| Capability | Unified Endpoint | Standard Path |
|---|---|---|
| Chat | POST /v1/responses (action=chat) | POST /v1/chat/completions |
| Streaming | POST /v1/responses (action=chat, stream=true) | POST /v1/chat/completions |
| Embedding | POST /v1/responses (action=embedding) | POST /v1/embeddings |
| Image Generation | POST /v1/responses (action=image) | POST /v1/images/generations |
| TTS | POST /v1/responses (action=tts) | POST /v1/audio/speech |
| STT | POST /v1/responses (action=transcription, multipart) | POST /v1/audio/transcriptions |
| Moderation | POST /v1/responses (action=moderation) | POST /v1/moderations |
| Video | POST /v1/responses (action=video) | POST /v1/videos/generations |
| File Upload | POST /v1/responses (action=file, multipart) | POST /v1/files |
| TypeSafe System One | — | POST /v1/systemone |
Authentication
Authorization: Bearer <YOUR_API_KEY>Get your API key from the Dashboard.
Request & Response
// Request
{
"model": "gpt-4o",
"input": [{ "role": "user", "content": "Hello" }]
}
// Response
{
"id": "resp_xxx",
"object": "response",
"created_at": 1720000000,
"status": "completed",
"model": "gpt-4o",
"output": [
{
"type": "message",
"id": "msg_xxx",
"status": "completed",
"role": "assistant",
"content": [
{ "type": "output_text", "text": "Hello! How can I help you?" }
]
}
],
"usage": { "input_tokens": 10, "output_tokens": 12, "total_tokens": 22 }
}Action field
action | Capability | Main input field |
|---|---|---|
chat | Chat / reasoning | messages |
embedding | Text embedding | input |
image | Image generation | prompt |
tts | Text-to-speech | input |
transcription | Speech-to-text | multipart file |
moderation | Content moderation | input |
video | Video generation | prompt |
file | File upload | multipart file |
Use multipart/form-data for transcription and file, including action as a form field. Other actions use JSON and otherwise accept the same fields as their standard paths.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
model | string | Yes | Model ID, e.g. gpt-4o, gpt-4.1, gpt-image-2.5-sunburst. |
action | string | Yes* | Gateway capability selector. Required for action routing; omit it only for a native OpenAI Responses request. |
input | string|array | Conditional | Native Responses input or embedding/TTS/moderation input. Chat action uses messages; image/video actions use prompt. |
instructions | string | No | System prompt, equivalent to a system message. |
stream | boolean | No | Enable SSE streaming. Default: false. |
max_output_tokens | integer | No | Maximum output tokens. |
temperature | number | No | Sampling temperature 0–2. Default: 1. |
top_p | number | No | Nucleus sampling 0–1. Default: 1. |
tools | array | No | List of callable tools. |
tool_choice | string|object | No | Tool selection strategy. |
store | boolean | No | Store the response server-side. Default: true. |
previous_response_id | string | No | Previous response ID for multi-turn conversation. |
TypeSafe System One
POST /v1/systemone calls Jev through the existing model-routing and billing pipeline and returns the native TypeSafe response format. The endpoint uses the same gateway API key authentication as the other API endpoints.
Before calling it, map the gateway model name jev to typesafe/jev and configure TypeSafe credentials. The request's model value is a gateway model name; sending a request does not create a model deployment automatically.
curl 'https://silkdock.ai/v1/systemone' \
-H "Authorization: Bearer $SILKDOCK_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "jev",
"state": "Help! My payouts have been failing for 3 days.",
"questions": {
"is_urgent": {
"type": "noul",
"instructions": "Does this convey urgency?"
}
}
}'Request parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
model | string | Yes | Configured gateway model name, such as jev. |
state | string | object | array | Yes | State to evaluate. Accepts a string, JSON object, or JSON array. |
questions | object | Yes | Non-empty question map. Supports noul, choice, and score question types. |
Missing required values and basic type errors return HTTP 422. See the TypeSafe API for the complete question schemas.
Response
{
"model": "jev-1.13.0",
"answers": {
"is_urgent": {
"type": "noul",
"noul": 0.95
}
},
"usage": {
"input_tokens": 296,
"output_tokens": 20
}
}The endpoint returns complete JSON only and does not support stream=true. Use /v1/chat/completions when a streaming wrapper is required. Internally, the gateway reuses the acompletion route so logging and billing operate on the converted Chat Completion response, while the client receives native answers and token usage fields.
Native Responses image generation
When action is omitted, OpenAI and ChatGPT routes support the standard image_generation tool. Always use the bare official image model ID in tools[].model, even when the top-level model has a chatgpt/ prefix.
{
"model": "gpt-5.4",
"input": "Create a cinematic photo of Shanghai on a rainy night",
"tools": [
{
"type": "image_generation",
"model": "gpt-image-2.5-sunburst",
"quality": "xhigh",
"size": "3:2"
}
]
}{
"model": "chatgpt/gpt-5.4",
"input": "Create a minimal product image of a smart watch",
"tools": [
{
"type": "image_generation",
"model": "gpt-image-2.5-flare",
"quality": "high",
"size": "1:1"
}
]
}Top-level Responses usage does not contain per-call image token details. Billing combines the top-level model's actual token cost with an estimated per-image charge for successful image_generation_call items that have status=completed and a result. Preauthorization uses max_tool_calls, or one call when it is omitted.
Code Examples
curl -X POST https://silkdock.ai/v1/responses \-H "Authorization: Bearer $SILKDOCK_API_KEY" \-H "Content-Type: application/json" \-d '{ "model": "gpt-4o", "input": [ {"role": "user", "content": "Hello"} ]}'const { OpenAI } = require("openai");const client = new OpenAI({apiKey: process.env.SILKDOCK_API_KEY,baseURL: "https://silkdock.ai/v1",});const response = await client.responses.create({model: "gpt-4o",input: [{ role: "user", content: "Hello" }],});console.log(response.output_text);import OpenAI from "openai";const client = new OpenAI({apiKey: process.env.SILKDOCK_API_KEY,baseURL: "https://silkdock.ai/v1",});const response = await client.responses.create({model: "gpt-4o",input: [{ role: "user", content: "Hello" }],});console.log(response.output_text);from openai import OpenAIimport osclient = OpenAI( api_key=os.getenv("SILKDOCK_API_KEY"), base_url="https://silkdock.ai/v1",)response = client.responses.create( model="gpt-4o", input=[{"role": "user", "content": "Hello"}],)print(response.output_text)#include <stdio.h>#include <curl/curl.h>int main(void) { CURL *curl = curl_easy_init(); if (!curl) return 1; struct curl_slist *headers = NULL; headers = curl_slist_append(headers, "Content-Type: application/json"); headers = curl_slist_append(headers, "Authorization: Bearer " SILKDOCK_API_KEY); const char *body = "{"model":"gpt-4o"," ""input":[{"role":"user","content":"Hello"}]}"; curl_easy_setopt(curl, CURLOPT_URL, "https://silkdock.ai/v1/responses"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body); curl_easy_perform(curl); curl_slist_free_all(headers); curl_easy_cleanup(curl); return 0;}/* compile: gcc main.c -lcurl -o main */#import <Foundation/Foundation.h>NSURLSession *session = [NSURLSession sharedSession];NSURL *url = [NSURL URLWithString:@"https://silkdock.ai/v1/responses"];NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];[request setHTTPMethod:@"POST"];[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];[request setValue:[@"Bearer " stringByAppendingString: [NSProcessInfo.processInfo.environment objectForKey:@"SILKDOCK_API_KEY"]] forHTTPHeaderField:@"Authorization"];NSDictionary *payload = @{ @"model": @"gpt-4o", @"input": @[ @{@"role": @"user", @"content": @"Hello"} ]};[request setHTTPBody:[NSJSONSerialization dataWithJSONObject:payload options:0 error:nil]];NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; NSArray *output = json[@"output"]; NSArray *content = output[0][@"content"]; NSLog(@"%@", content[0][@"text"]); }];[task resume];import java.net.http.*;import java.net.URI;var body = """ {"model":"gpt-4o","input":[ {"role":"user","content":"Hello"} ]}""";var req = HttpRequest.newBuilder() .uri(URI.create("https://silkdock.ai/v1/responses")) .header("Authorization", "Bearer " + System.getenv("SILKDOCK_API_KEY")) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(body)) .build();var res = HttpClient.newHttpClient().send(req, HttpResponse.BodyHandlers.ofString());System.out.println(res.body());package mainimport ( "bytes" "encoding/json" "fmt" "io" "net/http" "os")func main() { body, _ := json.Marshal(map[string]any{ "model": "gpt-4o", "input": []map[string]string{ {"role": "user", "content": "Hello"}, }, }) req, _ := http.NewRequest("POST", "https://silkdock.ai/v1/responses", bytes.NewReader(body)) req.Header.Set("Authorization", "Bearer "+os.Getenv("SILKDOCK_API_KEY")) req.Header.Set("Content-Type", "application/json") resp, _ := http.DefaultClient.Do(req) defer resp.Body.Close() data, _ := io.ReadAll(resp.Body) fmt.Println(string(data))}<?php$ch = curl_init("https://silkdock.ai/v1/responses");curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ "Authorization: Bearer " . getenv("SILKDOCK_API_KEY"), "Content-Type: application/json", ], CURLOPT_POSTFIELDS => json_encode([ "model" => "gpt-4o", "input" => [ ["role" => "user", "content" => "Hello"], ], ]),]);echo curl_exec($ch);import Foundationvar req = URLRequest(url: URL(string: "https://silkdock.ai/v1/responses")!)req.httpMethod = "POST"req.setValue("Bearer \(ProcessInfo.processInfo.environment["SILKDOCK_API_KEY"]!)", forHTTPHeaderField: "Authorization")req.setValue("application/json", forHTTPHeaderField: "Content-Type")req.httpBody = try! JSONSerialization.data(withJSONObject: [ "model": "gpt-4o", "input": [ ["role": "user", "content": "Hello"], ],])let (data, _) = try! await URLSession.shared.data(for: req)print(String(data: data, encoding: .utf8)!)using System.Net.Http;using System.Net.Http.Json;var client = new HttpClient();client.DefaultRequestHeaders.Add("Authorization", $"Bearer {Environment.GetEnvironmentVariable("SILKDOCK_API_KEY")}");var res = await client.PostAsJsonAsync("https://silkdock.ai/v1/responses", new { model = "gpt-4o", input = new[] { new { role = "user", content = "Hello" }, },});Console.WriteLine(await res.Content.ReadAsStringAsync());require "net/http"require "json"uri = URI("https://silkdock.ai/v1/responses")req = Net::HTTP::Post.new(uri)req["Authorization"] = "Bearer #{ENV['SILKDOCK_API_KEY']}"req["Content-Type"] = "application/json"req.body = {model: "gpt-4o",input: [ { role: "user", content: "Hello" },]}.to_jsonres = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |h| h.request(req) }puts res.bodyimport java.net.http.*import java.net.URIval req = HttpRequest.newBuilder() .uri(URI.create("https://silkdock.ai/v1/responses")) .header("Authorization", "Bearer ${System.getenv("SILKDOCK_API_KEY")}") .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(""" {"model":"gpt-4o","input":[ {"role":"user","content":"Hello"} ]}""")) .build()val res = HttpClient.newHttpClient().send(req, HttpResponse.BodyHandlers.ofString())println(res.body())use reqwest::blocking::Client;use serde_json::json;fn main() -> Result<(), Box<dyn std::error::Error>> { let res = Client::new() .post("https://silkdock.ai/v1/responses") .header("Authorization", format!("Bearer {}", std::env::var("SILKDOCK_API_KEY")?)) .json(&json!({ "model": "gpt-4o", "input": [ {"role": "user", "content": "Hello"} ] })) .send()?; println!("{}", res.text()?); Ok(())}POST /v1/responses HTTP/1.1Host: silkdock.aiAuthorization: Bearer <YOUR_API_KEY>Content-Type: application/json{"model": "gpt-4o","input": [ {"role": "user", "content": "Hello"}]}import 'dart:convert';import 'package:http/http.dart' as http;void main() async {final res = await http.post( Uri.parse('https://silkdock.ai/v1/responses'), headers: { 'Authorization': 'Bearer ${const String.fromEnvironment("SILKDOCK_API_KEY")}', 'Content-Type': 'application/json', }, body: jsonEncode({ 'model': 'gpt-4o', 'input': [ {'role': 'user', 'content': 'Hello'}, ], }),);print(res.body);}library(httr2)req <- request("https://silkdock.ai/v1/responses") |>req_headers( Authorization = paste("Bearer", Sys.getenv("SILKDOCK_API_KEY")), "Content-Type" = "application/json") |>req_body_json(list( model = "gpt-4o", input = list( list(role = "user", content = "Hello") )))resp <- req_perform(req)cat(resp_body_string(resp))(* requires cohttp-lwt-unix *)open Cohttp_lwt_unixopen Cohttpopen Lwtlet () =let body = {|{"model":"gpt-4o","input":[ {"role":"user","content":"Hello"}]}|} inlet headers = Header.of_list [ "Authorization", "Bearer " ^ Sys.getenv "SILKDOCK_API_KEY"; "Content-Type", "application/json";] inLwt_main.run ( Client.post ~headers ~body:(Cohttp_lwt.Body.of_string body) (Uri.of_string "https://silkdock.ai/v1/responses") >>= fun (_, body) -> Cohttp_lwt.Body.to_string body >>= fun s -> print_string s; return_unit)curl -X POST https://silkdock.ai/v1/responses \-H "Authorization: Bearer $SILKDOCK_API_KEY" \-H "Content-Type: application/json" \--no-buffer \-H "Accept: text/event-stream" -d '{ "model": "gpt-4o", "input": [{"role": "user", "content": "Write a short poem"}], "stream": true}'const { OpenAI } = require("openai");const client = new OpenAI({apiKey: process.env.SILKDOCK_API_KEY,baseURL: "https://silkdock.ai/v1",});const stream = await client.responses.create({model: "gpt-4o",input: [{ role: "user", content: "Write a short poem" }],stream: true,});for await (const event of stream) {if (event.type === "response.output_text.delta") process.stdout.write(event.delta);}import OpenAI from "openai";const client = new OpenAI({apiKey: process.env.SILKDOCK_API_KEY,baseURL: "https://silkdock.ai/v1",});const stream = await client.responses.create({model: "gpt-4o",input: [{ role: "user", content: "Write a short poem" }],stream: true,});for await (const event of stream) {if (event.type === "response.output_text.delta") process.stdout.write(event.delta);}import requests, json, oswith requests.post( "https://silkdock.ai/v1/responses", headers={"Authorization": f"Bearer {os.getenv('SILKDOCK_API_KEY')}"}, json={ "model": "gpt-4o", "stream": True, "input": [{"role": "user", "content": "Write a short poem"}], }, stream=True,) as res: for line in res.iter_lines(): if not line or line == b"data: [DONE]": continue chunk = json.loads(line.removeprefix(b"data: ")) print(chunk["choices"][0]["delta"].get("content", ""), end="", flush=True)#include <stdio.h>#include <string.h>#include <curl/curl.h>static size_t write_cb(char *ptr, size_t size, size_t nmemb, void *userdata) { size_t total = size * nmemb; /* ptr may contain multiple lines separated by \n */ char buf[8192]; memcpy(buf, ptr, total < sizeof(buf) - 1 ? total : sizeof(buf) - 1); buf[total < sizeof(buf) - 1 ? total : sizeof(buf) - 1] = '\0'; char *line = strtok(buf, "\n"); while (line) { if (strncmp(line, "data: ", 6) == 0 && strcmp(line, "data: [DONE]") != 0) { printf("%s\n", line + 6); fflush(stdout); } line = strtok(NULL, "\n"); } return total;}int main(void) { CURL *curl = curl_easy_init(); if (!curl) return 1; const char *api_key = getenv("SILKDOCK_API_KEY"); char auth_header[256]; snprintf(auth_header, sizeof(auth_header), "Authorization: Bearer %s", api_key ? api_key : ""); struct curl_slist *headers = NULL; headers = curl_slist_append(headers, auth_header); headers = curl_slist_append(headers, "Content-Type: application/json"); const char *body = "{\"model\":\"gpt-4o\",\"action\":\"chat\",\"stream\":true," "\"messages\":[{\"role\":\"user\",\"content\":\"Write a short poem\"}]}"; curl_easy_setopt(curl, CURLOPT_URL, "https://silkdock.ai/v1/responses"); curl_easy_setopt(curl, CURLOPT_POST, 1L); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_cb); curl_easy_setopt(curl, CURLOPT_BUFFERSIZE, 1L); /* minimize buffering */ curl_easy_perform(curl); curl_slist_free_all(headers); curl_easy_cleanup(curl); return 0;}#import <Foundation/Foundation.h>@interface StreamDelegate : NSObject <NSURLSessionDataDelegate>@property (nonatomic, strong) NSMutableData *buffer;@end@implementation StreamDelegate- (instancetype)init { self = [super init]; _buffer = [NSMutableData data]; return self;}- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { [self.buffer appendData:data]; // Process complete lines NSString *text = [[NSString alloc] initWithData:self.buffer encoding:NSUTF8StringEncoding]; NSArray<NSString *> *lines = [text componentsSeparatedByString:@"\n"]; NSMutableData *remainder = [NSMutableData data]; for (NSUInteger i = 0; i < lines.count; i++) { NSString *line = lines[i]; if (i == lines.count - 1) { // Last segment may be incomplete [remainder appendData:[line dataUsingEncoding:NSUTF8StringEncoding]]; break; } if ([line hasPrefix:@"data: "] && ![line isEqualToString:@"data: [DONE]"]) { NSString *json = [line substringFromIndex:6]; NSLog(@"%@", json); } } self.buffer = remainder;}- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)taskdidCompleteWithError:(NSError *)error { if (error) NSLog(@"Error: %@", error); CFRunLoopStop(CFRunLoopGetMain());}@endint main(int argc, const char *argv[]) { @autoreleasepool { NSURL *url = [NSURL URLWithString:@"https://silkdock.ai/v1/responses"]; NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url]; req.HTTPMethod = @"POST"; NSString *apiKey = [NSProcessInfo.processInfo.environment objectForKey:@"SILKDOCK_API_KEY"]; [req setValue:[NSString stringWithFormat:@"Bearer %@", apiKey] forHTTPHeaderField:@"Authorization"]; [req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; NSDictionary *bodyDict = @{ @"model": @"gpt-4o", @"stream": @YES, @"input": @[@{@"role": @"user", @"content": @"Write a short poem"}], }; req.HTTPBody = [NSJSONSerialization dataWithJSONObject:bodyDict options:0 error:nil]; StreamDelegate *delegate = [[StreamDelegate alloc] init]; NSURLSession *session = [NSURLSession sessionWithConfiguration:NSURLSessionConfiguration.defaultSessionConfiguration delegate:delegate delegateQueue:nil]; [[session dataTaskWithRequest:req] resume]; CFRunLoopRun(); } return 0;}import java.net.http.*;import java.net.URI;import java.io.*;var req = HttpRequest.newBuilder() .uri(URI.create("https://silkdock.ai/v1/responses")) .header("Authorization", "Bearer " + System.getenv("SILKDOCK_API_KEY")) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString( """{"model":"gpt-4o","stream":true, "input":[{"role":"user","content":"Write a short poem"}]}""")) .build();HttpClient.newHttpClient() .send(req, HttpResponse.BodyHandlers.ofLines()) .body() .filter(line -> line.startsWith("data: ") && !line.equals("data: [DONE]")) .map(line -> line.substring(6)) .forEach(System.out::println);package mainimport ( "bufio" "bytes" "encoding/json" "fmt" "net/http" "os" "strings")func main() { body, _ := json.Marshal(map[string]any{ "model": "gpt-4o", "stream": true, "input": []map[string]string{{"role": "user", "content": "Write a short poem"}}, }) req, _ := http.NewRequest("POST", "https://silkdock.ai/v1/responses", bytes.NewReader(body)) req.Header.Set("Authorization", "Bearer "+os.Getenv("SILKDOCK_API_KEY")) req.Header.Set("Content-Type", "application/json") resp, _ := http.DefaultClient.Do(req) defer resp.Body.Close() scanner := bufio.NewScanner(resp.Body) for scanner.Scan() { line := scanner.Text() if !strings.HasPrefix(line, "data: ") || line == "data: [DONE]" { continue } var chunk map[string]any json.Unmarshal([]byte(line[6:]), &chunk) fmt.Print(chunk) }}<?php$ch = curl_init("https://silkdock.ai/v1/responses");curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => false, CURLOPT_HTTPHEADER => [ "Authorization: Bearer " . getenv("SILKDOCK_API_KEY"), "Content-Type: application/json", ], CURLOPT_POSTFIELDS => json_encode([ "model" => "gpt-4o", "stream" => true, "input" => [["role" => "user", "content" => "Write a short poem"]], ]), CURLOPT_WRITEFUNCTION => function($ch, $data) { echo $data; flush(); return strlen($data); },]);curl_exec($ch);import Foundationvar req = URLRequest(url: URL(string: "https://silkdock.ai/v1/responses")!)req.httpMethod = "POST"req.setValue("Bearer \(ProcessInfo.processInfo.environment["SILKDOCK_API_KEY"]!)", forHTTPHeaderField: "Authorization")req.setValue("application/json", forHTTPHeaderField: "Content-Type")req.httpBody = try! JSONSerialization.data(withJSONObject: [ "model": "gpt-4o", "stream": true, "input": [["role": "user", "content": "Write a short poem"]],])let (stream, _) = try! await URLSession.shared.bytes(for: req)for try await line in stream.lines { guard line.hasPrefix("data: "), line != "data: [DONE]" else { continue } print(line.dropFirst(6))}using System.Net.Http;using System.Net.Http.Json;var client = new HttpClient();client.DefaultRequestHeaders.Add("Authorization", $"Bearer {Environment.GetEnvironmentVariable("SILKDOCK_API_KEY")}");var res = await client.PostAsJsonAsync("https://silkdock.ai/v1/responses", new { model = "gpt-4o", stream = true, input = new[] { new { role = "user", content = "Write a short poem" } },});using var reader = new StreamReader(await res.Content.ReadAsStreamAsync());while (!reader.EndOfStream) { var line = await reader.ReadLineAsync(); if (line?.StartsWith("data: ") == true && line != "data: [DONE]") Console.WriteLine(line[6..]);}require "net/http"require "json"uri = URI("https://silkdock.ai/v1/responses")req = Net::HTTP::Post.new(uri)req["Authorization"] = "Bearer #{ENV['SILKDOCK_API_KEY']}"req["Content-Type"] = "application/json"req.body = {model: "gpt-4o", stream: true,input: [{ role: "user", content: "Write a short poem" }]}.to_jsonNet::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|http.request(req) do |res| res.read_body do |chunk| chunk.each_line do |line| next unless line.start_with?("data: ") && line.strip != "data: [DONE]" puts line[6..] end endendendimport java.net.http.*import java.net.URIval req = HttpRequest.newBuilder() .uri(URI.create("https://silkdock.ai/v1/responses")) .header("Authorization", "Bearer ${System.getenv("SILKDOCK_API_KEY")}") .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString( """{"model":"gpt-4o","stream":true, "input":[{"role":"user","content":"Write a short poem"}]}""")) .build()HttpClient.newHttpClient() .send(req, HttpResponse.BodyHandlers.ofLines()) .body() .filter { it.startsWith("data: ") && it != "data: [DONE]" } .forEach { println(it.substring(6)) }use reqwest::blocking::Client;use serde_json::json;use std::io::{BufRead, BufReader};fn main() -> Result<(), Box<dyn std::error::Error>> { let res = Client::new() .post("https://silkdock.ai/v1/responses") .header("Authorization", format!("Bearer {}", std::env::var("SILKDOCK_API_KEY")?)) .json(&json!({ "model": "gpt-4o", "stream": true, "input": [{"role": "user", "content": "Write a short poem"}] })) .send()?; for line in BufReader::new(res).lines().flatten() { if line.starts_with("data: ") && line != "data: [DONE]" { println!("{}", &line[6..]); } } Ok(())}POST /v1/responses HTTP/1.1Host: silkdock.aiAuthorization: Bearer <YOUR_API_KEY>Content-Type: application/json{"model": "gpt-4o","stream": true,"input": [{"role": "user", "content": "Write a short poem"}]}import 'dart:convert';import 'package:http/http.dart' as http;void main() async {final req = http.Request('POST', Uri.parse('https://silkdock.ai/v1/responses')) ..headers['Authorization'] = 'Bearer ${const String.fromEnvironment("SILKDOCK_API_KEY")}' ..headers['Content-Type'] = 'application/json' ..body = jsonEncode({ 'model': 'gpt-4o', 'stream': true, 'messages': [{'role': 'user', 'content': 'Write a short poem'}], });final res = await http.Client().send(req);await for (final chunk in res.stream.transform(utf8.decoder).transform(const LineSplitter())) { if (chunk.startsWith('data: ') && chunk != 'data: [DONE]') { print(chunk.substring(6)); }}}library(httr2)req <- request("https://silkdock.ai/v1/responses") |>req_headers( Authorization = paste("Bearer", Sys.getenv("SILKDOCK_API_KEY")), "Content-Type" = "application/json") |>req_body_json(list( model = "gpt-4o", action = "chat", stream = TRUE, messages = list(list(role = "user", content = "Write a short poem"))))# Stream response line by lineresp <- req_perform_connection(req)while (!is.null(line <- readLines(resp, n = 1, warn = FALSE))) {if (startsWith(line, "data: ") && line != "data: [DONE]") cat(substring(line, 7), "\n")}(* requires cohttp-lwt-unix: opam install cohttp-lwt-unix *)open Cohttp_lwt_unixopen Cohttpopen Lwtlet () =let body = {|{"model":"gpt-4o","stream":true, "input":[{"role":"user","content":"Write a short poem"}]}|}inlet headers = Header.of_list [ ("Authorization", "Bearer " ^ Sys.getenv "SILKDOCK_API_KEY") ; ("Content-Type", "application/json") ]inLwt_main.run ( Client.post ~headers ~body:(Cohttp_lwt.Body.of_string body) (Uri.of_string "https://silkdock.ai/v1/responses") >>= fun (_, body) -> Cohttp_lwt.Body.to_string body >>= fun s -> String.split_on_char '\n' s |> List.iter (fun line -> if String.length line > 6 && String.sub line 0 6 = "data: " then print_string (String.sub line 6 (String.length line - 6))); return_unit )curl -X POST https://silkdock.ai/v1/responses \-H "Authorization: Bearer $SILKDOCK_API_KEY" \-H "Content-Type: application/json" \-d '{ "action": "embedding", "model": "text-embedding-3-small", "input": ["Hello world", "Goodbye world"]}'const { OpenAI } = require("openai");const client = new OpenAI({apiKey: process.env.SILKDOCK_API_KEY,baseURL: "https://silkdock.ai/v1",});const response = await client.embeddings.create({model: "text-embedding-3-small",input: ["Hello world", "Goodbye world"],});response.data.forEach(item => {console.log(`[${item.index}] ${item.embedding.slice(0, 3)} ...`);});import OpenAI from "openai";const client = new OpenAI({apiKey: process.env.SILKDOCK_API_KEY,baseURL: "https://silkdock.ai/v1",});const response = await client.embeddings.create({model: "text-embedding-3-small",input: ["Hello world", "Goodbye world"],});response.data.forEach(item => {console.log(`[${item.index}] ${item.embedding.slice(0, 3)} ...`);});import requests, osres = requests.post( "https://silkdock.ai/v1/responses", headers={"Authorization": f"Bearer {os.getenv('SILKDOCK_API_KEY')}"}, json={ "action": "embedding", "model": "text-embedding-3-small", "input": ["Hello world", "Goodbye world"], },)for item in res.json()["data"]: print(f"[{item['index']}] {item['embedding'][:3]} ...")#include <stdio.h>#include <curl/curl.h>int main(void) { CURL *curl = curl_easy_init(); if (!curl) return 1; struct curl_slist *headers = NULL; headers = curl_slist_append(headers, "Content-Type: application/json"); headers = curl_slist_append(headers, "Authorization: Bearer " SILKDOCK_API_KEY); const char *body = "{"model":"text-embedding-3-small","action":"embedding"," ""input":["Hello world","Goodbye world"]}"; curl_easy_setopt(curl, CURLOPT_URL, "https://silkdock.ai/v1/responses"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body); curl_easy_perform(curl); curl_slist_free_all(headers); curl_easy_cleanup(curl); return 0;}/* compile: gcc main.c -lcurl -o main */#import <Foundation/Foundation.h>NSURLSession *session = [NSURLSession sharedSession];NSURL *url = [NSURL URLWithString:@"https://silkdock.ai/v1/responses"];NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];[request setHTTPMethod:@"POST"];[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];[request setValue:[@"Bearer " stringByAppendingString: [NSProcessInfo.processInfo.environment objectForKey:@"SILKDOCK_API_KEY"]] forHTTPHeaderField:@"Authorization"];NSDictionary *payload = @{ @"model": @"text-embedding-3-small", @"input": @[@"Hello world", @"Goodbye world"]};[request setHTTPBody:[NSJSONSerialization dataWithJSONObject:payload options:0 error:nil]];NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; NSLog(@"%@", json[@"data"][0][@"embedding"]); }];[task resume];import java.net.http.*;import java.net.URI;var req = HttpRequest.newBuilder() .uri(URI.create("https://silkdock.ai/v1/responses")) .header("Authorization", "Bearer " + System.getenv("SILKDOCK_API_KEY")) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString( """{"model":"text-embedding-3-small", "input":["Hello world","Goodbye world"]}""")) .build();System.out.println(HttpClient.newHttpClient().send(req, HttpResponse.BodyHandlers.ofString()).body());package mainimport ( "bytes" "encoding/json" "fmt" "io" "net/http" "os")func main() { body, _ := json.Marshal(map[string]any{ "model": "text-embedding-3-small", "input": []string{"Hello world", "Goodbye world"}, }) req, _ := http.NewRequest("POST", "https://silkdock.ai/v1/responses", bytes.NewReader(body)) req.Header.Set("Authorization", "Bearer "+os.Getenv("SILKDOCK_API_KEY")) req.Header.Set("Content-Type", "application/json") resp, _ := http.DefaultClient.Do(req) defer resp.Body.Close() data, _ := io.ReadAll(resp.Body) fmt.Println(string(data))}<?php$ch = curl_init("https://silkdock.ai/v1/responses");curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ "Authorization: Bearer " . getenv("SILKDOCK_API_KEY"), "Content-Type: application/json", ], CURLOPT_POSTFIELDS => json_encode([ "model" => "text-embedding-3-small", "input" => ["Hello world", "Goodbye world"], ]),]);echo curl_exec($ch);import Foundationvar req = URLRequest(url: URL(string: "https://silkdock.ai/v1/responses")!)req.httpMethod = "POST"req.setValue("Bearer \(ProcessInfo.processInfo.environment["SILKDOCK_API_KEY"]!)", forHTTPHeaderField: "Authorization")req.setValue("application/json", forHTTPHeaderField: "Content-Type")req.httpBody = try! JSONSerialization.data(withJSONObject: [ "model": "text-embedding-3-small", "input": ["Hello world", "Goodbye world"],])let (data, _) = try! await URLSession.shared.data(for: req)print(String(data: data, encoding: .utf8)!)using System.Net.Http;using System.Net.Http.Json;var client = new HttpClient();client.DefaultRequestHeaders.Add("Authorization", $"Bearer {Environment.GetEnvironmentVariable("SILKDOCK_API_KEY")}");var res = await client.PostAsJsonAsync("https://silkdock.ai/v1/responses", new { model = "text-embedding-3-small", input = new[] { "Hello world", "Goodbye world" },});Console.WriteLine(await res.Content.ReadAsStringAsync());require "net/http"require "json"uri = URI("https://silkdock.ai/v1/responses")req = Net::HTTP::Post.new(uri)req["Authorization"] = "Bearer #{ENV['SILKDOCK_API_KEY']}"req["Content-Type"] = "application/json"req.body = {model: "text-embedding-3-small",action: "embedding",input: ["Hello world", "Goodbye world"]}.to_jsonres = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |h| h.request(req) }puts res.bodyimport java.net.http.*import java.net.URIval req = HttpRequest.newBuilder() .uri(URI.create("https://silkdock.ai/v1/responses")) .header("Authorization", "Bearer ${System.getenv("SILKDOCK_API_KEY")}") .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString( """{"model":"text-embedding-3-small", "input":["Hello world","Goodbye world"]}""")) .build()println(HttpClient.newHttpClient().send(req, HttpResponse.BodyHandlers.ofString()).body())use reqwest::blocking::Client;use serde_json::json;fn main() -> Result<(), Box<dyn std::error::Error>> { let res = Client::new() .post("https://silkdock.ai/v1/responses") .header("Authorization", format!("Bearer {}", std::env::var("SILKDOCK_API_KEY")?)) .json(&json!({ "model": "text-embedding-3-small", "input": ["Hello world", "Goodbye world"] })) .send()?; println!("{}", res.text()?); Ok(())}POST /v1/responses HTTP/1.1Host: silkdock.aiAuthorization: Bearer <YOUR_API_KEY>Content-Type: application/json{"model": "text-embedding-3-small","input": ["Hello world", "Goodbye world"]}import 'dart:convert';import 'package:http/http.dart' as http;void main() async {final res = await http.post( Uri.parse('https://silkdock.ai/v1/responses'), headers: { 'Authorization': 'Bearer ${const String.fromEnvironment("SILKDOCK_API_KEY")}', 'Content-Type': 'application/json', }, body: jsonEncode({ 'model': 'text-embedding-3-small', 'input': ['Hello world', 'Goodbye world'], }),);print(res.body);}library(httr2)req <- request("https://silkdock.ai/v1/responses") |>req_headers( Authorization = paste("Bearer", Sys.getenv("SILKDOCK_API_KEY")), "Content-Type" = "application/json") |>req_body_json(list( model = "text-embedding-3-small", input = list("Hello world", "Goodbye world")))resp <- req_perform(req)cat(resp_body_string(resp))(* requires cohttp-lwt-unix *)open Cohttp_lwt_unixopen Cohttpopen Lwtlet () =let body = {|{"model":"text-embedding-3-small", "input":["Hello world","Goodbye world"]}|} inlet headers = Header.of_list [ "Authorization", "Bearer " ^ Sys.getenv "SILKDOCK_API_KEY"; "Content-Type", "application/json";] inLwt_main.run ( Client.post ~headers ~body:(Cohttp_lwt.Body.of_string body) (Uri.of_string "https://silkdock.ai/v1/responses") >>= fun (_, body) -> Cohttp_lwt.Body.to_string body >>= fun s -> print_string s; return_unit)curl -X POST https://silkdock.ai/v1/responses \-H "Authorization: Bearer $SILKDOCK_API_KEY" \-H "Content-Type: application/json" \-d '{ "action": "image", "model": "gpt-image-2.5-sunburst", "prompt": "An orange cat walking in space, cyberpunk style", "size": "1:1", "quality": "xhigh"}'const { OpenAI } = require("openai");const client = new OpenAI({apiKey: process.env.SILKDOCK_API_KEY,baseURL: "https://silkdock.ai/v1",});const response = await client.images.generate({model: "gpt-image-2.5-sunburst",prompt: "An orange cat walking in space, cyberpunk style",n: 1,size: "1:1",quality: "xhigh",});console.log(response.data[0].url);import OpenAI from "openai";const client = new OpenAI({apiKey: process.env.SILKDOCK_API_KEY,baseURL: "https://silkdock.ai/v1",});const response = await client.images.generate({model: "gpt-image-2.5-sunburst",prompt: "An orange cat walking in space, cyberpunk style",n: 1,size: "1:1",quality: "xhigh",});console.log(response.data[0].url);import requests, osres = requests.post( "https://silkdock.ai/v1/responses", headers={"Authorization": f"Bearer {os.getenv('SILKDOCK_API_KEY')}"}, json={ "action": "image", "model": "gpt-image-2.5-sunburst", "prompt": "An orange cat walking in space, cyberpunk style", "size": "1:1", "quality": "xhigh", },)print(res.json()["data"][0]["url"])#include <stdio.h>#include <curl/curl.h>int main(void) { CURL *curl = curl_easy_init(); if (!curl) return 1; struct curl_slist *headers = NULL; headers = curl_slist_append(headers, "Content-Type: application/json"); headers = curl_slist_append(headers, "Authorization: Bearer " SILKDOCK_API_KEY); const char *body = "{\"model\":\"gpt-image-2.5-sunburst\",\"action\":\"image\"," "\"prompt\":\"An orange cat walking in space, cyberpunk style\"," "\"size\":\"1:1\",\"quality\":\"xhigh\"}"; curl_easy_setopt(curl, CURLOPT_URL, "https://silkdock.ai/v1/responses"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body); curl_easy_perform(curl); curl_slist_free_all(headers); curl_easy_cleanup(curl); return 0;}/* compile: gcc main.c -lcurl -o main */#import <Foundation/Foundation.h>NSURLSession *session = [NSURLSession sharedSession];NSURL *url = [NSURL URLWithString:@"https://silkdock.ai/v1/responses"];NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];[request setHTTPMethod:@"POST"];[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];[request setValue:[@"Bearer " stringByAppendingString: [NSProcessInfo.processInfo.environment objectForKey:@"SILKDOCK_API_KEY"]] forHTTPHeaderField:@"Authorization"];NSDictionary *payload = @{ @"model": @"gpt-image-2.5-sunburst", @"prompt": @"An orange cat walking in space, cyberpunk style", @"size": @"1:1", @"quality": @"xhigh"};[request setHTTPBody:[NSJSONSerialization dataWithJSONObject:payload options:0 error:nil]];NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; NSLog(@"%@", json[@"data"][0][@"url"]); }];[task resume];import java.net.http.*;import java.net.URI;var req = HttpRequest.newBuilder() .uri(URI.create("https://silkdock.ai/v1/responses")) .header("Authorization", "Bearer " + System.getenv("SILKDOCK_API_KEY")) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString( """{"model":"gpt-image-2.5-sunburst", "prompt":"An orange cat walking in space, cyberpunk style", "size":"1:1","quality":"xhigh"}""")) .build();System.out.println(HttpClient.newHttpClient().send(req, HttpResponse.BodyHandlers.ofString()).body());package mainimport ( "bytes" "encoding/json" "fmt" "io" "net/http" "os")func main() { body, _ := json.Marshal(map[string]any{ "model": "gpt-image-2.5-sunburst", "prompt": "An orange cat walking in space, cyberpunk style", "size": "1:1", "quality": "xhigh", }) req, _ := http.NewRequest("POST", "https://silkdock.ai/v1/responses", bytes.NewReader(body)) req.Header.Set("Authorization", "Bearer "+os.Getenv("SILKDOCK_API_KEY")) req.Header.Set("Content-Type", "application/json") resp, _ := http.DefaultClient.Do(req) defer resp.Body.Close() data, _ := io.ReadAll(resp.Body) fmt.Println(string(data))}<?php$ch = curl_init("https://silkdock.ai/v1/responses");curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ "Authorization: Bearer " . getenv("SILKDOCK_API_KEY"), "Content-Type: application/json", ], CURLOPT_POSTFIELDS => json_encode([ "model" => "gpt-image-2.5-sunburst", "prompt" => "An orange cat walking in space, cyberpunk style", "size" => "1:1", "quality" => "xhigh", ]),]);$res = json_decode(curl_exec($ch), true);echo $res["data"][0]["url"];import Foundationvar req = URLRequest(url: URL(string: "https://silkdock.ai/v1/responses")!)req.httpMethod = "POST"req.setValue("Bearer \(ProcessInfo.processInfo.environment["SILKDOCK_API_KEY"]!)", forHTTPHeaderField: "Authorization")req.setValue("application/json", forHTTPHeaderField: "Content-Type")req.httpBody = try! JSONSerialization.data(withJSONObject: [ "model": "gpt-image-2.5-sunburst", "prompt": "An orange cat walking in space, cyberpunk style", "size": "1:1", "quality": "xhigh",])let (data, _) = try! await URLSession.shared.data(for: req)print(String(data: data, encoding: .utf8)!)using System.Net.Http;using System.Net.Http.Json;var client = new HttpClient();client.DefaultRequestHeaders.Add("Authorization", $"Bearer {Environment.GetEnvironmentVariable("SILKDOCK_API_KEY")}");var res = await client.PostAsJsonAsync("https://silkdock.ai/v1/responses", new { model = "gpt-image-2.5-sunburst", action = "image", prompt = "An orange cat walking in space, cyberpunk style", size = "1:1", quality = "xhigh",});Console.WriteLine(await res.Content.ReadAsStringAsync());require "net/http"require "json"uri = URI("https://silkdock.ai/v1/responses")req = Net::HTTP::Post.new(uri)req["Authorization"] = "Bearer #{ENV['SILKDOCK_API_KEY']}"req["Content-Type"] = "application/json"req.body = {model: "gpt-image-2.5-sunburst", action: "image",prompt: "An orange cat walking in space, cyberpunk style",size: "1:1", quality: "xhigh"}.to_jsonres = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |h| h.request(req) }puts JSON.parse(res.body)["data"][0]["url"]import java.net.http.*import java.net.URIval req = HttpRequest.newBuilder() .uri(URI.create("https://silkdock.ai/v1/responses")) .header("Authorization", "Bearer ${System.getenv("SILKDOCK_API_KEY")}") .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString( """{"model":"gpt-image-2.5-sunburst", "prompt":"An orange cat walking in space, cyberpunk style", "size":"1:1","quality":"xhigh"}""")) .build()println(HttpClient.newHttpClient().send(req, HttpResponse.BodyHandlers.ofString()).body())use reqwest::blocking::Client;use serde_json::json;fn main() -> Result<(), Box<dyn std::error::Error>> { let res = Client::new() .post("https://silkdock.ai/v1/responses") .header("Authorization", format!("Bearer {}", std::env::var("SILKDOCK_API_KEY")?)) .json(&json!({ "model": "gpt-image-2.5-sunburst", "prompt": "An orange cat walking in space, cyberpunk style", "size": "1:1", "quality": "xhigh" })) .send()?; println!("{}", res.text()?); Ok(())}POST /v1/responses HTTP/1.1Host: silkdock.aiAuthorization: Bearer <YOUR_API_KEY>Content-Type: application/json{"model": "gpt-image-2.5-sunburst","prompt": "An orange cat walking in space, cyberpunk style","size": "1:1","quality": "xhigh"}import 'dart:convert';import 'package:http/http.dart' as http;void main() async {final res = await http.post( Uri.parse('https://silkdock.ai/v1/responses'), headers: { 'Authorization': 'Bearer ${const String.fromEnvironment("SILKDOCK_API_KEY")}', 'Content-Type': 'application/json', }, body: jsonEncode({ 'model': 'gpt-image-2.5-sunburst', 'prompt': 'An orange cat walking in space, cyberpunk style', 'size': '1:1', 'quality': 'xhigh', }),);final data = jsonDecode(res.body);print(data['data'][0]['url']);}library(httr2)req <- request("https://silkdock.ai/v1/responses") |>req_headers( Authorization = paste("Bearer", Sys.getenv("SILKDOCK_API_KEY")), "Content-Type" = "application/json") |>req_body_json(list( model = "gpt-image-2.5-sunburst", action = "image", prompt = "An orange cat walking in space, cyberpunk style", size = "1:1", quality = "xhigh"))resp <- req_perform(req)cat(resp_body_json(resp)$data[[1]]$url)(* requires cohttp-lwt-unix *)open Cohttp_lwt_unixopen Cohttpopen Lwtlet () =let body = {|{"model":"gpt-image-2.5-sunburst", "prompt":"An orange cat walking in space, cyberpunk style", "size":"1:1","quality":"xhigh"}|} inlet headers = Header.of_list [ "Authorization", "Bearer " ^ Sys.getenv "SILKDOCK_API_KEY"; "Content-Type", "application/json";] inLwt_main.run ( Client.post ~headers ~body:(Cohttp_lwt.Body.of_string body) (Uri.of_string "https://silkdock.ai/v1/responses") >>= fun (_, body) -> Cohttp_lwt.Body.to_string body >>= fun s -> print_string s; return_unit)curl -X POST https://silkdock.ai/v1/responses \-H "Authorization: Bearer $SILKDOCK_API_KEY" \-H "Content-Type: application/json" \-d '{ "action": "tts", "model": "tts-1", "input": "Hello, world!", "voice": "alloy"}' \--output speech.mp3const { OpenAI } = require("openai");const fs = require("fs");const path = require("path");const client = new OpenAI({apiKey: process.env.SILKDOCK_API_KEY,baseURL: "https://silkdock.ai/v1",});const mp3 = await client.audio.speech.create({model: "tts-1",voice: "alloy",input: "Hello, welcome to the text-to-speech service.",});const buffer = Buffer.from(await mp3.arrayBuffer());fs.writeFileSync(path.resolve("./output.mp3"), buffer);console.log("Saved to output.mp3");import OpenAI from "openai";import { writeFileSync } from "fs";import path from "path";const client = new OpenAI({apiKey: process.env.SILKDOCK_API_KEY,baseURL: "https://silkdock.ai/v1",});const mp3 = await client.audio.speech.create({model: "tts-1",voice: "alloy",input: "Hello, welcome to the text-to-speech service.",});writeFileSync(path.resolve("./output.mp3"), Buffer.from(await mp3.arrayBuffer()));console.log("Saved to output.mp3");import requests, osres = requests.post( "https://silkdock.ai/v1/responses", headers={"Authorization": f"Bearer {os.getenv('SILKDOCK_API_KEY')}"}, json={ "action": "tts", "model": "tts-1", "input": "Hello, welcome to the text-to-speech service.", "voice": "alloy", "response_format": "mp3", },)with open("output.mp3", "wb") as f: f.write(res.content)print("Saved to output.mp3")#include <stdio.h>#include <stdlib.h>#include <string.h>#include <curl/curl.h>struct Buffer { unsigned char *data; size_t size;};static size_t write_cb(void *ptr, size_t size, size_t nmemb, void *userdata) { size_t total = size * nmemb; struct Buffer *buf = (struct Buffer *)userdata; unsigned char *tmp = realloc(buf->data, buf->size + total); if (!tmp) return 0; buf->data = tmp; memcpy(buf->data + buf->size, ptr, total); buf->size += total; return total;}int main(void) { const char *api_key = getenv("SILKDOCK_API_KEY"); char auth_header[256]; snprintf(auth_header, sizeof(auth_header), "Authorization: Bearer %s", api_key); const char *body = "{"model":"tts-1","action":"tts"," ""input":"Hello, world!","voice":"alloy"}"; struct Buffer buf = {NULL, 0}; struct curl_slist *headers = NULL; headers = curl_slist_append(headers, auth_header); headers = curl_slist_append(headers, "Content-Type: application/json"); CURL *curl = curl_easy_init(); curl_easy_setopt(curl, CURLOPT_URL, "https://silkdock.ai/v1/responses"); curl_easy_setopt(curl, CURLOPT_POST, 1L); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_cb); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buf); curl_easy_perform(curl); curl_easy_cleanup(curl); curl_slist_free_all(headers); FILE *fp = fopen("speech.mp3", "wb"); fwrite(buf.data, 1, buf.size, fp); fclose(fp); free(buf.data); printf("Saved to speech.mp3\n"); return 0;}#import <Foundation/Foundation.h>int main(int argc, const char *argv[]) { @autoreleasepool { NSString *apiKey = [NSProcessInfo processInfo].environment[@"SILKDOCK_API_KEY"]; NSURL *url = [NSURL URLWithString:@"https://silkdock.ai/v1/responses"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; request.HTTPMethod = @"POST"; [request setValue:[NSString stringWithFormat:@"Bearer %@", apiKey] forHTTPHeaderField:@"Authorization"]; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; NSDictionary *bodyDict = @{ @"model": @"tts-1", @"input": @"Hello, world!", @"voice": @"alloy" }; request.HTTPBody = [NSJSONSerialization dataWithJSONObject:bodyDict options:0 error:nil]; dispatch_semaphore_t sem = dispatch_semaphore_create(0); NSURLSession *session = [NSURLSession sharedSession]; [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"speech.mp3"]; [data writeToFile:path atomically:YES]; NSLog(@"Saved to %@", path); dispatch_semaphore_signal(sem); }] resume]; dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER); } return 0;}import java.net.http.*;import java.net.URI;import java.nio.file.*;var req = HttpRequest.newBuilder() .uri(URI.create("https://silkdock.ai/v1/responses")) .header("Authorization", "Bearer " + System.getenv("SILKDOCK_API_KEY")) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString( """{"model":"tts-1", "input":"Hello, welcome to the text-to-speech service.", "voice":"alloy","response_format":"mp3"}""")) .build();var res = HttpClient.newHttpClient().send(req, HttpResponse.BodyHandlers.ofByteArray());Files.write(Path.of("output.mp3"), res.body());System.out.println("Saved to output.mp3");package mainimport ( "bytes" "encoding/json" "net/http" "os")func main() { body, _ := json.Marshal(map[string]any{ "model": "tts-1", "input": "Hello, welcome to the text-to-speech service.", "voice": "alloy", "response_format": "mp3", }) req, _ := http.NewRequest("POST", "https://silkdock.ai/v1/responses", bytes.NewReader(body)) req.Header.Set("Authorization", "Bearer "+os.Getenv("SILKDOCK_API_KEY")) req.Header.Set("Content-Type", "application/json") resp, _ := http.DefaultClient.Do(req) defer resp.Body.Close() buf := new(bytes.Buffer) buf.ReadFrom(resp.Body) os.WriteFile("output.mp3", buf.Bytes(), 0644) println("Saved to output.mp3")}<?php$ch = curl_init("https://silkdock.ai/v1/responses");curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ "Authorization: Bearer " . getenv("SILKDOCK_API_KEY"), "Content-Type: application/json", ], CURLOPT_POSTFIELDS => json_encode([ "model" => "tts-1", "input" => "Hello, welcome to the text-to-speech service.", "voice" => "alloy", "response_format" => "mp3", ]),]);file_put_contents("output.mp3", curl_exec($ch));echo "Saved to output.mp3";import Foundationvar req = URLRequest(url: URL(string: "https://silkdock.ai/v1/responses")!)req.httpMethod = "POST"req.setValue("Bearer \(ProcessInfo.processInfo.environment["SILKDOCK_API_KEY"]!)", forHTTPHeaderField: "Authorization")req.setValue("application/json", forHTTPHeaderField: "Content-Type")req.httpBody = try! JSONSerialization.data(withJSONObject: [ "model": "tts-1", "input": "Hello, welcome to the text-to-speech service.", "voice": "alloy", "response_format": "mp3",])let (data, _) = try! await URLSession.shared.data(for: req)try! data.write(to: URL(fileURLWithPath: "output.mp3"))print("Saved to output.mp3")using System.Net.Http;using System.Net.Http.Json;var client = new HttpClient();client.DefaultRequestHeaders.Add("Authorization", $"Bearer {Environment.GetEnvironmentVariable("SILKDOCK_API_KEY")}");var res = await client.PostAsJsonAsync("https://silkdock.ai/v1/responses", new { model = "tts-1", action = "tts", input = "Hello, welcome to the text-to-speech service.", voice = "alloy", response_format = "mp3",});await File.WriteAllBytesAsync("output.mp3", await res.Content.ReadAsByteArrayAsync());Console.WriteLine("Saved to output.mp3");require "net/http"require "json"uri = URI("https://silkdock.ai/v1/responses")req = Net::HTTP::Post.new(uri)req["Authorization"] = "Bearer #{ENV['SILKDOCK_API_KEY']}"req["Content-Type"] = "application/json"req.body = {model: "tts-1", action: "tts",input: "Hello, welcome to the text-to-speech service.",voice: "alloy", response_format: "mp3"}.to_jsonres = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |h| h.request(req) }File.binwrite("output.mp3", res.body)puts "Saved to output.mp3"import java.net.http.*import java.net.URIimport java.nio.file.Filesimport java.nio.file.Pathval req = HttpRequest.newBuilder() .uri(URI.create("https://silkdock.ai/v1/responses")) .header("Authorization", "Bearer ${System.getenv("SILKDOCK_API_KEY")}") .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString( """{"model":"tts-1", "input":"Hello, welcome to the text-to-speech service.", "voice":"alloy","response_format":"mp3"}""")) .build()val res = HttpClient.newHttpClient().send(req, HttpResponse.BodyHandlers.ofByteArray())Files.write(Path.of("output.mp3"), res.body())println("Saved to output.mp3")use reqwest::blocking::Client;use serde_json::json;use std::fs;fn main() -> Result<(), Box<dyn std::error::Error>> { let bytes = Client::new() .post("https://silkdock.ai/v1/responses") .header("Authorization", format!("Bearer {}", std::env::var("SILKDOCK_API_KEY")?)) .json(&json!({ "model": "tts-1", "input": "Hello, welcome to the text-to-speech service.", "voice": "alloy", "response_format": "mp3" })) .send()? .bytes()?; fs::write("output.mp3", &bytes)?; println!("Saved to output.mp3"); Ok(())}POST /v1/responses HTTP/1.1Host: silkdock.aiAuthorization: Bearer <YOUR_API_KEY>Content-Type: application/json{"model": "tts-1","input": "Hello, welcome to the text-to-speech service.","voice": "alloy","response_format": "mp3"}import 'dart:io';import 'dart:convert';import 'package:http/http.dart' as http;void main() async {final res = await http.post( Uri.parse('https://silkdock.ai/v1/responses'), headers: { 'Authorization': 'Bearer ${const String.fromEnvironment("SILKDOCK_API_KEY")}', 'Content-Type': 'application/json', }, body: jsonEncode({ 'model': 'tts-1', 'input': 'Hello, welcome to the text-to-speech service.', 'voice': 'alloy', 'response_format': 'mp3', }),);await File('output.mp3').writeAsBytes(res.bodyBytes);print('Saved to output.mp3');}library(httr2)req <- request("https://silkdock.ai/v1/responses") |>req_headers( Authorization = paste("Bearer", Sys.getenv("SILKDOCK_API_KEY")), "Content-Type" = "application/json") |>req_body_json(list( model = "tts-1", action = "tts", input = "Hello, welcome to the text-to-speech service.", voice = "alloy", response_format = "mp3"))resp <- req_perform(req)writeBin(resp_body_raw(resp), "output.mp3")cat("Saved to output.mp3")(* requires cohttp-lwt-unix *)open Cohttp_lwt_unixopen Cohttpopen Lwtlet () =let body = {|{"model":"tts-1", "input":"Hello, welcome to the text-to-speech service.", "voice":"alloy","response_format":"mp3"}|} inlet headers = Header.of_list [ "Authorization", "Bearer " ^ Sys.getenv "SILKDOCK_API_KEY"; "Content-Type", "application/json";] inLwt_main.run ( Client.post ~headers ~body:(Cohttp_lwt.Body.of_string body) (Uri.of_string "https://silkdock.ai/v1/responses") >>= fun (_, body) -> Cohttp_lwt.Body.to_string body >>= fun s -> let oc = open_out_bin "output.mp3" in output_string oc s; close_out oc; print_string "Saved to output.mp3"; return_unit)curl -X POST https://silkdock.ai/v1/audio/transcriptions \-H "Authorization: Bearer $SILKDOCK_API_KEY" \-F "model=whisper-1" \-F "[email protected]" \-F "language=en"const { OpenAI } = require("openai");const fs = require("fs");const client = new OpenAI({apiKey: process.env.SILKDOCK_API_KEY,baseURL: "https://silkdock.ai/v1",});const transcript = await client.audio.transcriptions.create({model: "whisper-1",file: fs.createReadStream("audio.mp3"),language: "en",});console.log(transcript.text);import OpenAI from "openai";import fs from "fs";const client = new OpenAI({apiKey: process.env.SILKDOCK_API_KEY,baseURL: "https://silkdock.ai/v1",});const transcript = await client.audio.transcriptions.create({model: "whisper-1",file: fs.createReadStream("audio.mp3"),language: "en",});console.log(transcript.text);import requests, oswith open("audio.mp3", "rb") as f: res = requests.post( "https://silkdock.ai/v1/audio/transcriptions", headers={"Authorization": f"Bearer {os.getenv('SILKDOCK_API_KEY')}"}, files={"file": ("audio.mp3", f, "audio/mpeg")}, data={"model": "whisper-1", "language": "en"}, )print(res.json()["text"])#include <stdio.h>#include <stdlib.h>#include <curl/curl.h>int main(void) { CURL *curl = curl_easy_init(); if (!curl) return 1; const char *api_key = getenv("SILKDOCK_API_KEY"); char auth_header[256]; snprintf(auth_header, sizeof(auth_header), "Authorization: Bearer %s", api_key); struct curl_slist *headers = NULL; headers = curl_slist_append(headers, auth_header); curl_mime *mime = curl_mime_init(curl); curl_mimepart *part = curl_mime_addpart(mime); curl_mime_name(part, "model"); curl_mime_data(part, "whisper-1", CURL_ZERO_TERMINATED); part = curl_mime_addpart(mime); curl_mime_name(part, "language"); curl_mime_data(part, "en", CURL_ZERO_TERMINATED); part = curl_mime_addpart(mime); curl_mime_name(part, "file"); curl_mime_filedata(part, "audio.mp3"); curl_mime_type(part, "audio/mpeg"); curl_easy_setopt(curl, CURLOPT_URL, "https://silkdock.ai/v1/audio/transcriptions"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_MIMEPOST, mime); CURLcode res = curl_easy_perform(curl); if (res != CURLE_OK) fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); curl_mime_free(mime); curl_slist_free_all(headers); curl_easy_cleanup(curl); return 0;}#import <Foundation/Foundation.h>int main(int argc, const char *argv[]) { @autoreleasepool { NSString *apiKey = [NSProcessInfo processInfo].environment[@"SILKDOCK_API_KEY"]; NSString *boundary = [[NSUUID UUID] UUIDString]; NSURL *url = [NSURL URLWithString:@"https://silkdock.ai/v1/audio/transcriptions"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; request.HTTPMethod = @"POST"; [request setValue:[NSString stringWithFormat:@"Bearer %@", apiKey] forHTTPHeaderField:@"Authorization"]; [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary] forHTTPHeaderField:@"Content-Type"]; NSMutableData *body = [NSMutableData data]; // model field [body appendData:[[NSString stringWithFormat: @"--%@
Content-Disposition: form-data; name="model"
whisper-1
", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; // language field [body appendData:[[NSString stringWithFormat: @"--%@
Content-Disposition: form-data; name="language"
en
", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; // file field NSData *audioData = [NSData dataWithContentsOfFile:@"audio.mp3"]; [body appendData:[[NSString stringWithFormat: @"--%@
Content-Disposition: form-data; name="file"; filename="audio.mp3"
Content-Type: audio/mpeg
", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:audioData]; [body appendData:[@"
" dataUsingEncoding:NSUTF8StringEncoding]]; // closing boundary [body appendData:[[NSString stringWithFormat:@"--%@--
", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; request.HTTPBody = body; dispatch_semaphore_t sema = dispatch_semaphore_create(0); [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (data) { NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; NSLog(@"%@", json[@"text"]); } dispatch_semaphore_signal(sema); }] resume]; dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER); } return 0;}import java.net.http.*;import java.net.URI;import java.nio.file.*;import java.util.UUID;String boundary = UUID.randomUUID().toString();byte[] fileBytes = Files.readAllBytes(Path.of("audio.mp3"));String partHeader = "--" + boundary + "
" + "Content-Disposition: form-data; name="file"; filename="audio.mp3"
" + "Content-Type: audio/mpeg
";String modelPart = "--" + boundary + "
" + "Content-Disposition: form-data; name="model"
whisper-1
";String closing = "--" + boundary + "--
";var body = java.io.ByteArrayOutputStream();body.write(modelPart.getBytes());body.write(partHeader.getBytes());body.write(fileBytes);body.write(("
" + closing).getBytes());var req = HttpRequest.newBuilder() .uri(URI.create("https://silkdock.ai/v1/audio/transcriptions")) .header("Authorization", "Bearer " + System.getenv("SILKDOCK_API_KEY")) .header("Content-Type", "multipart/form-data; boundary=" + boundary) .POST(HttpRequest.BodyPublishers.ofByteArray(body.toByteArray())) .build();System.out.println(HttpClient.newHttpClient().send(req, HttpResponse.BodyHandlers.ofString()).body());package mainimport ( "bytes" "fmt" "io" "mime/multipart" "net/http" "os" "path/filepath")func main() { var buf bytes.Buffer w := multipart.NewWriter(&buf) w.WriteField("model", "whisper-1") w.WriteField("language", "en") f, _ := os.Open("audio.mp3") defer f.Close() part, _ := w.CreateFormFile("file", filepath.Base("audio.mp3")) io.Copy(part, f) w.Close() req, _ := http.NewRequest("POST", "https://silkdock.ai/v1/audio/transcriptions", &buf) req.Header.Set("Authorization", "Bearer "+os.Getenv("SILKDOCK_API_KEY")) req.Header.Set("Content-Type", w.FormDataContentType()) resp, _ := http.DefaultClient.Do(req) defer resp.Body.Close() data, _ := io.ReadAll(resp.Body) fmt.Println(string(data))}<?php$ch = curl_init("https://silkdock.ai/v1/audio/transcriptions");curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ "Authorization: Bearer " . getenv("SILKDOCK_API_KEY"), ], CURLOPT_POSTFIELDS => [ "model" => "whisper-1", "language" => "en", "file" => new CURLFile("audio.mp3", "audio/mpeg", "audio.mp3"), ],]);$res = json_decode(curl_exec($ch), true);echo $res["text"];import Foundationlet boundary = UUID().uuidStringvar req = URLRequest(url: URL(string: "https://silkdock.ai/v1/audio/transcriptions")!)req.httpMethod = "POST"req.setValue("Bearer \(ProcessInfo.processInfo.environment["SILKDOCK_API_KEY"]!)", forHTTPHeaderField: "Authorization")req.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")var body = Data()func addField(_ name: String, _ value: String) { body.append("--\(boundary)\r\nContent-Disposition: form-data; name=\"\(name)\"\r\n\r\n\(value)\r\n".data(using: .utf8)!)}addField("model", "whisper-1")addField("language", "en")let audioData = try! Data(contentsOf: URL(fileURLWithPath: "audio.mp3"))body.append("--\(boundary)\r\nContent-Disposition: form-data; name=\"file\"; filename=\"audio.mp3\"\r\nContent-Type: audio/mpeg\r\n\r\n".data(using: .utf8)!)body.append(audioData)body.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!)req.httpBody = bodylet (data, _) = try! await URLSession.shared.data(for: req)print(String(data: data, encoding: .utf8)!)using System.Net.Http;var client = new HttpClient();client.DefaultRequestHeaders.Add("Authorization", $"Bearer {Environment.GetEnvironmentVariable("SILKDOCK_API_KEY")}");using var form = new MultipartFormDataContent();form.Add(new StringContent("whisper-1"), "model");form.Add(new StringContent("en"), "language");form.Add(new ByteArrayContent(await File.ReadAllBytesAsync("audio.mp3")), "file", "audio.mp3");var res = await client.PostAsync("https://silkdock.ai/v1/audio/transcriptions", form);Console.WriteLine(await res.Content.ReadAsStringAsync());require "net/http"uri = URI("https://silkdock.ai/v1/audio/transcriptions")req = Net::HTTP::Post.new(uri)req["Authorization"] = "Bearer #{ENV['SILKDOCK_API_KEY']}"form = Net::HTTP::Post::Multipart.new(uri.path,"model" => "whisper-1","language" => "en","file" => UploadIO.new("audio.mp3", "audio/mpeg"))form["Authorization"] = req["Authorization"]res = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |h| h.request(form) }puts JSON.parse(res.body)["text"]import java.net.http.*import java.net.URIimport java.nio.file.*import java.util.UUIDval boundary = UUID.randomUUID().toString()val fileBytes = Files.readAllBytes(Path.of("audio.mp3"))val body = buildString { append("--$boundary
") append("Content-Disposition: form-data; name="model"
whisper-1
") append("--$boundary
") append("Content-Disposition: form-data; name="language"
en
") append("--$boundary
") append("Content-Disposition: form-data; name="file"; filename="audio.mp3"
") append("Content-Type: audio/mpeg
")}.toByteArray() + fileBytes + "
--$boundary--
".toByteArray()val req = HttpRequest.newBuilder() .uri(URI.create("https://silkdock.ai/v1/audio/transcriptions")) .header("Authorization", "Bearer ${System.getenv("SILKDOCK_API_KEY")}") .header("Content-Type", "multipart/form-data; boundary=$boundary") .POST(HttpRequest.BodyPublishers.ofByteArray(body)) .build()println(HttpClient.newHttpClient().send(req, HttpResponse.BodyHandlers.ofString()).body())use reqwest::blocking::{Client, multipart};fn main() -> Result<(), Box<dyn std::error::Error>> { let form = multipart::Form::new() .text("model", "whisper-1") .text("language", "en") .file("file", "audio.mp3")?; let res = Client::new() .post("https://silkdock.ai/v1/audio/transcriptions") .header("Authorization", format!("Bearer {}", std::env::var("SILKDOCK_API_KEY")?)) .multipart(form) .send()?; println!("{}", res.text()?); Ok(())}POST /v1/audio/transcriptions HTTP/1.1Host: silkdock.aiAuthorization: Bearer <YOUR_API_KEY>Content-Type: multipart/form-data; boundary=----boundary------boundaryContent-Disposition: form-data; name="model"whisper-1------boundaryContent-Disposition: form-data; name="language"en------boundaryContent-Disposition: form-data; name="file"; filename="audio.mp3"Content-Type: audio/mpeg<binary audio data>------boundary--import 'dart:io';import 'package:http/http.dart' as http;void main() async {final req = http.MultipartRequest( 'POST', Uri.parse('https://silkdock.ai/v1/audio/transcriptions'),) ..headers['Authorization'] = 'Bearer ${const String.fromEnvironment("SILKDOCK_API_KEY")}' ..fields['model'] = 'whisper-1' ..fields['language'] = 'en' ..files.add(await http.MultipartFile.fromPath('file', 'audio.mp3'));final res = await req.send();print(await res.stream.bytesToString());}library(httr2)req <- request("https://silkdock.ai/v1/audio/transcriptions") |>req_headers(Authorization = paste("Bearer", Sys.getenv("SILKDOCK_API_KEY"))) |>req_body_multipart( model = "whisper-1", language = "en", file = curl::form_file("audio.mp3", type = "audio/mpeg"))resp <- req_perform(req)cat(resp_body_json(resp)$text)(* requires cohttp-lwt-unix and multipart_form *)(* Simple approach using curl via shell *)let () =let key = Sys.getenv "SILKDOCK_API_KEY" inlet cmd = Printf.sprintf {|curl -s -X POST https://silkdock.ai/v1/audio/transcriptions -H "Authorization: Bearer %s" -F "model=whisper-1" -F "language=en" -F "[email protected]"|} keyinprint_string (Unix.open_process_in cmd |> (fun ch -> let buf = Buffer.create 256 in (try while true do Buffer.add_channel buf ch 1 done with End_of_file -> ()); Buffer.contents buf))curl -X POST https://silkdock.ai/v1/moderations \-H "Authorization: Bearer $SILKDOCK_API_KEY" \-H "Content-Type: application/json" \-d '{ "model": "omni-moderation-latest", "input": "I want to hurt someone."}'const { OpenAI } = require("openai");const client = new OpenAI({apiKey: process.env.SILKDOCK_API_KEY,baseURL: "https://silkdock.ai/v1",});const response = await client.moderations.create({input: "I want to hurt someone.",model: "omni-moderation-latest",});console.log(`flagged: ${response.results[0].flagged}`);import OpenAI from "openai";const client = new OpenAI({apiKey: process.env.SILKDOCK_API_KEY,baseURL: "https://silkdock.ai/v1",});const response = await client.moderations.create({input: "I want to hurt someone.",model: "omni-moderation-latest",});console.log(`flagged: ${response.results[0].flagged}`);import requests, osres = requests.post( "https://silkdock.ai/v1/moderations", headers={"Authorization": f"Bearer {os.getenv('SILKDOCK_API_KEY')}"}, json={ "model": "omni-moderation-latest", "input": "I want to hurt someone.", },)result = res.json()["results"][0]print("Flagged:", result["flagged"])print("Categories:", result["categories"])#include <stdio.h>#include <curl/curl.h>int main(void) { CURL *curl = curl_easy_init(); if (!curl) return 1; const char *body = "{"model":"omni-moderation-latest"," ""input":"I want to hurt someone."}"; char auth_header[256]; snprintf(auth_header, sizeof(auth_header), "Authorization: Bearer %s", getenv("SILKDOCK_API_KEY")); struct curl_slist *headers = NULL; headers = curl_slist_append(headers, auth_header); headers = curl_slist_append(headers, "Content-Type: application/json"); curl_easy_setopt(curl, CURLOPT_URL, "https://silkdock.ai/v1/moderations"); curl_easy_setopt(curl, CURLOPT_POST, 1L); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body); curl_easy_perform(curl); curl_slist_free_all(headers); curl_easy_cleanup(curl); return 0;}#import <Foundation/Foundation.h>int main(int argc, const char *argv[]) { @autoreleasepool { NSURL *url = [NSURL URLWithString:@"https://silkdock.ai/v1/moderations"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; request.HTTPMethod = @"POST"; NSString *apiKey = [NSProcessInfo.processInfo.environment objectForKey:@"SILKDOCK_API_KEY"]; [request setValue:[NSString stringWithFormat:@"Bearer %@", apiKey] forHTTPHeaderField:@"Authorization"]; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; NSDictionary *bodyDict = @{ @"model": @"omni-moderation-latest", @"input": @"I want to hurt someone." }; request.HTTPBody = [NSJSONSerialization dataWithJSONObject:bodyDict options:0 error:nil]; dispatch_semaphore_t sem = dispatch_semaphore_create(0); [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *resp, NSError *err) { if (data) { NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@", result); } dispatch_semaphore_signal(sem); }] resume]; dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER); } return 0;}import java.net.http.*;import java.net.URI;var req = HttpRequest.newBuilder() .uri(URI.create("https://silkdock.ai/v1/moderations")) .header("Authorization", "Bearer " + System.getenv("SILKDOCK_API_KEY")) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString( """{"model":"omni-moderation-latest","input":"I want to hurt someone."}""")) .build();System.out.println(HttpClient.newHttpClient().send(req, HttpResponse.BodyHandlers.ofString()).body());package mainimport ( "bytes" "encoding/json" "fmt" "io" "net/http" "os")func main() { body, _ := json.Marshal(map[string]any{ "model": "omni-moderation-latest", "input": "I want to hurt someone.", }) req, _ := http.NewRequest("POST", "https://silkdock.ai/v1/moderations", bytes.NewReader(body)) req.Header.Set("Authorization", "Bearer "+os.Getenv("SILKDOCK_API_KEY")) req.Header.Set("Content-Type", "application/json") resp, _ := http.DefaultClient.Do(req) defer resp.Body.Close() data, _ := io.ReadAll(resp.Body) fmt.Println(string(data))}<?php$ch = curl_init("https://silkdock.ai/v1/moderations");curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ "Authorization: Bearer " . getenv("SILKDOCK_API_KEY"), "Content-Type: application/json", ], CURLOPT_POSTFIELDS => json_encode([ "model" => "omni-moderation-latest", "input" => "I want to hurt someone.", ]),]);$res = json_decode(curl_exec($ch), true);echo $res["results"][0]["flagged"] ? "Flagged" : "Clean";import Foundationvar req = URLRequest(url: URL(string: "https://silkdock.ai/v1/moderations")!)req.httpMethod = "POST"req.setValue("Bearer \(ProcessInfo.processInfo.environment["SILKDOCK_API_KEY"]!)", forHTTPHeaderField: "Authorization")req.setValue("application/json", forHTTPHeaderField: "Content-Type")req.httpBody = try! JSONSerialization.data(withJSONObject: [ "model": "omni-moderation-latest", "input": "I want to hurt someone.",])let (data, _) = try! await URLSession.shared.data(for: req)print(String(data: data, encoding: .utf8)!)using System.Net.Http;using System.Net.Http.Json;var client = new HttpClient();client.DefaultRequestHeaders.Add("Authorization", $"Bearer {Environment.GetEnvironmentVariable("SILKDOCK_API_KEY")}");var res = await client.PostAsJsonAsync("https://silkdock.ai/v1/moderations", new { model = "omni-moderation-latest", input = "I want to hurt someone.",});Console.WriteLine(await res.Content.ReadAsStringAsync());require "net/http"require "json"uri = URI("https://silkdock.ai/v1/moderations")req = Net::HTTP::Post.new(uri)req["Authorization"] = "Bearer #{ENV['SILKDOCK_API_KEY']}"req["Content-Type"] = "application/json"req.body = {model: "omni-moderation-latest",input: "I want to hurt someone."}.to_jsonres = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |h| h.request(req) }result = JSON.parse(res.body)["results"][0]puts "Flagged: #{result["flagged"]}"import java.net.http.*import java.net.URIval req = HttpRequest.newBuilder() .uri(URI.create("https://silkdock.ai/v1/moderations")) .header("Authorization", "Bearer ${System.getenv("SILKDOCK_API_KEY")}") .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString( """{"model":"omni-moderation-latest","input":"I want to hurt someone."}""")) .build()println(HttpClient.newHttpClient().send(req, HttpResponse.BodyHandlers.ofString()).body())use reqwest::blocking::Client;use serde_json::json;fn main() -> Result<(), Box<dyn std::error::Error>> { let res = Client::new() .post("https://silkdock.ai/v1/moderations") .header("Authorization", format!("Bearer {}", std::env::var("SILKDOCK_API_KEY")?)) .json(&json!({ "model": "omni-moderation-latest", "input": "I want to hurt someone." })) .send()?; println!("{}", res.text()?); Ok(())}POST /v1/moderations HTTP/1.1Host: silkdock.aiAuthorization: Bearer <YOUR_API_KEY>Content-Type: application/json{"model": "omni-moderation-latest","input": "I want to hurt someone."}import 'dart:convert';import 'package:http/http.dart' as http;void main() async {final res = await http.post( Uri.parse('https://silkdock.ai/v1/moderations'), headers: { 'Authorization': 'Bearer ${const String.fromEnvironment("SILKDOCK_API_KEY")}', 'Content-Type': 'application/json', }, body: jsonEncode({ 'model': 'omni-moderation-latest', 'input': 'I want to hurt someone.', }),);final data = jsonDecode(res.body);print('Flagged: ${data["results"][0]["flagged"]}');}library(httr2)req <- request("https://silkdock.ai/v1/moderations") |>req_headers( Authorization = paste("Bearer", Sys.getenv("SILKDOCK_API_KEY")), "Content-Type" = "application/json") |>req_body_json(list( model = "omni-moderation-latest", input = "I want to hurt someone."))resp <- req_perform(req)result <- resp_body_json(resp)$results[[1]]cat("Flagged:", result$flagged, "")(* requires cohttp-lwt-unix *)open Cohttp_lwt_unixopen Cohttpopen Lwtlet () =let body = {|{"model":"omni-moderation-latest","input":"I want to hurt someone."}|} inlet headers = Header.of_list [ "Authorization", "Bearer " ^ Sys.getenv "SILKDOCK_API_KEY"; "Content-Type", "application/json";] inLwt_main.run ( Client.post ~headers ~body:(Cohttp_lwt.Body.of_string body) (Uri.of_string "https://silkdock.ai/v1/moderations") >>= fun (_, body) -> Cohttp_lwt.Body.to_string body >>= fun s -> print_string s; return_unit)Errors
{
"error": {
"code": "invalid_action",
"message": "type must be one of: chat, embedding, image, tts, transcription, moderation, video, file"
}
}| Status | Code | Description |
|---|---|---|
400 | invalid_action | action is missing or unrecognised. |
400 | missing_field | A required field for the given action is absent. |
400 | invalid_request_error | Malformed request body. |
401 | authentication_error | Missing or invalid API key. |
429 | rate_limit_error | Too many requests. |
500 | server_error | Internal server error. |
503 | service_unavailable | Upstream provider unavailable. |
Last updated on