# SDKs and language examples

## Choose a language

Set `SITE6_API_KEY` in your environment and put an `AGENTS.md` file beside your script. The examples post the file contents as `agents_md` and include a short `system_prompt`. Choose a text model listed for your key.

## Python

The Python standard library is enough.

~~~python
import json
import os
from pathlib import Path
from urllib.request import Request, urlopen

payload = {
    "model": "deepseek-v4.1-flash-1017",
    "messages": [{"role": "user", "content": "Suggest one test for our string parser."}],
    "system_prompt": "Keep the reply concise.",
    "agents_md": Path("AGENTS.md").read_text(encoding="utf-8"),
    "max_tokens": 256,
}
request = Request(
    "https://site6.eokgg.win/v1/chat/completions",
    data=json.dumps(payload, ensure_ascii=False).encode("utf-8"),
    headers={
        "Authorization": "Bearer " + os.environ["SITE6_API_KEY"],
        "Content-Type": "application/json",
    },
    method="POST",
)
with urlopen(request) as response:
    print(json.load(response)["choices"][0]["message"]["content"])
~~~

## JavaScript / TypeScript

Use Node.js with built-in fetch. Save as an ES module, or use the same code in a TypeScript project that supports top-level await.

~~~javascript
import { readFile } from "node:fs/promises";

const key = process.env.SITE6_API_KEY;
if (!key) throw new Error("Set SITE6_API_KEY");

const response = await fetch("https://site6.eokgg.win/v1/chat/completions", {
  method: "POST",
  headers: { Authorization: "Bearer " + key, "Content-Type": "application/json" },
  body: JSON.stringify({
    model: "deepseek-v4.1-flash-1017",
    messages: [{ role: "user", content: "Suggest one test for our string parser." }],
    system_prompt: "Keep the reply concise.",
    agents_md: await readFile("AGENTS.md", "utf8"),
    max_tokens: 256,
  }),
});
if (!response.ok) throw new Error(await response.text());
const result = await response.json();
console.log(result.choices[0].message.content);
~~~

## Bash / cURL

Use curl and jq. The rawfile option loads the complete file as a string.

~~~bash
jq -n --rawfile rules AGENTS.md '{
  model: "deepseek-v4.1-flash-1017",
  messages: [{role: "user", content: "Suggest one test for our string parser."}],
  system_prompt: "Keep the reply concise.",
  agents_md: $rules,
  max_tokens: 256
}' | curl --fail-with-body -sS https://site6.eokgg.win/v1/chat/completions \
  -H "Authorization: Bearer $SITE6_API_KEY" \
  -H 'Content-Type: application/json' \
  --data-binary @-
~~~

## PowerShell

Use Invoke-RestMethod to send UTF-8 JSON.

~~~powershell
$request = @{
    model = 'deepseek-v4.1-flash-1017'
    messages = @(@{role = 'user'; content = 'Suggest one test for our string parser.'})
    system_prompt = 'Keep the reply concise.'
    agents_md = Get-Content -LiteralPath './AGENTS.md' -Raw -Encoding UTF8
    max_tokens = 256
} | ConvertTo-Json -Depth 6

$answer = Invoke-RestMethod -Method Post -Uri 'https://site6.eokgg.win/v1/chat/completions' -Headers @{
    Authorization = "Bearer $env:SITE6_API_KEY"
} -ContentType 'application/json; charset=utf-8' -Body ([Text.Encoding]::UTF8.GetBytes($request))
$answer.choices[0].message.content
~~~

## Go

Save as main.go and run go run main.go.

~~~go
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "log"
    "net/http"
    "os"
    "time"
)

