CoeurdeLeon 8 Posted December 29, 2022 Does anyone have a working example where a connection is made with chatgpt, a question is asked and a response successfully returned. I have tried with both indy and ipworks components. I get a variety of errors. Here are 2 IPworks functions: Unit ads.ChatGpt; Interface Function ChatWithGPT(Const question, Api_Key: String): String; Function ChatWithGPT2(Const question, Api_Key: String): String; Implementation Uses ipwcore, ipwhttp, ipwrest, ipwtypes, System.SysUtils; Function ChatWithGPT(Const question, Api_Key: String): String; Var http : TIpwHttp; response: String; Begin http := TIpwHttp.Create(Nil); Try http.AddCookie('Authorization', 'Bearer ' + Api_Key); http.Get('https://api.openai.com/v1/chatgpt/chat?question=' + question); response := http.TransferredData; Result := response; Finally http.Free; End; End; Function ChatWithGPT2(Const question, Api_Key: String): String; Var rest : TipwREST; response: String; Begin rest := TipwREST.Create(Nil); Try rest.ContentType := 'application/json'; rest.OtherHeaders := 'Authorization: Bearer ' + Api_Key; rest.PostData := '{\"model\": \"text-davinci-003\", \"prompt\": \"" + question + "\", \"temperature\": 0, \"max_tokens\": 64}'; rest.Post('https://api.openai.com/v1/completions'); rest.XPath := '/json/choices/[1]/text'; response := rest.XText.Replace('\"', ''); Result := response; Finally FreeAndNil(rest); End; End; End. Richard Maley Share this post Link to post
Dave Nottage 557 Posted December 29, 2022 (edited) 2 hours ago, CoeurdeLeon said: I get a variety of errors Why did you choose not to include those in your post? 2 hours ago, CoeurdeLeon said: rest.PostData := '{\"model\": \"text-davinci-003\", \"prompt\": \"" + question + "\", \"temperature\": 0, \"max_tokens\": 64}'; Do the quotes here really need to be escaped? 2 hours ago, CoeurdeLeon said: http.Get('https://api.openai.com/v1/chatgpt/chat?question=' + question); Is that URL documented somewhere? I'm unable to find it Edited December 29, 2022 by Dave Nottage 1 Share this post Link to post
CoeurdeLeon 8 Posted December 29, 2022 I have 3 functions using IPWorks: Unit ads.ChatGpt; Interface Function ChatWithGPT(Const question, Api_Key: String): String; Function ChatWithGPT2(Const question, Api_Key: String): String; Function ChatWithGPT3(Const question, Api_Key: String): String; Implementation Uses chatgpt_p, ipwcore, ipwhttp, ipwrest, ipwtypes, System.SysUtils, System.NetEncoding; Function ChatWithGPT(Const question, Api_Key: String): String; Var http : TIpwHttp; response: String; Begin http := TIpwHttp.Create(Nil); Try http.AddCookie('Authorization', 'Bearer ' + Api_Key); http.Get('https://api.openai.com/v1/chatgpt/chat?question=' + question); response := http.TransferredData; Result := response; Finally http.Free; End; End; Function ChatWithGPT2(Const question, Api_Key: String): String; Var rest : TipwREST; response: String; Begin rest := TipwREST.Create(Nil); Try rest.ContentType := 'application/json'; rest.OtherHeaders := 'Authorization: Bearer ' + Api_Key; rest.PostData := '{\"model\": \"text-davinci-003\", \"prompt\": \"" + question + "\", \"temperature\": 0, \"max_tokens\": 64}'; rest.Post('https://api.openai.com/v1/completions'); rest.XPath := '/json/choices/[1]/text'; response := rest.XText.Replace('\"', ''); Result := response; Finally FreeAndNil(rest); End; End; Function ChatWithGPT3(Const question, Api_Key: String): String; Var http : TIpwHttp; response: String; Begin http := TIpwHttp.Create(Nil); Try http.OnSSLServerAuthentication:=frmchatgpt.ipwHTTP1SSLServerAuthentication; http.AddCookie('Authorization', 'Bearer ' + Api_Key); http.Get('https://api.openai.com/v1/chatgpt/chat?question=' + TNetEncoding.URL.Encode(question)); response := http.TransferredData; Result := response; Except on E: Exception do Result := 'Error: ' + E.Message; End; http.Free; End; End. The errors are as follows: Function ChatWithGPT(Const question, Api_Key: String): String; Function ChatWithGPT2(Const question, Api_Key: String): String; Function ChatWithGPT3(Const question, Api_Key: String): String; Richard Maley Share this post Link to post
Rolphy Reyes 0 Posted December 29, 2022 Hi! I don't know if you have seen this blog (and may help you): https://www.tmssoftware.com/site/blog.asp?post=1045 Share this post Link to post
CoeurdeLeon 8 Posted December 30, 2022 Thank you. No I had not seen this. My only problem is I need to spend more money. And it is not completely clear what TMS product I need to buy. I have already spent a ton of money on Rad Studio Architect and IPWorks. I would like to get IPWorks or Indy working to save a buck. I do thank you for pointing out this solution. Richard Maley Share this post Link to post
Dave Nottage 557 Posted December 30, 2022 2 hours ago, CoeurdeLeon said: Function ChatWithGPT(Const question, Api_Key: String): String; Function ChatWithGPT3(Const question, Api_Key: String): String; Because the URL is probably invalid. It does not appear to be documented anywhere. 2 hours ago, CoeurdeLeon said: Function ChatWithGPT2(Const question, Api_Key: String): String; Because, as the error says, the request is bad. As I said: 2 hours ago, Dave Nottage said: Do the quotes here really need to be escaped? This should work as long as there's no characters that need escaping in the question variable: rest.PostData := '{"model": "text-davinci-003", "prompt": "' + question + '", "temperature": 0, "max_tokens": 64}'; Share this post Link to post
esegece 47 Posted December 30, 2022 (edited) Hello, The API is very simple, you can use Indy to send the POST request and then parse the JSON response. Find below an example: function AskChatGPT(const aAPI, aQuestion: string): string; var oHTTP: TIdHTTP; oSSL: TIdSSLIOHandlerSocketOpenSSL; oStream: TStringStream; vPostData: string; oJSON: TJSONValue; oArray: TJSonArray; begin oHTTP := TIdHTTP.Create(nil); oSSL := TIdSSLIOHandlerSocketOpenSSL.Create(nil); Try oSSL.SSLOptions.Method := sslvTLSv1_2; oHTTP.IOHandler := oSSL; oHTTP.Request.CustomHeaders.Add('Authorization: Bearer ' + aAPI); oHTTP.Request.ContentType := 'application/json'; vPostData := Format('{"model": "text-davinci-003","prompt": "%s","max_tokens": 2048,"temperature": 0}', [aQuestion]); // send request oStream := TStringStream.Create(vPostData); Try result := oHTTP.Post('https://api.openai.com/v1/completions', oStream); // parse response oJSON := TJSonObject.ParseJSONValue(result).GetValue<TJSONValue> ('choices'); result := TJSonArray(oJSON).Items[0].GetValue<TJSONString>('text').Value; Finally oStream.Free; End; Finally oSSL.Free; oHTTP.Free; End; end; The function has 2 arguments, the API key (can be obtained from https://beta.openai.com/account/api-keys) and the message you want to sent to ChatGPT. The function just sends the API Key as a Bearer Token and POST the JSON message to the server. The server returns a JSON object that must be parsed to obtain the response text. I've attached the complete project with the required openSSL libraries. Kind Regards, Sergio chatgpt_esegece.zip Edited December 30, 2022 by esegece 3 Share this post Link to post
CoeurdeLeon 8 Posted December 30, 2022 Esegece WOW!!! WOW!!! WOW!!! VERY GOOD!!! IT WORKS VERY WELL. Thank you. Richard Maley Share this post Link to post
toms 29 Posted December 30, 2022 Comment from the TMS website: Quote Just as a note and for people don''t get confused, this API is not to use ChatGPT. This API is to use GPT-3 text transformer. Although ChatGPT is based on GPT-3, they are totally different models, and there is no API to use ChatGPT yet. Share this post Link to post
Rollo62 536 Posted December 30, 2022 3 hours ago, toms said: Although ChatGPT is based on GPT-3, they are totally different models Thats true. As far as I could see from the chatGPT Playground, this is very well capable to remember earlier prompts in the conversation, while this GPT3 API only answers more or less to the current prompt. I think that is one of the main, important differences so far in chatGPT, among other algorithm details probably. Share this post Link to post
CoeurdeLeon 8 Posted December 30, 2022 Thank you for all the responses. I would like to specially thank esegese (Sergio Gomez Cortijo). I was hoping to demonstrate a number of methods of connecting to chatGPT. However I have now modified that objective to connecting with GPT3. Listed below is a unit that either uses Indy or IPworks to query GPT3. The 3 functions work well for me and I hope they work for you. I had also wanted to have some functions that use the http get method, but none worked for me. Unit ads.Gpt3; Interface Function GPT3_IndyPostWithSSL(Const question, Api_Key: String): String; //Indy Post with SSL Function GPT3_IPWorks_PostWithRest(Const question, Api_Key: String): String; Function GPT3_IPWorksWithPost(Const question, Api_Key: String): String; Implementation Uses IdHttp, IdSSLOpenSSL, ipwcore, ipwhttp, ipwrest, ipwtypes, ipwxml, System.Classes, System.JSON, System.NetEncoding, System.SysUtils, Vcl.Dialogs, Vcl.Forms; Function GPT3_IndyPostWithSSL(Const question, Api_Key: String): String; //Indy Post with SSL Var http : TIdHTTP; JSON : TJSONValue; JSonArray: TJSonArray; PostData : String; SSL : TIdSSLIOHandlerSocketOpenSSL; Stream : TStringStream; Begin http := TIdHTTP.Create(Nil); SSL := TIdSSLIOHandlerSocketOpenSSL.Create(Nil); Try SSL.SSLOptions.Method := sslvTLSv1_2; http.IOHandler := SSL; http.Request.CustomHeaders.Add('Authorization: Bearer ' + Api_Key); http.Request.ContentType := 'application/json'; PostData := Format('{"model": "text-davinci-003","prompt": "%s","max_tokens": 2048,"temperature": 0}', [question]); Stream := TStringStream.Create(PostData); Try Result := http.Post('https://api.openai.com/v1/completions', Stream); JSON := TJSonObject.ParseJSONValue(Result).GetValue<TJSONValue>('choices'); Result := TJSonArray(JSON).Items[0].GetValue<TJSONString>('text').Value; Finally Stream.Free; End; Finally SSL.Free; http.Free; End; End; Function GPT3_IPWorks_PostWithRest(Const question, Api_Key: String): String; Var ipwrest: TipwREST; Begin ipwrest := TipwREST.Create(Nil); Try ipwrest.ContentType := 'application/json'; ipwrest.OtherHeaders := 'Authorization: Bearer ' + Api_Key; ipwrest.PostData := Format('{"model": "text-davinci-003","prompt": "%s","max_tokens": 2048,"temperature": 0}', [question]); Try ipwrest.Post('https://api.openai.com/v1/completions'); ipwrest.XPath := '/json/choices/[1]/text'; Result := ipwrest.XText; If Pos('"', Result) = 1 Then Result := Copy(Result, 2, Length(Result) - 1 + 1); If Copy(Result, Length(Result), 1) = '"' Then Result := Copy(Result, 1, Length(Result) - 1); If Copy(Result, 1, 4) = '\n\n' Then Result := Copy(Result, 5, Length(Result) - 5); Result := Trim(Result); Except On E: Exception Do ShowMessage(E.ClassName + ': ' + E.Message); End; Finally FreeAndNil(ipwrest); End; End; Function GPT3_IPWorksWithPost(Const question, Api_Key: String): String; Var http : TIpwHttp; response : String; JSON : TJSONValue; JSonArray: TJSonArray; Begin http := TIpwHttp.Create(Nil); Try Try http.ContentType := 'application/json'; http.OtherHeaders := 'Authorization: Bearer ' + Api_Key; http.PostData := Format('{"model": "text-davinci-003","prompt": "%s","max_tokens": 2048,"temperature": 0}', [question]); http.Post('https://api.openai.com/v1/completions'); response := http.TransferredData; JSON := TJSonObject.ParseJSONValue(response).GetValue<TJSONValue>('choices'); Result := TJSonArray(JSON).Items[0].GetValue<TJSONString>('text').Value; Except On E: Exception Do Result := 'Error: ' + E.Message; End; Finally FreeAndNil(http); End; End; End. Richard Maley Share this post Link to post
limelect 48 Posted January 7, 2023 fpiette / DelphiChatGPT https://github.com/fpiette/DelphiChatGPT 1 Share this post Link to post
limelect 48 Posted January 7, 2023 Tested it needs 2 ssl DLL's found them on HeidiSQL-project Share this post Link to post
limelect 48 Posted January 8, 2023 (edited) @esegece For Both applications, I tested writing the word >>>>> help see what happens. on the site https://chat.openai.com/chat I get the answer Of course! How can I help you today? This is what I get Q: help A: ers/esm/inherits.js"); /* harmony import */ var _babel_runtime_helpers_esm_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/esm/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js"); /* harmony import */ var _babel_runtime_helpers_esm_getPrototypeOf__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/esm/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js"); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! react */ "./node_modules/react/index.js"); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_5__); /* harmony import */ var _components_Layout__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../components/Layout */ "./components/Layout.js"); /* harmony import */ var _components_Header__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../components/Header */ "./components/Header.js"); /* harmony import */ var _components_Content__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../components/Content */ "./components/Content.js"); /* harmony import */ var _components_Footer__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../components/Footer */ "./components/Footer.js"); var _jsxFileName = "/Users/muhsinsutanto/Documents/practice/react_practice/hello-next/pages/index.js"; var __jsx = react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement; function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = Object(_babel_runtime_helpers_esm_getPrototypeOf__WEBPACK_IMPORTED_MODULE_4__["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = Object(_babel_runtime_helpers_esm_getPrototypeOf__WEBPACK_IMPORTED_MODULE_4__["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return Object(_babel_runtime_helpers_esm_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_3__["default"])(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } var Index = /*#__PURE__*/function (_React$Component) { Object(_babel_runtime_helpers_esm_inherits__WEBPACK_IMPORTED_MODULE_2__["default"])(Index, _React$Component); var _super = _createSuper(Index); function Index() { Object(_babel_runtime_helpers_esm_classCallCheck__WEBPACK_IMPORTED_MODULE_0__["default"])(this, Index); return _super.apply(this, arguments); } Object(_babel_runtime_helpers_esm_createClass__WEBPACK_IMPORTED_MODULE_1__["default"])(Index, [{ key: "render", value: function render() { return __jsx(_components_Layout__WEBPACK_IMPORTED_MODULE_6__["default"], { __self: this, __source: { fileName: _jsxFileName, lineNumber: 11, columnNumber: 7 } }, __jsx(_components_Header__WEBPACK_IMPORTED_MODULE_7__["default"], { __self: this, __source: { fileName: _jsxFileName, lineNumber: 12, columnNumber: 9 } }), __jsx(_components_Content__WEBPACK_IMPORTED_MODULE_8__["default"], { __self: this, __source: { fileName: _jsxFileName, lineNumber: 13, columnNumber: 9 } }), __jsx(_components_Footer__WEBPACK_IMPORTED_MODULE_9__["default"], { __self: this, __source: { fileName: _jsxFileName, lineNumber: 14, columnNumber: 9 } })); } }]); return Index; }(react__WEBPACK_IMPORTED_MODULE_5___default.a.Component); /* harmony default export */ __webpack_exports__["default"] = (Index); /***/ }) }) //# sourceMappingURL=index.js.f9f9f9f9f9f9f9f9f9f.hot-update.js.map ---- Edited January 8, 2023 by limelect Share this post Link to post
esegece 47 Posted January 8, 2023 @limelect because as in a previous post has been noted, these examples are using GPT-3 text transformer, not ChatGPT. ChatGPT has not API access yet. So you can receive different responses if you compare both. Kind Regards, Sergio 1 Share this post Link to post
Jars 0 Posted April 23, 2023 Hi, Could someone tell me how to use this code in Delphi 7 with Indy10? Thank in advance. Share this post Link to post
programmerdelphi2k 237 Posted April 23, 2023 (edited) did try the sample using INDY above? On 12/30/2022 at 8:35 PM, CoeurdeLeon said: Function GPT3_IndyPostWithSSL(Const question, Api_Key: String): String; //Indy Post with SSL = need 2 DLL from Open SSL to INDY version Edited April 23, 2023 by programmerdelphi2k Share this post Link to post
Die Holländer 45 Posted April 24, 2023 Just an idea.. Since the most OpenAI development I see in Python we can consider to use this development environment in combination with Delphi.. Search for "python" in Delphi GetIT package manager. https://www.embarcadero.com/new-tools/python/delphi-4-python Share this post Link to post