Groq: Una Soluzione Economica per Applicazioni AI
Continuano le mie peregrinazioni nel mondo dell’intelligenza artificiale. Oggi vorrei parlarvi di Groq, un servizio che, nonostante la somiglianza del nome con Grok di Elon Musk, in realtà non ha alcuna connessione con esso.
Groq è una piattaforma che consente di utilizzare modelli economicissimi come Llama 8B Instant, che risultano rapidissimi nel rispondere alle domande degli utenti. Questa soluzione è particolarmente adatta per implementazioni in simulazioni, cacce al tesoro o applicazioni con numerosi NPC.
Vantaggi economici
Il costo è veramente competitivo:
- Groq: 0.05/0.08$ per milione di token
- OpenAI: 0.15/0.60$ per milione di token
- DeepSeek: 0.27/1.10$ per milione di token leggermente piu’ cara di openai gpt 4o mini, ma decisamente piu’ intelligente, in cambio e’ lenta….
Per raggiungere la spesa di 1$, occorrerebbero circa 200 conversazioni lunghe con Groq. Per applicazioni dove non è richiesta una straordinaria intelligenza o un supporto multilingue avanzato, parliamo di un risparmio fino a 13 volte rispetto alle alternative – ideale per giochi o cacce al tesoro dove non si ha intenzione di investire budget elevati.
Prestazioni
Lo script che alleghiamo funziona perfettamente con Groq, offrendo performance velocissime se paragonate a:
- DeepSeek: 3-4 secondi di elaborazione
- OpenAI: 1 secondo di elaborazione
Ecco lo script valido per Groq,
come al solito dovete andare su grok per ottenere Api Key, si noti che e’ praticamente uguale a deep seek o open ai, variando al solito qualcosuccia nell’ottimizzazione del parsing.