func main() {
    key := os.Getenv("SITE6_API_KEY")
    if key == "" {
        log.Fatal("Set SITE6_API_KEY")
    }
    rules, err := os.ReadFile("AGENTS.md")
    if err != nil {
        log.Fatal(err)
    }
    payload, err := json.Marshal(map[string]any{
        "model": "deepseek-v4.1-flash-1017",
        "messages": []map[string]string{{"role": "user", "content": "Suggest one test for our string parser."}},
        "system_prompt": "Keep the reply concise.",
        "agents_md": string(rules),
        "max_tokens": 256,
    })
    if err != nil {
        log.Fatal(err)
    }
    req, err := http.NewRequest("POST", "https://site6.eokgg.win/v1/chat/completions", bytes.NewReader(payload))
    if err != nil {
        log.Fatal(err)
    }
    req.Header.Set("Authorization", "Bearer "+key)
    req.Header.Set("Content-Type", "application/json")
    client := &http.Client{Timeout: 3 * time.Minute}
    res, err := client.Do(req)
    if err != nil {
        log.Fatal(err)
    }
    defer res.Body.Close()
    data, err := io.ReadAll(res.Body)
    if err != nil {
        log.Fatal(err)
    }
    if res.StatusCode != http.StatusOK {
        log.Fatalf("HTTP %d: %s", res.StatusCode, data)
    }
    fmt.Println(string(data))
}
~~~

## Rust

Add reqwest with the blocking and json features, and add serde_json to your Cargo project.

~~~rust
use reqwest::blocking::Client;
use serde_json::{json, Value};
use std::{env, error::Error, fs};

fn main() -> Result<(), Box<dyn Error>> {
    let key = env::var("SITE6_API_KEY")?;
    let rules = fs::read_to_string("AGENTS.md")?;
    let body = json!({
        "model": "deepseek-v4.1-flash-1017",
        "messages": [{"role": "user", "content": "Suggest one test for our string parser."}],
        "system_prompt": "Keep the reply concise.",
        "agents_md": rules,
        "max_tokens": 256
    });

    let reply: Value = Client::new()
        .post("https://site6.eokgg.win/v1/chat/completions")
        .bearer_auth(key)
        .json(&body)
        .send()?
        .error_for_status()?
        .json()?;
    if let Some(text) = reply["choices"][0]["message"]["content"].as_str() {
        println!("{}", text);
    }
    Ok(())
}
~~~

## C#

Use a modern .NET console project with System.Net.Http.Json.

~~~csharp
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;

var key = Environment.GetEnvironmentVariable("SITE6_API_KEY")
    ?? throw new InvalidOperationException("Set SITE6_API_KEY");

using var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", key);
using var response = await client.PostAsJsonAsync("https://site6.eokgg.win/v1/chat/completions", new
{
    model = "deepseek-v4.1-flash-1017",
    messages = new[] { new { role = "user", content = "Suggest one test for our string parser." } },
    system_prompt = "Keep the reply concise.",
    agents_md = await File.ReadAllTextAsync("AGENTS.md"),
    max_tokens = 256
});

var body = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
    throw new HttpRequestException(body);
using var result = JsonDocument.Parse(body);
Console.WriteLine(result.RootElement.GetProperty("choices")[0]
    .GetProperty("message").GetProperty("content").GetString());
~~~

## Java

Use Java 17 or later and add Jackson Databind to your project.

~~~java
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class Site6Example {
    public static void main(String[] args) throws Exception {
        String key = Objects.requireNonNull(System.getenv("SITE6_API_KEY"), "Set SITE6_API_KEY");
        var json = new ObjectMapper();
        var payload = Map.of(
            "model", "deepseek-v4.1-flash-1017",
            "messages", List.of(Map.of("role", "user", "content", "Suggest one test for our string parser.")),
            "system_prompt", "Keep the reply concise.",
            "agents_md", Files.readString(Path.of("AGENTS.md")),
            "max_tokens", 256
        );
        var request = HttpRequest.newBuilder(URI.create("https://site6.eokgg.win/v1/chat/completions"))
            .header("Authorization", "Bearer " + key)
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(json.writeValueAsString(payload)))
            .build();
        var response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() != 200) throw new IllegalStateException(response.body());
        System.out.println(json.readTree(response.body()).path("choices")
            .path(0).path("message").path("content").asText());
    }
}
~~~

## R

Install the httr2 package.

~~~r
library(httr2)

key <- Sys.getenv("SITE6_API_KEY")
stopifnot(nzchar(key))
rules <- rawToChar(readBin("AGENTS.md", "raw", n = file.size("AGENTS.md")))
Encoding(rules) <- "UTF-8"

