    //% color="#1e90ff" iconWidth=50 iconHeight=40
    namespace doubao{
        
    //% block="初始化API密钥[api_psd]接入点ID[id_psd]温度[temp]" blockType="command"
    //% api_psd.shadow="string" api_psd.defl=c4a347fc-b9f9-4be6-96f5-b3334abf9016
    //% id_psd.shadow="string" id_psd.defl=ep-20250624120313-pt5n6
    //% temp.shadow="number" temp.defl=0.3
    export function myBlock3(parameter: any, block: any) {
        let api_psd= parameter.api_psd.code
        let id_psd= parameter.id_psd.code
        let temp= parameter.temp.code
        Generator.addInclude("HTTPClient",`#include <HTTPClient.h>`)
        Generator.addInclude("ArduinoJsonK10",`#include <ArduinoJsonK10.h>`)
        Generator.addInclude("k10_base64",`#include "k10_base64.h"`)
        Generator.addObject("doubao_apiKey",`const char*`, `doubao_apiKey = ${api_psd};  // API密钥`)
        Generator.addObject("apiUrl",`const String `,`apiUrl = "https://ark.cn-beijing.volces.com/api/v3/chat/completions";  // API地址`)
        Generator.addObject("model",`const String`, `model = ${id_psd};  // 使用的模型`)
        Generator.addObject("temperature",`const float`, `temperature = ${temp};                   // AI创造性参数（0-1）`)

    }
    //% block="初始化角色[role]" blockType="command"
    //% role.shadow="string" role.defl=你是人工智能助手，你叫小行
    export function myBlock2(parameter: any, block: any) {
        let role= parameter.role.code
        Generator.addObject("systemPrompt",`const String`, `systemPrompt = ${role};`)
    }
    //% block="发送消息[msg]" blockType="command"
    //% msg.shadow="string" msg.defl=你好，小行！
    export function myBlock5(parameter: any, block: any) {
        let msg= parameter.msg.code
        let func = [
          'String getGPTAnswer(String inputText) {',
          '  HTTPClient http;',
          '  http.setTimeout(30000);  // 使用配置的超时时间',
          '  if (!http.begin(apiUrl)) {',
          '    //Serial.println("HTTP连接初始化失败");',
          '    return "<network_error>";',
          '  }',
          '  // 设置请求头',
          '  http.addHeader("Content-Type", "application/json");',
          '  http.addHeader("Authorization", "Bearer " + String(doubao_apiKey));',
          '  // 构建JSON请求体（使用配置的模型和参数）',
          '  String payload = "{";',
          '  payload += "\\"model\\":\\"" + model + "\\",";',
          '  payload += "\\"messages\\":[";',
          '  payload += "{\\"role\\":\\"system\\",\\"content\\":\\"" + systemPrompt + "\\"},";',
          '  payload += "{\\"role\\":\\"user\\",\\"content\\":\\"" + inputText + "\\"}";',
          '  payload += "],";', 
          '  payload += "\\"temperature\\":" + String(temperature);',
          '  payload += "}";',
          '  // 发送POST请求',
          '  int httpCode = http.POST(payload);',
          '  String outputText = "<error>";',
          '  // 处理响应',
          '  if (httpCode == 200) {',
          '    String response = http.getString();',    
          '    DynamicJsonDocument jsonDoc(4096);  // 使用配置的缓冲区大小',
          '    DeserializationError error = deserializeJson(jsonDoc, response);',
          '    if (!error) {',
          '      outputText = jsonDoc["choices"][0]["message"]["content"].as<String>();',
          '    } else {',
          '      //Serial.print("JSON解析错误: ");',    
          '      //Serial.println(error.c_str());',
          '    }',
          '  } else {',
          '    //Serial.printf("HTTP错误代码: %d", httpCode);',
          '  }',
          '  http.end();',    
          '  return outputText;',
          '}'
        ]
        Generator.addObject("answer",`String`, `answer;`)
        Generator.addFunction("getGPTAnswer","String","getGPTAnswer","String inputText",func)
        Generator.addCode(`answer = "";`)
        Generator.addCode(`answer = getGPTAnswer(${msg});`)
    }
    //% block="发送消息，文字[msg_urlimg]，图片URL[url_img]" blockType="command"
    //% msg_urlimg.shadow="string" msg_urlimg.defl=图片主要讲了什么?
    //% url_img.shadow="string" url_img.defl=https://ark-project.tos-cn-beijing.volces.com/images/view.jpeg
    export function myBlock6(parameter: any, block: any) {
        let msg_urlimg= parameter.msg_urlimg.code
        let url_img= parameter.url_img.code
        let func = [
          'String getGPTAnswer_urlimg(String inputText, String imageUrl = "") {',
          '  HTTPClient http;',
          '  http.setTimeout(30000);  // 使用配置的超时时间',
          '  if (!http.begin(apiUrl)) {',
          '    return "<network_error>";',
          '  }',
          '  http.addHeader("Content-Type", "application/json");',
          '  http.addHeader("Authorization", "Bearer " + String(doubao_apiKey));',
          '  String payload = "{";',
          '  payload += "\\"model\\":\\"" + model + "\\",";',
          '  payload += "\\"messages\\":[";',
          '  payload += "{\\"role\\":\\"system\\",\\"content\\":\\"" + systemPrompt + "\\"},";',
          '  if (imageUrl == "") {',
          '    // 纯文本模式',
          '    payload += "{\\"role\\":\\"user\\",\\"content\\":\\"" + inputText + "\\"}";',
          '  } else {',
          '    // 图片模式',
          '    payload += "{\\"role\\":\\"user\\",\\"content\\":[";',
          '    payload += "{\\"type\\":\\"image_url\\",\\"image_url\\":{\\"url\\":\\"" + imageUrl + "\\"}},";',
          '    payload += "{\\"type\\":\\"text\\",\\"text\\":\\"" + inputText + "\\"}";',
          '    payload += "]}";',
          '  }',
          '  payload += "],";',
          '  payload += "\\"temperature\\":" + String(temperature);',
          '  payload += "}";',
          '  int httpCode = http.POST(payload);',
          '  String outputText = "<error>";',
          '  if (httpCode == 200) {',
          '    String response = http.getString();',    
          '    DynamicJsonDocument jsonDoc(4096);  // 使用配置的缓冲区大小',
          '    DeserializationError error = deserializeJson(jsonDoc, response);',
          '    if (!error) {',
          '      outputText = jsonDoc["choices"][0]["message"]["content"].as<String>();',
          '    } else {',
          '      //Serial.print("JSON解析错误: ");',    
          '      //Serial.println(error.c_str());',
          '    }',
          '  } else {',
          '    //Serial.printf("HTTP错误代码: %d", httpCode);',
          '  }',
          '  http.end();',    
          '  return outputText;',
          '}'
        ]
        Generator.addObject("answer",`String`, `answer;`)
        Generator.addFunction("getGPTAnswer_urlimg","String","getGPTAnswer_urlimg","String inputText, String imageUrl",func)
        Generator.addCode(`answer = "";`)
        Generator.addCode(`answer = getGPTAnswer_urlimg(${msg_urlimg},${url_img});`)
    }
    //% block="发送消息，文字[msg_camera]，摄像头照片" blockType="command"
    //% msg_camera.shadow="string" msg_camera.defl=图片里面讲了什么?
    export function myBlock7(parameter: any, block: any) {
        let msg_camera= parameter.msg_camera.code
        let func = [
          'String getGPTAnswer_camera(String inputText) {',
          '  String imageFormat = "jpg";',
          '  K10_base64 k10base64;',
          '  String base64Image = k10base64.K10tobase64();',
          '  if (base64Image == "NULL" || base64Image.length() == 0) {',
          '    Serial.println("摄像头拍照失败");',
          '    return "<camera_error>";',
          '  }',
          '  Serial.println("Base64编码成功，长度: " + String(base64Image.length()));',
          // 检查图片大小，如果太大则返回错误
          '  if (base64Image.length() > 100000) {  // 限制在100KB以内',
          '    Serial.println("图片太大，请调整摄像头分辨率或质量");',
          '    return "<image_too_large>";',
          '  }',
          '  WiFiClientSecure client;',
          '  String outputText = "<error>";',
          '  // 设置SSL证书验证（跳过证书验证以简化连接）',
          '  client.setInsecure();',
          '  if (!client.connect("ark.cn-beijing.volces.com", 443)) {',
          '    Serial.println("连接服务器失败");',
          '    return "<connection_error>";',
          '  }',
          '  // 构建请求体',
          '  String payload = "{";',
          '  payload += "\\"model\\":\\"" + model + "\\",";',
          '  payload += "\\"messages\\":[";',
          '  payload += "{\\"role\\":\\"system\\",\\"content\\":\\"" + systemPrompt + "\\"},";',
          '  payload += "{";',
          '  payload += "\\"role\\":\\"user\\",";',
          '  payload += "\\"content\\":[";',
          '  payload += "{\\"type\\":\\"text\\",\\"text\\":\\"" + inputText + "\\"},";',
          '  payload += "{\\"type\\":\\"image_url\\",";',
          '  payload += "\\"image_url\\":{\\"url\\":\\"data:image/" + imageFormat + \";base64,\" + base64Image + \"\\\"}";',
          '  payload += "}";',
          '  payload += "]";',
          '  payload += "}";',
          '  payload += "]";',
          '  payload += ",\\"temperature\\":" + String(temperature);',
          '  payload += "}";',
              
          '  // 发送HTTP请求头',
          '  String request = "POST /api/v3/chat/completions HTTP/1.1\\r\\n";',
          '  request += "Host: ark.cn-beijing.volces.com\\r\\n";',
          '  request += "Content-Type: application/json\\r\\n";',
          '  request += "Authorization: Bearer " + String(doubao_apiKey) + "\\r\\n";',
          '  request += "Transfer-Encoding: chunked\\r\\n";',
          '  request += "Connection: close\\r\\n";',
          '  request += "\\r\\n";',
                
          '  client.print(request);',
          '  // 分块发送数据',
          '  int chunkSize = 4096; // 4KB每块',
          '  int totalLength = payload.length();',
          '  int sent = 0;',
          '  int chunkCount = 0;',
                
          '  while (sent < totalLength) {',
          '    int currentChunkSize = min(chunkSize, totalLength - sent);',
          '    String chunk = payload.substring(sent, sent + currentChunkSize);',
          '    // 发送块大小（十六进制）',
          '    String chunkHeader = String(currentChunkSize, HEX) + "\\r\\n";',
          '    client.print(chunkHeader);',
          '    // 发送块数据',
          '    client.print(chunk);',
          '    client.print("\\r\\n");',
          '    sent += currentChunkSize;',
          '    chunkCount++;',
                  
          '  delay(5); // 小延迟避免缓冲区溢出',
          '  }',
          '  // 发送结束块',
          '  client.print("0\\r\\n\\r\\n");',
          '  // 读取响应',
          '  String response = "";',
          '  unsigned long timeout = millis() + 300000; // 5分钟超时',
          '  unsigned long startTime = millis();',
                
          '  while (client.connected() && millis() < timeout) {',
          '    if (client.available()) {',
          '      String chunk = client.readString();',
          '      response += chunk;',
          '     }',
          '     delay(10);',
          '  }',
          '  unsigned long responseTime = millis() - startTime;',
          '  client.stop();',
                
          '  // 解析响应',
          '  if (response.length() > 0) {',
          '    // 找到JSON开始位置（跳过HTTP头）',
          '    int jsonStart = response.indexOf("\\r\\n\\r\\n");',
          '    if (jsonStart > 0) {',
          '      response = response.substring(jsonStart + 4);',
          '    }',
                  
          '    DynamicJsonDocument jsonDoc(32768);',
          '    DeserializationError error = deserializeJson(jsonDoc, response);',
          '    if (!error) {',
          '      outputText = jsonDoc["choices"][0]["message"]["content"].as<String>();',
          '    } else {',
          '      Serial.print("JSON解析错误: ");',
          '      Serial.println(error.c_str());',
          '      Serial.println("完整响应: " + response);',
          '    }',
          '  } else {',
          '    Serial.println("未接收到响应");',
          '  }',
          '  return outputText;',
          '}'
        ]
        Generator.addObject("answer",`String`, `answer;`)
        Generator.addFunction("getGPTAnswer_camera","String","getGPTAnswer_camera","String inputText",func)
        Generator.addCode(`answer = "";`)
        Generator.addCode(`answer = getGPTAnswer_camera(${msg_camera});`)
    }
    //% block="获取结果" blockType="reporter"
    export function myBlock4(parameter: any, block: any) {
        Generator.addCode(`answer`)
    }
    }
    