New “sk-proj” OpenAI Key Truncated? WebRequest Always Returns “You didn’t provide an API key.”

 

Hello everyone,

I’m attempting to integrate ChatGPT (gpt-3.5-turbo) into MetaTrader 5 using WebRequest() in MQL5. When I call https://api.openai.com/v1/chat/completions , I consistently get a 401 response telling me:

"You didn’t provide an API key. You need to provide your API key in an Authorization header using Bearer auth..."

It looks as if the Authorization: Bearer header is never recognized by OpenAI.

Key details:

  1. I have a new “sk-proj...” type of API key from OpenAI, which can be about 130–160 characters long.
  2. In MetaTrader, I’ve added https://api.openai.com to Tools → Options → Expert Advisors → “Allow WebRequest”.
  3. I’ve tested multiple MT5 builds (including the latest from MetaQuotes directly).
  4. Using cURL or Python with the exact same key works fine, so the key itself is valid.
  5. Trying to capture the HTTPS request via Fiddler or Wireshark just shows a CONNECT tunnel with no decrypted headers, suggesting MT5 might be rejecting man-in-the-middle SSL or possibly “pinning” the certificate.

Has anyone faced issues with these longer “sk-proj” keys causing MQL5’s WebRequest() to drop or truncate the Authorization header? Or do we need an official MT5 update to handle these keys properly?

Below is a simplified code snippet showing how I’m sending the request:


//+------------------------------------------------------------------+
//|  ChatGPTRequest.mq5                                             |
//|  MQL5 Script: Minimal example                                    |
//+------------------------------------------------------------------+
#property script_show_inputs

void OnStart()
{
   // 1) My new “sk-proj...” key (length ~100+ chars)
   string openai_api_key = "sk-proj-EXAMPLE_KEY_which_is_quite_long...";

   // 2) A simple JSON body for Chat Completions
   string json_body = 
      "{\"model\":\"gpt-3.5-turbo\","
      "\"messages\":[{\"role\":\"user\",\"content\":\"Hello!\"}],"
      "\"max_tokens\":50}";

   // Convert JSON to UTF-8 char array
   char data[];
   int size = StringToCharArray(json_body, data, 0, StringLen(json_body), CP_UTF8);
   ArrayResize(data, size + 1);
   data[size] = 0; // null-terminate

   // 3) Headers (with Authorization)
   string headers =
      "Content-Type: application/json\r\n"
      "Authorization: Bearer " + openai_api_key + "\r\n"
      "\r\n";

   // 4) WebRequest call
   char resultBuf[];
   string cookie;
   int timeoutMs = 10000;
   string openai_url = "https://api.openai.com/v1/chat/completions";

   int res = WebRequest(
      "POST",
      openai_url,
      headers,
      "",                // params = empty
      timeoutMs,
      data,
      size,
      resultBuf,
      cookie
   );

   Print("WebRequest return = ", res);
   if(res == -1)
   {
      Print("Error code: ", GetLastError());
   }
   else
   {
      // Show the server's response
      string response = CharArrayToString(resultBuf, 0, -1);
      Print("OpenAI response: ", response);
   }
}


Result: Always returns 401 with

"You didn't provide an API key..."

Questions:
  • Have you successfully used ChatGPT with MQL5 and the newer, longer “sk-proj-...” keys?
  • Is there a known limit on WebRequest() or on the MQL field that might truncate the API key?
  • Any workaround or official fix to ensure Authorization: Bearer is actually sent?

Thanks in advance for any guidance!

 
Your topic has been moved to the section: Expert Advisors and Automated Trading
Please consider which section is most appropriate — https://www.mql5.com/en/forum/172166/page6#comment_49114893
 
just wondering if you use valid key here ?


string openai_api_key = "sk-proj-EXAMPLE_KEY_which_is_quite_long...";

To verify your POST, you can send it to:
https://httpbin.org/#/Anything

and save the returned response to verify your request.

note:
don't post real key there, just same long string to verify webrequest post.
;)

good luck

 
Soewono Effendi #:
just wondering if you use valid key here ?




Thank you for your comment. I have already confirmed that the key is valid by testing it through CMD (Command Prompt). If there’s any specific issue you believe might be related to the key, please let me know.
 
Soewono Effendi #:
just wondering if you use valid key here ?



To verify your POST, you can send it to:

and save the returned response to verify your request.

note:
don't post real key there, just same long string to verify webrequest post.
;)

good luck

Thank you for your suggestion. I will try sending my POST request to https://httpbin.org/#/Anything to verify it and review the returned response. I appreciate your advice and will update if I find any issues.
 
Thank you for your suggestion, Soewono Effendi. I tried verifying my POST request using https://httpbin.org/#/Anything, but unfortunately, it didn’t resolve the issue.

I’ll continue seeking solutions and would greatly appreciate any further advice or recommendations. Thank you again for your support!
 
change this
// Convert JSON to UTF-8 char array
   char data[];
   int size = StringToCharArray(json_body, data, 0, StringLen(json_body), CP_UTF8);
   ArrayResize(data, size + 1);
   data[size] = 0; // null-terminate
to
// Convert JSON to UTF-8 char array
   char data[];
   StringToCharArray(json_body, data, 0, StringLen(json_body)-1, CP_UTF8);
  

and verify again using httpbin.
good luck.

 

See if that helps.

Forum on trading, automated trading systems and testing of trading strategies

New MetaTrader 5 platform version build 4620: MQL5 bug fixes and new OpenBLAS methods

Stanislav Korotky , 2024.11.29 19:49

Once again I came across a couple of glitches, which I managed to solve only because it was not the first time. The illogical behavior of the system does not fit in my head, so I periodically forget about the catch.

Here is a seemingly simple function:

 bool DumpTextToFile( const string name, const string buffer)
{
   uchar bytes[];
   StringToCharArray (buffer, bytes, 0 , - 1 , CP_UTF8 );
   return FileSave (name, bytes);
}

But don't believe your eyes. A text file created this way won't be able to be opened by MetaEditor - or rather, it opens a tab for it, but doesn't show the contents. The whole point is that the array (and the file) gets a terminal 0. All other text editors open such a file without any problems.

If we assume a trivial solution:

 bool DumpTextToFile( const string name, const string buffer)
{
   uchar bytes[];
   StringToCharArray (buffer, bytes, 0 , StringLen (buffer), CP_UTF8 );
   return FileSave (name, bytes);
}

we will get a new bug - if the text contains non-Latin letters, then not all the text will be written to the file, because the arguments of the StringToCharArray function refer to the buffer (!), and not the string, and when encoding in utf-8, the buffer increases in size compared to the string.

Final solution (with bugs I haven't found yet):

 bool DumpTextToFile( const string name, const string buffer)
{
   uchar bytes[];
   StringToCharArray (buffer, bytes, 0 , - 1 , CP_UTF8 );
   ArrayResize (bytes, bytes.Size() - 1 );
   return FileSave (name, bytes);
}

 
You passed incorrect params to webrequest func