Jump to content

misc_bb

Members
  • Content Count

    68
  • Joined

  • Last visited

Community Reputation

7 Neutral

1 Follower

Technical Information

  • Delphi-Version
    Delphi 11 Alexandria

Recent Profile Visitors

The recent visitors block is disabled and is not being shown to other users.

  1. I was able to come out of a simply just using REST components instead of the DelphiOpenAI. Here's what I have so that others can also make use of it if they want to. You can still improve this code but this one works fine. This is utilizing the Function Calling with structured output. function TMappingLabels.MappingLabels: TJSONObject; var fRESTRequest: TRESTRequest; fRESTClient: TRESTClient; jsonTools, jsonPayload: TJdoJsonObject; jsonMessages1, jsonMessages2: TJSONObject; jsonMessages3, JSONResult: TJSONObject; begin try Result := TJSONObject.Create;; jsonPayLoad := TJSONObject.Create; jsonMessages1 := TJSONObject.Create; jsonMessages2 := TJSONObject.Create; jsonMessages3 := TJSONObject.Create; JSONResult := TJSONObject.Create; jsonPayLoad.S['model'] := 'gpt-4-turbo'; jsonPayLoad.I['max_tokens'] := 2000; jsonMessages1 := TJdoJsonObject.Parse('{"role": "system", "content": "You are an AI that maps financial data labels to corresponding account labels based on best matching terms."}') as TJSONObject; jsonMessages2 := TJdoJsonObject.Parse('{"role": "user", "content": "Map the following financial data to the closest matching account labels."}') as TJSONObject; jsonMessages3.S['role'] := 'user'; jsonMessages3.S['content'] := JSONDataLabels['data'].ObjectValue.ToString; jsonTools := TJdoJsonObject.Parse('{"type": "function","function": { "name": "map_financial_labels", ' + '"description": "Map the financial data labels to the most fitting account labels", ' + '"parameters": { "type": "object", "properties": { "mapping": { "type": "array", ' + ' "items": { "type": "object", "properties": { "FinancialLabel": {"type": "string"}, ' + ' "MappedAccountLabel": {"type": "string"} }, "required": ["FinancialLabel", "MappedAccountLabel"] ' + ' } } } } } }') as TJSONObject; jsonPayLoad.A['messages'].AddObject(jsonMessages1); jsonPayLoad.A['messages'].AddObject(jsonMessages2); jsonPayLoad.A['messages'].AddObject(jsonMessages3); jsonPayLoad.A['tools'].AddObject(jsonTools); jsonPayLoad.S['tool_choice'] := 'auto'; //API Call fRESTRequest := TRESTRequest.Create(nil); fRESTRequest.Accept := 'application/json, text/plain; q=0.9, text/html;q=0.8,'; fRESTRequest.AcceptCharset := 'utf-8, *;q=0.8'; fRESTRequest.Client := TRESTClient.Create(fRESTRequest); fRESTRequest.Client.UserAgent := 'Embarcadero RESTClient/1.0'; fRESTRequest.Client.AutoCreateParams := true; fRESTRequest.Client.BaseURL := 'https://api.openai.com/v1/chat/completions'; fRESTRequest.Client.ContentType := 'application/json'; fRESTRequest.SynchronizedEvents := false; fRESTRequest.HandleRedirects := true; fRESTRequest.params.Add; fRESTRequest.Params[0].Name := 'Authorization'; fRESTRequest.Params[0].Value := 'Bearer ' + API_KEY; fRESTRequest.Params[0].Options := [poDoNotEncode]; fRESTRequest.Params[0].Kind := pkHTTPHEADER; fRESTRequest.params.Add; fRESTRequest.Params[1].Name := 'Body'; fRESTRequest.Params[1].Value := jsonPayLoad.ToJSON; fRESTRequest.Params[1].ContentType := 'application/json'; fRESTRequest.Params[1].Kind := pkREQUESTBODY; try fRESTRequest.Method := rmPOST; fRESTRequest.Execute; JSONResult := TJdoJSONObject.Parse(fRESTRequest.Response.Content) as TJSONObject; //here just to extract the JSON object we want to get but you can simply display the result Result := ExtractArgumentsWithJsonDataObjects(JSONResult.ToJSON({Compact:false})); except on E: Exception do Codesite.Send('Error: ' + E.Message); end; finally end; end; You have to get your own API_KEY. The goal for this function is simply to request OpenAI to mapping some labels based on an existing map that we have and send also a list of labels you have to be map against it. It will then return the corresponding map based on the JSON structure as instructed. 🙂
  2. Hi, Just trying to explore further on utilizing OpenAI with Delphi. Any here tried utilizing this https://github.com/HemulGM/DelphiOpenAI? I wanted to explore a little bit more on using Structured outputs but would appreciate some examples. Thank you.
  3. I'm recently facing an issue with a POST API call to my Servermethod function. I understand we can add a code to allow CORS header but I think that was applicable for Webmodule. I don't think this line of code is applicable in my servermethod function: Response.SetCustomHeader('Access-Control-Allow-Origin', '*'); In my case the function is directly called from front-end thru Axios, it works fine when it is using GET but since we want to pass a JSON, we want to apply a POST call. The call is coming from a different subdomain. Works fine within localhost testing and the same domain configuration. Is there a workaround for this to work? Sample code here. Any thoughts on a possible solution would be appreciated. Thank you. axios.post('https://url/staging.dll/datasnap/rest/TServerMethods1/"GetAllCompanies"/', requestBody,{ headers: { 'Content-Type': 'application/json' // Specify JSON format } })
  4. misc_bb

    New Delphi job opportunity

    I'd love to see Delphi opportunities as well. Looking forward to seeing them as I am very much interested. I've worked with Delphi 7 but currently I'm now working with Delphi 11 focusing mostly on using Delphi as backend for a web application with primary task on integrating accounting software such as Xero, Quickbooks and MYOB. Should there be any opportunities in this area, hit me up. 🙂
  5. misc_bb

    Work with PDF documents

    I have been using PDFtk (https://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/) in our Delphi apps to merge documents. I haven't tried splitting but PDFtk has also the splitting function. you may want to give it a try. As for our case, we utilized the command prompt and we just issue a call Shellexecute in our app. Works just fine.
  6. Currently we have a web app with Delphi as a backend. We are planning to incorporate NodeJS as well because we want to take advantage of some JS libraries like a headless browser in our application. I am still not sure if this would work out just fine since I'm currently exploring. I just wanted to ask if someone else have tried this setup before I fully dive into this. Any thoughts or comments are appreciated. Thank you.
  7. misc_bb

    Working with Delphi and Excel

    @corneliusdavid Thank you. I think I'll go for this library. @Dave Nottage I'm currently using OLE but wanted to avoid Excel app from opening. Thank you for the suggestion but I've been thru a lot with OOXML working with docx files, I don't want to go there for the mean time.
  8. misc_bb

    Working with Delphi and Excel

    I think I've read this article as well. Not interested in buying yet but we'll see. Thank you.
  9. misc_bb

    Working with Delphi and Excel

    I know a lot of you might have worked with reading and writing Excel sheets with Delphi. I would like to ask if its possible to read an excel file without opening it?
  10. misc_bb

    Delphi REST with PDF files

    After some trial and error again, was able to figure it out. This integration is with the Datylon API & Delphi REST components which handles a PDF return type. Although free account in Datylon doesn't work with this API integration. If anyone want to implements the API or something similar, the following code can be utilized. You just need to add some error handling. Getauthorization - a function that return the Basic authentication with username and password 64bit encoded, small letter 'a' in 'authorization' is from datylon documentation templateid and datasource - these are datylon parameters that needs be followed based on Datylon documentation JSONStr - this is actually the JSON string that needs to be sent TRY RESTRequest := TRESTRequest.create(nil); RESTRequest.Client := TRESTClient.create(RESTRequest); RESTRequest.SynchronizedEvents := False; RESTRequest.Client.UserAgent := DatylonUserAgent; RESTRequest.Client.FallbackCharsetEncoding := 'raw'; RESTRequest.Client.BaseURL := datylon_BaseURI; RESTRequest.Client.ContentType := 'application/json'; RESTRequest.Client.Params.AddItem('authorization', Getauthorization, TRESTRequestParameterkind.pkHTTPHEADER, [TRESTRequestParameterOption.poDoNotEncode]); RESTRequest.Client.Params.AddItem('x-graph-template-id', templateid, TRESTRequestParameterkind.pkHTTPHEADER, [TRESTRequestParameterOption.poDoNotEncode]); RESTRequest.Client.Params.AddItem('x-graph-datasource-name', datasource, TRESTRequestParameterkind.pkHTTPHEADER, [TRESTRequestParameterOption.poDoNotEncode]); RESTRequest.Body.ClearBody; RestRequest.body.Add(JSONStr, ctAPPLICATION_JSON); // RESTRequest.Resource := 'render'; RESTRequest.Method := rmPOST; RESTRequest.Response := TRESTResponse.Create(RESTRequest); RESTRequest.Accept := 'application/pdf'; RESTRequest.Execute; Codesite.Send('AuthenticationProcess Result: ' + RESTRequest.Response.Content); Result := RESTRequest.Response.RawBytes; finally RESTRequest.Free; end; This code result will return rawbytes which you need to convert to a file. You need the FallbackCharsetEncoding to 'raw' - this I'm not sure but I've read this from here: https://community.embarcadero.com/de/component/easydiscuss/rest-request-error-to-get-pdf-attached-berlin-10-1?Itemid=1 I'm not even sure if it made a difference but I lost track of it which ones is working and which one is not when I was doing my trial and error. 🤣 the ultimate goal is to make it work haha This is for the bytes to file conversion: procedure TfrmMain.SaveBytesToFile(const Data: TBytes; const FileName: string); var Stream: TFileStream; begin Stream := TFileStream.Create(FileName, fmCreate); try if Data <> nil then Stream.WriteBuffer(Data[0], Length(Data)); finally Stream.Free; end; end; //This will call the REST function above RestResultFile := API.PDFProcess(LoadTextFromFile('text1.txt')); //text file here contains the JSON string SaveBytesToFile(RestResultFile, 'test.pdf'); Thank you guys for your ideas. It led me to this solution above. Cheers!
  11. misc_bb

    Delphi REST with PDF files

    In my testing I encounter this result: {"Error":"Content type not recognized"} Should I explicitly specify the return type in code? In Postman, there's no need for that but I'm not sure with Delphi REST. I've dealt with other APIs before but those are all text, json values and Delphi REST works perfectly.
  12. misc_bb

    Delphi REST with PDF files

    Thank you. I guess i'll just have to figure it out how to handle the return PDF file. @Mohammed Nasman Yes, Delphi MVC is very good but I think it's too much for what I require. Thank you.
  13. Hello, I'm currently implementing a tool to handle an API using Delphi REST components. The API we are dealing with returns a PDF file. Can Delphi handle REST this file type? I don't see any file type/content type option in the object inspector. I've made some testing it doesn't seem to replicate what I have in Postman. Anyone have tried using Delphi REST with a PDF file as response? I just want to know otherwise I'll shift to Python. Thanks in advance.
  14. misc_bb

    PDF Library

    Any recommendations for Delphi library for PDF handling? I'm currently working on merging multiple files into 1 pdf file. Fast-reports said it handle this, any thoughts?
  15. misc_bb

    Getting PID of winword.exe based on filename

    Thank you for the idea on this topic. I don't want to go the hard way I can probably do this one at a time. I'll just terminate winword after every documents' final save until the next document opens.
×