result <- request("https://site6.eokgg.win/v1/chat/completions") |>
  req_auth_bearer_token(key) |>
  req_body_json(list(
    model = "deepseek-v4.1-flash-1017",
    messages = list(list(role = "user", content = "Suggest one test for our string parser.")),
    system_prompt = "Keep the reply concise.",
    agents_md = rules,
    max_tokens = 256
  )) |>
  req_perform() |>
  resp_body_json()

cat(result$choices[[1]]$message$content, "\n")
~~~

## Julia

Install HTTP and JSON3 in your Julia environment.

~~~julia
using HTTP, JSON3

body = JSON3.write(Dict(
    "model" => "deepseek-v4.1-flash-1017",
    "messages" => [Dict("role" => "user", "content" => "Suggest one test for our string parser.")],
    "system_prompt" => "Keep the reply concise.",
    "agents_md" => read("AGENTS.md", String),
    "max_tokens" => 256
))
headers = ["Authorization" => "Bearer " * ENV["SITE6_API_KEY"],
           "Content-Type" => "application/json"]
response = HTTP.post("https://site6.eokgg.win/v1/chat/completions", headers, body)
result = JSON3.read(String(response.body))
println(result.choices[1].message.content)
~~~

## C++

Link libcurl and include the nlohmann/json headers in a C++17 project.

~~~cpp
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <iterator>
#include <memory>
#include <stdexcept>
#include <string>
#include <curl/curl.h>
#include <nlohmann/json.hpp>

size_t receive(char* data, size_t size, size_t count, void* target) {
    auto& output = *static_cast<std::string*>(target);
    output.append(data, size * count);
    return size * count;
}

int main() {
    const char* key = std::getenv("SITE6_API_KEY");
    if (!key) throw std::runtime_error("Set SITE6_API_KEY");
    std::ifstream file("AGENTS.md", std::ios::binary);
    if (!file) throw std::runtime_error("Open AGENTS.md");
    std::string rules((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
    const std::string body = nlohmann::json{
        {"model", "deepseek-v4.1-flash-1017"},
        {"messages", nlohmann::json::array({{{"role", "user"}, {"content", "Suggest one test for our string parser."}}})},
        {"system_prompt", "Keep the reply concise."},
        {"agents_md", rules},
        {"max_tokens", 256}
    }.dump();

    std::unique_ptr<CURL, decltype(&curl_easy_cleanup)> curl(curl_easy_init(), curl_easy_cleanup);
    if (!curl) throw std::runtime_error("libcurl failed to initialise");
    auto* list = curl_slist_append(nullptr, ("Authorization: Bearer " + std::string(key)).c_str());
    list = curl_slist_append(list, "Content-Type: application/json");
    std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)> headers(list, curl_slist_free_all);
    std::string reply;
    curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, headers.get());
    curl_easy_setopt(curl.get(), CURLOPT_URL, "https://site6.eokgg.win/v1/chat/completions");
    curl_easy_setopt(curl.get(), CURLOPT_POSTFIELDS, body.c_str());
    curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, receive);
    curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &reply);
    const auto result = curl_easy_perform(curl.get());
    if (result != CURLE_OK) throw std::runtime_error(curl_easy_strerror(result));
    long status = 0;
    curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &status);
    if (status != 200) throw std::runtime_error(reply);
    std::cout << nlohmann::json::parse(reply)["choices"][0]["message"]["content"].get<std::string>() << '\n';
}
~~~

## OpenAI-compatible clients

Use `https://site6.eokgg.win/v1` as the base URL and pass your Site6 API key. Choose the wire format your client supports.

| Method and path | Interface |
|---|---|
| `POST /v1/chat/completions` | Chat Completions |
| `POST /v1/chat` | Chat alias |
| `POST /v1/responses` | Responses |
| `POST /v1/completions` | Legacy text completions with `prompt` |
| `GET /v1/models` | Models accessible to your key |
| `GET /v1/models/{id}` | Model metadata |
| `GET /v1/tools` | Built-in tool definitions |
| `POST /v1/tools/execute` | Execute one built-in tool |
| `GET /v1/usage` | Account usage |
| `POST /v1/images/generations` | Generate an image |
| `POST /v1/images/edits` | Upload images for editing |

