Skip to content
繁體中文
Generate Image

Tool Calling ​

Generate images from a chat tool and display completed results.

API Calls in Multiple Languages ​

See language setup. Set API_KEY and replace model, file URL, and ID placeholders first. Each version displays the raw response to the same request.

These examples display the raw API response. Continue with this page or the image overview for Base64 decoding, download, and storage. This is the generation API call inside the tool handler, not the chat endpoint. See the complete example below for handling chat call IDs.

bash
curl --fail-with-body --silent --show-error --max-time 180 \
  --request POST \
  --url "https://api.tokatlas.ai/v1/images/generations" \
  --header "Authorization: Bearer $API_KEY" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "YOUR_ENABLED_IMAGE_MODEL_ID",
  "prompt": "A white ceramic cup on a pale gray background, studio lighting",
  "n": 1
}'
python
import os
import requests

headers = {
    'Authorization': 'Bearer ' + os.environ["API_KEY"],
    'Content-Type': 'application/json',
}
payload = {'model': 'YOUR_ENABLED_IMAGE_MODEL_ID',
 'prompt': 'A white ceramic cup on a pale gray background, studio lighting',
 'n': 1}
response = requests.request(
    'POST', 'https://api.tokatlas.ai/v1/images/generations', headers=headers,
    json=payload,
    timeout=180,
)
response.raise_for_status()
print(response.text)
js
if (!process.env.API_KEY) throw new Error("Set API_KEY first.");
const response = await fetch("https://api.tokatlas.ai/v1/images/generations", {
  method: "POST",
  headers: {
    "Authorization": "Bearer " + process.env.API_KEY,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
  "model": "YOUR_ENABLED_IMAGE_MODEL_ID",
  "prompt": "A white ceramic cup on a pale gray background, studio lighting",
  "n": 1
}),
  signal: AbortSignal.timeout(180_000),
});
if (!response.ok) {
  throw new Error(`HTTP ${response.status}: ${await response.text()}`);
}
console.log(await response.text());
java
import java.net.URI;
import java.net.http.*;
import java.time.Duration;

public class Example {
    public static void main(String[] args) throws Exception {
        String apiKey = System.getenv("API_KEY");
        if (apiKey == null || apiKey.isBlank()) {
            throw new IllegalArgumentException("Set API_KEY first.");
        }
        String payload = String.join("\n",
            "{",
            "  \"model\": \"YOUR_ENABLED_IMAGE_MODEL_ID\",",
            "  \"prompt\": \"A white ceramic cup on a pale gray background, studio lighting\",",
            "  \"n\": 1",
            "}"
        );
        HttpClient client = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(30)).build();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.tokatlas.ai/v1/images/generations"))
            .timeout(Duration.ofSeconds(180))
            .header("Authorization", "Bearer " + apiKey)
            .header("Content-Type", "application/json")
            .method("POST", HttpRequest.BodyPublishers.ofString(payload))
            .build();
        HttpResponse<String> response = client.send(
            request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() < 200 || response.statusCode() >= 300) {
            throw new IllegalStateException("HTTP " + response.statusCode() + ": "
                + response.body());
        }
        System.out.println(response.body());
    }
}

Integration Steps ​

  1. Run Generate Image Overview first and keep the same API_KEY and IMAGE_MODEL_ID.
  2. In the complete Python example from Chat Tool Calling, replace the contents of TOOLS with this definition, keeping its outer list.
  3. Replace execute with the handler below and include GENERATED_IMAGES. The 1,000-character limit is an application choice, not a universal model limit.
  4. Replace “Check stock for DEMO-001.” in the Chat example with an image-generation request. The tool returns completed and a count. Save GENERATED_IMAGES using the overview's download logic and display the images in your UI.
json
{"type":"function","function":{"name":"generate_image","description":"Generate an image and return its completion status.","parameters":{"type":"object","properties":{"prompt":{"type":"string","maxLength":1000}},"required":["prompt"],"additionalProperties":false}}}
python
import os
import requests

GENERATED_IMAGES = []


def execute(name, args):
    if name != "generate_image" or not isinstance(args, dict):
        return {"error": "Invalid tool call"}
    prompt = args.get("prompt")
    if set(args) != {"prompt"} or not isinstance(prompt, str):
        return {"error": "Expected a prompt string"}
    if not prompt.strip() or len(prompt) > 1000:
        return {"error": "prompt must contain 1 to 1000 characters"}
    try:
        response = requests.post(
            "https://api.tokatlas.ai/v1/images/generations",
            headers={"Authorization": f"Bearer {os.environ['API_KEY']}"},
            json={"model": os.environ["IMAGE_MODEL_ID"], "prompt": prompt, "n": 1},
            timeout=120,
        )
    except requests.RequestException:
        return {"error": "Submission outcome unknown; reconcile before retrying"}
    if not response.ok:
        return {"error": "Submission failed; check before retrying",
                "http_status": response.status_code}
    body = response.json()
    if not isinstance(body.get("data"), list) or not body["data"]:
        return {"error": "Unexpected submission response; reconcile before retrying"}
    images = body["data"]
    if not all(item.get("url") or item.get("b64_json") for item in images):
        return {"error": "Expected completed images; check the configured image route"}
    # Store the actual images outside the model context; render them in your UI.
    GENERATED_IMAGES.extend(images)
    return {"status": "completed", "image_count": len(images)}

Do not send Base64 image bytes back as tool-result text. In production, replace the in-memory demo list with storage scoped to each request. On timeouts, reconcile request records before generating again for the same tool call.