// LSL Script for Groq Chat Integration with Memory
// Reads API key and system prompt from notecards
// Configuration
string API_KEY = "";
string SYSTEM_PROMPT = "";
string API_URL = "https://api.groq.com/openai/v1/chat/completions";
string MODEL = "llama-3.1-8b-instant";
//string MODEL = "llama3-8b-8192";
integer MAX_MEMORY = 10;
integer LISTEN_CHANNEL = 0;
// Notecard configuration
string API_KEY_NOTECARD = "api_key";
string SYSTEM_PROMPT_NOTECARD = "system_prompt";
// Variables
list message_memory = [];
key http_request_id;
integer listen_handle;
key api_key_query_id;
key system_prompt_query_id;
integer initialization_complete = FALSE;
// Function to add a message to memory
add_to_memory(string role, string content)
{
string message = llList2Json(JSON_OBJECT, ["role", role, "content", content]);
message_memory += [message];
while (llGetListLength(message_memory) > MAX_MEMORY)
{
message_memory = llDeleteSubList(message_memory, 0, 0);
}
}
// Function to construct API payload
string construct_payload()
{
list temp_messages = [];
if (SYSTEM_PROMPT != "")
{
temp_messages += [llList2Json(JSON_OBJECT, ["role", "system", "content", SYSTEM_PROMPT])];
}
temp_messages += message_memory;
string messages = llList2Json(JSON_ARRAY, temp_messages);
string payload = llList2Json(JSON_OBJECT, [
"model", MODEL,
"messages", llJsonGetValue(messages, []),
"temperature", 1.0,
"max_tokens", 1024,
"top_p", 1.0,
"stream", "false"
]);
return payload;
}
// Function to display memory contents
display_memory()
{
integer i;
integer len = llGetListLength(message_memory);
llOwnerSay("--- CHAT MEMORY ---");
if (SYSTEM_PROMPT != "")
{
llOwnerSay("System: " + SYSTEM_PROMPT);
}
if (len == 0)
{
llOwnerSay("Memory is empty.");
}
else
{
for (i = 0; i < len; i++)
{
string msg_json = llList2String(message_memory, i);
string role = llJsonGetValue(msg_json, ["role"]);
string content = llJsonGetValue(msg_json, ["content"]);
llOwnerSay((string)(i + 1) + ": [" + role + "] " + content);
}
}
llOwnerSay("------------------");
}
// Send to Groq API
send_to_groq()
{
if (!initialization_complete)
{
llSay(0, "Still initializing. Please wait...");
return;
}
if (API_KEY == "")
{
llSay(0, "Error: API key not found. Please add an 'api_key' notecard.");
return;
}
// Check if API key is too long for LSL headers (limit is around 253 chars)
if (llStringLength("Bearer " + API_KEY) > 250)
{
llSay(0, "Error: API key is too long for LSL HTTP headers. Please use a shorter API key.");
return;
}
string payload = construct_payload();
//llOwnerSay("Debug - Payload: " + payload); // Debug line
list headers = [
HTTP_METHOD, "POST",
HTTP_MIMETYPE, "application/json",
HTTP_CUSTOM_HEADER, "Authorization", "Bearer " + API_KEY,
HTTP_BODY_MAXLENGTH, 16384
];
http_request_id = llHTTPRequest(API_URL, headers, payload);
llSay(0, "Thinking...");
}
// Initialize function
initialize()
{
llOwnerSay("Initializing...");
initialization_complete = FALSE;
if (llGetInventoryType(API_KEY_NOTECARD) == INVENTORY_NOTECARD)
{
api_key_query_id = llGetNotecardLine(API_KEY_NOTECARD, 0);
llOwnerSay("Reading API key from notecard...");
}
else
{
llOwnerSay("Warning: '" + API_KEY_NOTECARD + "' notecard not found!");
if (llGetInventoryType(SYSTEM_PROMPT_NOTECARD) == INVENTORY_NOTECARD)
{
system_prompt_query_id = llGetNotecardLine(SYSTEM_PROMPT_NOTECARD, 0);
llOwnerSay("Reading system prompt from notecard...");
}
else
{
llOwnerSay("Warning: '" + SYSTEM_PROMPT_NOTECARD + "' notecard not found!");
initialization_complete = TRUE;
llOwnerSay("Initialization complete.");
listen_handle = llListen(LISTEN_CHANNEL, "", NULL_KEY, "");
llOwnerSay("Say something in chat to start a conversation.");
llOwnerSay("Say '/reset' to clear memory.");
llOwnerSay("Touch to see current memory.");
}
}
}
// Clean text function
string clean_text(string text)
{
integer i;
string clean_content = "";
integer len = llStringLength(text);
for (i = 0; i < len; i++)
{
string char = llGetSubString(text, i, i);
integer charCode = (integer)char;
if (charCode >= 32 && charCode <= 126)
{
clean_content += char;
}
else if (charCode == 10 || charCode == 13)
{
clean_content += " ";
}
}
return clean_content;
}
default
{
state_entry()
{
initialize();
}
dataserver(key query_id, string data)
{
if (query_id == api_key_query_id)
{
if (data != EOF)
{
API_KEY = llStringTrim(data, STRING_TRIM);
llOwnerSay("API key loaded successfully.");
}
else if (data == EOF && API_KEY == "")
{
llOwnerSay("Error: API key notecard is empty!");
}
if (llGetInventoryType(SYSTEM_PROMPT_NOTECARD) == INVENTORY_NOTECARD)
{
system_prompt_query_id = llGetNotecardLine(SYSTEM_PROMPT_NOTECARD, 0);
llOwnerSay("Reading system prompt from notecard...");
}
else
{
llOwnerSay("Warning: '" + SYSTEM_PROMPT_NOTECARD + "' notecard not found!");
initialization_complete = TRUE;
llOwnerSay("Initialization complete.");
listen_handle = llListen(LISTEN_CHANNEL, "", NULL_KEY, "");
llOwnerSay("Say something in chat to start a conversation.");
llOwnerSay("Say '/reset' to clear memory.");
llOwnerSay("Touch to see current memory.");
}
}
else if (query_id == system_prompt_query_id)
{
if (data != EOF)
{
if (SYSTEM_PROMPT == "")
{
SYSTEM_PROMPT = data;
}
else
{
SYSTEM_PROMPT += "\n" + data;
}
integer next_line = llGetListLength(llParseString2List(SYSTEM_PROMPT, ["\n"], []));
system_prompt_query_id = llGetNotecardLine(SYSTEM_PROMPT_NOTECARD, next_line);
}
else
{
if (SYSTEM_PROMPT != "")
{
llOwnerSay("System prompt loaded successfully.");
}
else
{
llOwnerSay("Notice: System prompt notecard is empty. No system prompt will be used.");
}
initialization_complete = TRUE;
llOwnerSay("Initialization complete.");
listen_handle = llListen(LISTEN_CHANNEL, "", NULL_KEY, "");
llOwnerSay("Say something in chat to start a conversation.");
llOwnerSay("Say '/reset' to clear memory.");
llOwnerSay("Touch to see current memory.");
}
}
}
listen(integer channel, string name, key id, string message)
{
if (message == "/reset")
{
message_memory = [];
llSay(0, "Memory has been reset.");
return;
}
add_to_memory("user", message);
send_to_groq();
}
http_response(key request_id, integer status, list metadata, string body)
{
if (request_id == http_request_id)
{
//llOwnerSay("Debug - HTTP Status: " + (string)status);
//llOwnerSay("Debug - Full Response: " + body);
if (status == 200)
{
// Parse the OpenAI-compatible response format from Groq
string content = llJsonGetValue(body, ["choices", 0, "message", "content"]);
if (content != JSON_INVALID)
{
// Handle escaped characters
content = llDumpList2String(llParseString2List(content, ["\\n"], []), " ");
content = llDumpList2String(llParseString2List(content, ["\\\""], []), "\"");
content = llDumpList2String(llParseString2List(content, ["\\\\"], []), "\\");
// Add to memory and display
add_to_memory("assistant", content);
llSay(0, "AI: " + content);
}
else
{
llSay(0, "Error: Content field not found in API response.");
llOwnerSay("Debug - Response structure: " + body);
}
}
else
{
llSay(0, "API Error: " + (string)status + " - " + body);
}
}
}
touch_start(integer total_number)
{
if (llDetectedKey(0) == llGetOwner())
{
display_memory();
}
}
on_rez(integer start_param)
{
message_memory = [];
initialize();
}
changed(integer change)
{
if (change & CHANGED_INVENTORY)
{
initialize();
}
}
}

Leave a comment