The primary `/v1` generation routes also accept the shorter forms without `/v1`. The `/api/v1` prefix is accepted for compatible clients.

## Set up an SDK

Set `SITE6_API_KEY` and use a [model available to your key](/models/#discover-your-models). Set `SITE6_MODEL` to use a different model in these examples.

### JavaScript with the OpenAI SDK

Install the `openai` package with `npm install openai`. Save the example as an `.mjs` file and run it with Node.js.

~~~javascript
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://site6.eokgg.win/v1",
  apiKey: process.env.SITE6_API_KEY,
});
const response = await client.responses.create({
  model: process.env.SITE6_MODEL ?? "deepseek-v4.1-flash-1017",
  input: "Explain what an HTTP 429 means.",
  max_output_tokens: 256,
  store: false,
});
console.log(response.output_text);
~~~

### Python with the OpenAI SDK

Install the `openai` package with `python -m pip install openai`. For SDK methods with typed request fields, Python's `extra_body` can carry [Site6-specific fields](/instructions/) such as `agents_md`.

~~~python
import os
from pathlib import Path
from openai import OpenAI

client = OpenAI(
    base_url="https://site6.eokgg.win/v1",
    api_key=os.environ["SITE6_API_KEY"],
)
response = client.chat.completions.create(
    model=os.getenv("SITE6_MODEL", "deepseek-v4.1-flash-1017"),
    messages=[{"role": "user", "content": "Suggest one test for our string parser."}],
    max_tokens=256,
    extra_body={
        "system_prompt": "Answer in two sentences.",
        "agents_md": Path("AGENTS.md").read_text(encoding="utf-8"),
    },
)
print(response.choices[0].message.content)
~~~

Use [streaming and reasoning](/streaming/#build-a-streaming-client) for an SDK example that handles completion, partial output and cancellation.

## Anthropic Messages

Use `https://site6.eokgg.win` as the base URL when your client appends `/v1/messages`.

~~~bash
curl --fail-with-body -sS https://site6.eokgg.win/v1/messages \
  -H "x-api-key: $SITE6_API_KEY" \
  -H 'anthropic-version: 2023-06-01' \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "deepseek-v4.1-flash-1017",
    "max_tokens": 256,
    "system": "Use plain language.",
    "messages": [{"role":"user","content":"Explain exponential backoff."}]
  }'
~~~

Read text blocks from `content[]`. `tool_use` and `tool_result` blocks carry calls and results. For supported effort levels use `output_config.effort`.

## Ollama-compatible clients

Use the same origin, with `Authorization: Bearer <key>`. Read `message.content` from `/api/chat` or `response` from `/api/generate`.

~~~bash
curl --fail-with-body -sS https://site6.eokgg.win/api/chat \
  -H "Authorization: Bearer $SITE6_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "deepseek-v4.1-flash-1017",
    "messages": [{"role":"user","content":"Explain a race condition."}],
    "stream": false,
    "options": {"num_predict": 256}
  }'
~~~

`GET /api/tags` lists the available text models. `POST /api/show` accepts a model ID in `model`. `GET /api/version` reports the adapter version.

## Codex

Set `SITE6_API_KEY` in the environment and use a key with access to `eok/stupid-ai`. The model keeps its intentionally silly behaviour in Codex.

~~~toml
model = "eok/stupid-ai"
model_provider = "site6"

[model_providers.site6]
name = "Site6"
base_url = "https://site6.eokgg.win/v1"
model_catalog_url = "https://site6.eokgg.win/v1/models"
env_key = "SITE6_API_KEY"
wire_api = "responses"
~~~

`POST /v1/responses/compact` can compact prior turns for this model. Send its returned `output` back as `input` with the same key.

## Compatibility scope

Site6 exposes text and image generation with the adapters above. Audio, video, embeddings, Realtime, managed Files uploads, Batches, Assistants, model downloads, background Responses and logprobs are outside these interfaces. The API returns structured errors for unsupported operations.
