Skip to main content
cancel
Showing results for 
Search instead for 
Did you mean: 

Earn a 50% discount on the DP-600 certification exam by completing the Fabric 30 Days to Learn It challenge.

Reply
Anonymous
Not applicable

custom visual using openai api (chatgpt) not working

it could not connect to api on submit button - const response = await axios.post("http://localhost:3000/api/completions"

it gives me error : Refused to connect to 'http://localhost:3000/api/completions' because it violates the following Content Security Policy directive: "default-src https://app.powerbi.com data: blob: 'unsafe-inline' 'unsafe-eval'". Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback.

i have attached code and running another server side node js api and i have created 
handleButtonClick function and try to call but still it gives same error.image.png

 





"use strict";

import powerbi from "powerbi-visuals-api";

import "./../style/visual.less";

import VisualConstructorOptions = powerbi.extensibility.visual.VisualConstructorOptions;
import VisualUpdateOptions = powerbi.extensibility.visual.VisualUpdateOptions;
import IVisual = powerbi.extensibility.visual.IVisual;
import axios from "axios";
import { VisualFormattingSettingsModel } from "./settings";

export class Visual implements IVisual {
    private target: HTMLElement;
    private updateCount: number;
    private newObject: object;
    private newPrompt: string;


    constructor(options: VisualConstructorOptions) {
        // console.log('Visual constructor', options);

        this.target = options.element;
        this.updateCount = 0;
        const containerDiv = document.createElement("div");

        const inputField = document.createElement("input");
        inputField.type = "text";
        inputField.id = "inputField";
        inputField.placeholder = "Enter your input";
        inputField.addEventListener("focus", function () {
            this.value = "";
        });
   
        const submitButton = document.createElement("button");
        submitButton.id = "submitBtn";
        submitButton.type = "submit";
        submitButton.textContent = "Submit";
        submitButton.addEventListener("click",async function () {
            const inputValue = inputField.value;
            const answerDiv = document.getElementById("answer");
            answerDiv.textContent = `You entered: ${inputValue}`;
            const apiKey = "apikey";
            const examplesObject = this.newObject;
            try {
                const response = await axios.post("http://localhost:3000/api/completions", {
                    prompt: `User: ${inputValue}\nOpenAI:`,
                    examples: examplesObject,
                    maxTokens: 50,
                    temperature: 0.7,
                    apiKey: apiKey,
                });
                const generatedAnswer = response.data.choices[0].text;
                answerDiv.textContent = `Answer: ${generatedAnswer}`;
            }
            catch (error) {
                console.error("Error calling ChatGPT API:", error);
            }
        }.bind(this));

        const answerDiv = document.createElement("div");
        answerDiv.id = "answer";

        containerDiv.appendChild(inputField);
        containerDiv.appendChild(submitButton);
        containerDiv.appendChild(answerDiv);

        // Assuming this.target refers to the container where you want to append the elements
        this.target.appendChild(containerDiv);



    }


    public update(options: VisualUpdateOptions) {
        let dataViews = options.dataViews;
        //  console.log("dataviews", dataViews);
        let categorical = dataViews[0].categorical;
        let category = categorical.categories;
        let dataValue = categorical.values
        console.log("category", category);
        console.log("dataValue", dataValue);

        // console.log(categorical.categories[0].source.displayName)
        function createVariable(name, value) {
            const obj = {};
            obj[name] = value;
            return obj;
        }

        const categoryObjects = category.map((category, index) => {

            const createdVariable = createVariable(category.source.displayName, category.values);
            return createdVariable
        })

        const dataObjects = dataValue.map((dataValue, index) => {
            const dataVariable = createVariable(dataValue.source.displayName, dataValue.values)
            return dataVariable
        })

     


        // const categoryObjects = category.map((category, index) => {
        //     return {
        //         category: category.source.displayName,
        //         categoryData :category.values,
        //         dataValue: dataValue[index].values,
        //     };
        // });

        console.log("Category Objects:", categoryObjects);
        console.log("data Objects:", dataObjects);
        const inputValue = (document.getElementById("inputField") as HTMLInputElement).value;
       
        this.newObject=categoryObjects.concat(dataObjects);
       

        // console.log("Generated Answer:", generatedAnswer);

        //     // Display the generated answer in the visual
        //     const answerDiv = document.getElementById("answer");
        //     answerDiv.textContent = `Answer: ${generatedAnswer}`;

    }


    public async handleButtonClick(inputValue: string,apiKeyNew:string,examplesObject:object) : Promise<string>{
       
            const apiKey = apiKeyNew;
            const prompt = `User: ${inputValue}\nOpenAI:`;
            const examples = examplesObject;
                // Add more examples as needed
           
            const maxTokens = 50;

            const response = await axios.post(
                "https://api.openai.com/v1/completions",
                {
                    prompt,
                    "model":"text-davinci-002",
                    examples,
                    max_tokens: maxTokens,
                    temperature: 0.7,
                },
                {
                    headers: {
                        "Content-Type": "application/json",
                        Authorization: `Bearer ${apiKey}`,
                    },
                }
            );

            return response.data.choices[0].text;
         
       
    }



}



0 REPLIES 0

Helpful resources

Announcements
RTI Forums Carousel3

New forum boards available in Real-Time Intelligence.

Ask questions in Eventhouse and KQL, Eventstream, and Reflex.

MayPowerBICarousel

Power BI Monthly Update - May 2024

Check out the May 2024 Power BI update to learn about new features.

LearnSurvey

Fabric certifications survey

Certification feedback opportunity for the community.