AiClientOptions.cs
//
// This code is part of Document Solutions for PDF demos.
// Copyright (c) MESCIUS inc. All rights reserved.
//
using System;
using System.IO;
using System.Drawing;
using GrapeCity.Documents.Pdf;
using GrapeCity.Documents.Text;
using GrapeCity.Documents.Pdf.AI;
using System.Threading.Tasks;
using OpenAI;
using System.ClientModel;
using DsPdfWeb.Demos.Common;

namespace DsPdfWeb.Demos
{
    // This sample demonstrates how to customize the OpenAIDocumentAssistant
    // by explicitly specifying options such as endpoint, model, and others.
    //
    // It then calls the GetAbstract method to generate an abstract of the PDF,
    // similar to the AiGetAbstract sample.
    //
    // To run this sample locally, set your OpenAI credentials
    // using Util.OpenAIToken.
    public class AiClientOptions
    {
        public int CreatePDF(Stream stream)
        {
            var doc = new GcPdfDocument();
            using var fs = File.OpenRead(Path.Combine("Resources", "PDFs", "Wetlands.pdf"));
            doc.Load(fs);
            try
            {
                // Create and configure OpenAIClient explicitly:
                OpenAIClient openAIClient = new(
                    credential: new ApiKeyCredential(Util.OpenAIToken),
                    options: new OpenAIClientOptions()
                    {
                        Endpoint = new Uri(@"https://api.openai.com/v1"), // Default endpoint, specifying for example only
                    }
                );
                // Initialize OpenAIDocumentAssistant with the configured OpenAIClient, customize it as needed:
                OpenAIDocumentAssistant a = new(openAIClient)
                {
                    Model = "gpt-4-turbo",
                };
                // Get the abstract of the PDF:
                var task = a.GetAbstract(doc);
                task.Wait();
                var page = doc.Pages.Insert(0);
                Util.AddNote("Abstract generated using DsPdf AI Assistant\n\n" + task.Result, page);
            }
            catch (Exception ex)
            {
                // Make sure you have assigned your OpenAI API key to Util.OpenAIToken:
                Util.CreatePdfError(doc, ex.Message);
            }
            doc.Save(stream);
            return doc.Pages.Count;
        }
    }
}