You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PaLM API JSON请求异常问题排查及修复(Roblox Lua实现)

修复Roblox Lua调用PaLM API时JSON请求失效的问题

在Roblox Lua中调用PaLM API的JSON请求一直无法正常工作,排查后发现问题出在MakeRequest函数的pcall代码块内——忘记添加return response语句,导致请求的响应结果没有被正确返回,后续解析响应体时触发"attempt to index nil with the Body"错误。

以下是修复后的完整代码:

--google palm--
--roblox lua

local Players = game:GetService("Players");
local HttpService = game:GetService("HttpService");
local LocalPlayer = Players.LocalPlayer;
local RequestFunction = request; -- 修正原代码拼写错误:RequestFunctiom → RequestFunction
local function MakeRequest(Prompt)
    local success, response = pcall(function()
        -- 核心修复:添加return,将request的执行结果返回给pcall的response变量
        return RequestFunction({
           Url = "https://generativelanguage.googleapis.com/v1beta2/models/text-bison-001:generateText?key=KEY_HERE",
            Method = "POST",
            Headers = {
                ["Content-Type"] = "application/json",
            },
            Body = HttpService:JSONEncode({
            prompt = {
              text = Prompt
            },
            temperature = 0.7,
            candidateCount = 1,
            topP = 0.95,
            topK = 5,
            maxOutputTokens = 100,
            stopSequences = {"Human:", "Ai:"},
            })
        })
    end)
    print(response)
    return response
end
print("MakeRequest sending")
print("test1")
local HttpRequest = MakeRequest("Human: Hello how are you today 

AI:");
-- 注意:添加wait(3)会导致HttpRequest变为nil,触发索引错误,因为请求未完成就执行解析逻辑
local Response =  ". " .. string.sub(HttpService:JSONDecode(HttpRequest["Body"]).candidates[1].output, 2);
print(Response)

注意事项:

  • 务必将代码中的KEY_HERE替换为你的PaLM API密钥
  • 原代码中存在变量拼写错误RequestFunctiom,已修正为正确的RequestFunction
  • 不要随意添加wait(3),否则会打断请求流程,导致解析时拿到nil值

内容的提问来源于stack exchange,提问作者Random

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 12:26:04