Dragon API

Dragon Script Routing

Put dragon_api.lsl in your object and every script in the same prim can use AI through link messages. It handles linking, the token, re-linking, server pushes and the owner menu for you.

Download dragon_api.lsl Download the chat example

  1. Put dragon_api.lsl in your object. It sends you a link: open it and sign in. The object says it's linked within a few seconds.
  2. Set its name, personality, knowledge and model on the agent's page of your dashboard.
  3. From any script in the same prim, send DRAGON_REQUEST and listen for DRAGON_REPLY and DRAGON_ERROR.

Downloads come set up for this server, each with its own password for storing the link token.

Constants

Link message numbers. Copy the ones you use into your script.

integer DRAGON_REQUEST   = 9100;   // you -> API: ask the AI
integer DRAGON_REPLY     = 9101;   // API -> you: the answer
integer DRAGON_ERROR     = 9102;   // API -> you: something went wrong
integer DRAGON_STATUS    = 9103;   // API -> you: ready / pairing / unpaired
integer DRAGON_RELINK    = 9104;   // you -> API: link again, same agent
integer DRAGON_NEW_AGENT = 9105;   // you -> API: become a new agent (copies)

Message index

ConstantKindSummary
DRAGON_REQUEST 9100sendAsk the AI something.
DRAGON_REPLY 9101eventThe answer to a request.
DRAGON_ERROR 9102eventA request failed, with a code.
DRAGON_STATUS 9103eventThe link status changed.
DRAGON_RELINK 9104sendLink the object again, keeping its agent.
DRAGON_NEW_AGENT 9105sendMake this object a new agent.

9110–9116 are for agent libraries (Custom Library); 9200 is what the Dragon Library sends to your scripts (hooks).

SendllMessageLinked( LINK_THIS, DRAGON_REQUEST, string request, key request_id );9100

Asks the AI something. Exactly one DRAGON_REPLY or DRAGON_ERROR comes back with the same request_id.

  • string request – a JSON object (build it with llList2Json(JSON_OBJECT, [...])). Required: prompt or messages. All fields below; for booleans use JSON_TRUE / JSON_FALSE.
  • key request_id – required. Any key you choose, usually llGenerateKey(). Returned on the reply so you can match it.
FieldTypeRequiredDescription
promptstringyes, or messagesThe message to answer.
messageslistyes, or promptA full conversation: [{"role":"user","content":"..."}]. Roles: system, user, assistant. At least one user message.
speakerkeyrecommendedThe avatar talking, from listen(). Gives each resident their own memory and lets it recognise the owner. See speakers.
speaker_namestringrecommendedTheir display name (up to 64 characters).
systemstringnoExtra instructions for this request, added to the agent's personality.
memorybooleanno (true)JSON_FALSE: don't read or save memory for this request.
modelstringnoA model for this request only, e.g. "openai/gpt-4o-mini". Default: the agent's model on the dashboard.
max_tokensintegernoLongest reply in tokens, 1–16000 (a token is about ¾ of a word).
max_charsintegernoCut the reply's text to this many characters.
temperaturefloatno0–2. Higher is more creative.
top_p, stop, seednoStandard sampling settings, passed to the model.
rawbooleannoJSON_TRUE: return the model provider's response untouched.

Caveats

  • Must be sent from a script in the same prim as dragon_api.lsl (LINK_THIS).
  • Before the object is linked, you get DRAGON_ERROR with NOT_PAIRED.
  • Replies go to every script in the object, so check request_id if more than one script makes requests.
  • Second Life limits how fast an object can make HTTP requests; past that you get THROTTLED.
  • Replies take about 1–5 seconds, longer for big answers or slow models.

Example

key gAsk;

ask(string question, key who, string name)
{
    gAsk = llGenerateKey();
    llMessageLinked(LINK_THIS, 9100, llList2Json(JSON_OBJECT, [
        "prompt", question,
        "speaker", (string)who,
        "speaker_name", name,
        "system", "Answer in one short sentence.",
        "max_chars", 1000
    ]), gAsk);
}

See also: DRAGON_REPLY · DRAGON_ERROR · Speakers and memory

Eventlink_message( integer sender, integer DRAGON_REPLY, string reply, key request_id ){ ; }9101

The AI's answer to a DRAGON_REQUEST.

  • string reply – a JSON object. Always has "ok": true and text; the other fields below.
  • key request_id – the key you sent with the request.
FieldTypeDescription
textstringThe answer. Empty when silent is true.
silentbooleanThe agent chose not to answer (for example, an overheard line that wasn't for it).
truncatedbooleanmax_chars cut the text.
faqbooleanThe answer came from your FAQ (instant and free).
modelstringThe model that actually answered.
usageobjectprompt_tokens, completion_tokens, cost_usd.
actionslistIn-world actions the AI chose. Only when a library has said it can act (Custom Library).
configobjectThe agent's settings: name, chat_mode, greet, moderate, tips.

Caveats

  • llSay takes at most 1,024 characters: set max_chars in the request if you speak the reply.
  • Replies up to 16 KB are delivered; very long answers are cut by the HTTP limit.

Example

link_message(integer sender, integer num, string str, key id)
{
    if (num != 9101 || id != gAsk) return;
    if (llJsonGetValue(str, ["silent"]) == JSON_TRUE) return;
    llSay(0, llJsonGetValue(str, ["text"]));
}

See also: DRAGON_REQUEST · DRAGON_ERROR

Eventlink_message( integer sender, integer DRAGON_ERROR, string error, key request_id ){ ; }9102

A DRAGON_REQUEST failed.

  • string error – a JSON object: {"code": "CODE", "error": "a readable message"}. Check code; the message may change.
  • key request_id – the key you sent with the request.
CodeMeaningWhat to do
In the prim
NOT_PAIREDThe object isn't linked yet.Open the link it sent you, or /88 settings → Re-link.
THROTTLEDSecond Life refused another HTTP request.Slow down; retry in a few seconds.
HTTP_<n>The request failed with no readable answer (HTTP_499 is a timeout).Retry once.
Your request
BAD_REQUESTA field is missing or the wrong type; the message says which.Send prompt or messages.
BAD_SPEAKERspeaker isn't an avatar key.Use the id from listen().
MODEL_NOT_ALLOWED, MODEL_NOT_FOUNDThat model isn't available.Pick one from your dashboard's list.
The link
INVALID_TOKEN, TOKEN_EXPIRED, DEVICE_REVOKEDThe object's link is no longer valid (revoked, or it changed owner).Nothing: it re-links by itself and sends the owner a link.
Spending
UPSTREAM_FORBIDDENUsually: this agent reached its spend cap.Raise the cap on its Model & spending tab.
INSUFFICIENT_CREDITSThe service is out of AI credit.Tell us; it's on our side.
The AI provider (temporary)
RATE_LIMITEDToo many requests to this model right now.Retry, or use another model.
UPSTREAM_TIMEOUTThe model took too long.Retry, or ask for less.
NO_PROVIDER_AVAILABLE, UPSTREAM_ERROR, UPSTREAM_UNREACHABLEThe model's provider is down or failed.Retry, or use another model.
UPSTREAM_BAD_REQUESTThe provider rejected it (often a too-long conversation).Send fewer messages.

Caveats

  • When the link breaks, every request still waiting fails with the same code, then the object re-links itself.

Example

link_message(integer sender, integer num, string str, key id)
{
    if (num != 9102) return;
    string code = llJsonGetValue(str, ["code"]);
    if (code == "NOT_PAIRED") llOwnerSay("Link me first: check your IMs.");
    else if (code == "UPSTREAM_FORBIDDEN") llOwnerSay("I've hit my spend cap.");
    else llOwnerSay("AI error " + code + ": " + llJsonGetValue(str, ["error"]));
}

See also: DRAGON_REQUEST · DRAGON_STATUS

Eventlink_message( integer sender, integer DRAGON_STATUS, string status, key id ){ ; }9103

The object's link status changed.

  • string status – plain text: ready (linked, requests work), pairing (waiting for the owner to open the link) or unpaired.
  • key id – NULL_KEY.

Caveats

  • Sent only when the status changes. A script added later won't hear the current status: just send requests and handle NOT_PAIRED.

Example

link_message(integer sender, integer num, string str, key id)
{
    if (num == 9103) llSetText("AI: " + str, <1, 1, 1>, 1.0);
}

See also: DRAGON_RELINK · DRAGON_ERROR

SendllMessageLinked( LINK_THIS, DRAGON_RELINK, "", NULL_KEY );9104

Links the object again, keeping the same agent: its name, personality and memory stay. The owner gets a new link to open.

  • string str – ignored.
  • key id – ignored.

The owner can also do this from the menu: /88 settings → Re-link. See also: DRAGON_STATUS · DRAGON_NEW_AGENT

SendllMessageLinked( LINK_THIS, DRAGON_NEW_AGENT, "", NULL_KEY );9105

Makes this object a new agent on the owner's account, instantly and with no browser. Use it in copies.

  • string str – ignored.
  • key id – ignored.

Caveats

  • Copies of a linked object share its identity until they do this. Link one object, then make more agents by copying it.
  • Giving or selling an object wipes its link; the new owner links it to their own account.
  • An agent with no contact for 7 days is paused and resumes when it's back; after 30 days it needs linking again.

The owner can also do this from the menu: /88 settings → New device. See also: DRAGON_RELINK

Complete example

A whole script: it answers the owner when they say ai <question> in local chat.

integer DRAGON_REQUEST = 9100;
integer DRAGON_REPLY   = 9101;
integer DRAGON_ERROR   = 9102;

default
{
    state_entry()
    {
        llListen(0, "", llGetOwner(), "");
    }

    listen(integer channel, string name, key id, string msg)
    {
        if (llToLower(llGetSubString(msg, 0, 2)) != "ai ") return;
        string request = llList2Json(JSON_OBJECT, [
            "prompt", llGetSubString(msg, 3, -1),
            "speaker", (string)id,          // who is talking: gives them their own memory
            "speaker_name", name,
            "max_tokens", 200
        ]);
        llMessageLinked(LINK_THIS, DRAGON_REQUEST, request, llGenerateKey());
    }

    link_message(integer sender, integer num, string str, key id)
    {
        if (num == DRAGON_REPLY) llSay(0, llJsonGetValue(str, ["text"]));
        else if (num == DRAGON_ERROR)
            llOwnerSay("AI error " + llJsonGetValue(str, ["code"]) + ": " + llJsonGetValue(str, ["error"]));
    }
}