Azure OpenAI in React Inline AI Assist

11 Aug 202624 minutes to read

The Inline AI Assist component integrates with Azure OpenAI to enable advanced conversational AI features in your applications. The component acts as a user interface, where user prompts are sent to the Azure OpenAI service via API calls, providing natural language understanding and context-aware responses.

Prerequisites

Before starting, ensure you have the following:

  • Node.js: Version 16 or higher with npm.

  • Azure Account: With access to Azure OpenAI services and a generated API key.

  • Syncfusion Inline AI Assist: Package @syncfusion/ej2-react-interactive-chat installed.

  • Marked Library: For parsing Markdown responses (npm install marked --save).

Set Up the Environment

Follow the Getting Started guide to configure and render the Inline AI Assist component in your application.

Install Dependency

To install the marked library, run npm install marked --save in your project directory to add it as a dependency in your package.json file.

Generate Azure API Key

  1. Log in to the Azure Portal and navigate to your Azure OpenAI resource.

  2. Under resource management, select keys and endpoint to retrieve your API key and endpoint URL.

  3. Note the following values:
    • API key
    • Endpoint
    • API version (must be supported by your resource)
    • Deployment name (for example, gpt-4o-mini)
  4. Store these values securely, as they will be used in your application.

Security Note: Never expose your API key in client-side code for production applications. Use a server-side proxy or environment variables to manage sensitive information securely.

Configure Inline AI Assist with Azure OpenAI

Modify the index.tsx file to integrate the Azure OpenAI with the Inline AI Assist component.

  • Update the following configuration values with Azure OpenAI details:
const azureOpenAIApiKey = 'Your_Azure_OpenAI_API_Key';
const azureOpenAIEndpoint = 'Your_Azure_OpenAI_Endpoint';
const azureOpenAIApiVersion = 'Your_Azure_OpenAI_API_Version';
const azureDeploymentName = 'Your_Deployment_Name';
import { InlineAIAssistComponent } from '@syncfusion/ej2-react-interactive-chat';
import { marked } from 'marked';
import * as React from 'react';
import * as ReactDOM from 'react-dom';

function App() {
    const assistRef = React.useRef(null);
    const editableRef = React.useRef(null);
    const [stopStreaming, setStopStreaming] = React.useState(false);

    // Initialize Azure OpenAI
    const azureOpenAIApiKey = ''; // replace your key
    const azureOpenAIEndpoint = ''; // replace your endpoint
    const azureOpenAIApiVersion = ''; // replace to match your resource
    const azureDeploymentName = ''; // your Azure OpenAI deployment name

    const handleSummarizeBtnClick = () => {
        if (assistRef.current && typeof assistRef.current.showPopup === 'function') {
            assistRef.current.showPopup();
        }
    };

    // Stream the model response to the UI in chunks
    const streamResponse = async (response) => {
        let lastResponse = "";
        const responseUpdateRate = 10;
        let i = 0;
        const responseLength = response.length;
        while (i < responseLength && !stopStreaming) {
            lastResponse += response[i];
            i++;
            if (i % responseUpdateRate === 0 || i === responseLength) {
                const htmlResponse = await marked.parse(lastResponse);
                if (assistRef.current && typeof assistRef.current.addResponse === 'function') {
                    assistRef.current.addResponse(htmlResponse, i === responseLength);
                }
            }
            await new Promise(resolve => setTimeout(resolve, 15));
        }
    };

    // Handle user prompt: call Azure OpenAI Chat Completions
    const handlePromptRequest = async (args) => {
        const url =
            azureOpenAIEndpoint.replace(/\/$/, '') +
            `/openai/deployments/${encodeURIComponent(azureDeploymentName)}/chat/completions` +
            `?api-version=${encodeURIComponent(azureOpenAIApiVersion)}`;

        try {
            setStopStreaming(false);
            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    Authorization: azureOpenAIApiKey,
                },
                body: JSON.stringify({
                    model: 'gpt-4o-mini',
                    messages: [{ role: 'user', content: args.prompt }],
                    max_tokens: 150,
                    stream: false
                }),
            });

            const reply = await response.json();
            const responseText = reply.choices[0].message.content.trim() || 'No response received.';
            await streamResponse(responseText);
        } catch (error) {
            if (assistRef.current && typeof assistRef.current.addResponse === 'function') {
                assistRef.current.addResponse('⚠️ Something went wrong while connecting to the AI service. Please check your API key, Deployment model, endpoint or try again later.', true);
            }
            setStopStreaming(true);
        }
    };

    const handleResponseItemSelect = (args) => {
        if (args.command.label === 'Accept') {
            if (editableRef.current && assistRef.current) {
                const lastResponse = assistRef.current.prompts && assistRef.current.prompts.length > 0
                    ? assistRef.current.prompts[assistRef.current.prompts.length - 1].response
                    : '';
                if (lastResponse) {
                    editableRef.current.innerHTML = '<p>' + lastResponse + '</p>';
                }
            }
            if (assistRef.current && typeof assistRef.current.hidePopup === 'function') {
                assistRef.current.hidePopup();
            }
        } else if (args.command.label === 'Discard') {
            if (assistRef.current && typeof assistRef.current.hidePopup === 'function') {
                assistRef.current.hidePopup();
            }
        }
    };

    const handleToolbarItemClick = (args) => {
        if (args.item.iconCss === 'e-icons e-inline-stop') {
            setStopStreaming(true);
        }
    };

    return (
        <div>
            <button 
                id="summarizeBtn" 
                className="e-btn e-primary" 
                style=
                onClick={handleSummarizeBtnClick}
            >
                Content Summarize
            </button>
            <div 
                id="editableText" 
                contentEditable="true" 
                ref={editableRef}
            >
                <p>Inline AI Assist component provides intelligent text processing capabilities that enhance user productivity. It leverages advanced natural language processing to understand context and deliver precise suggestions. Users can seamlessly integrate AI-powered features into their applications.</p>
                <p>With real-time response streaming and customizable prompts, developers can create interactive experiences. The component supports multiple response modes including inline editing and popup-based interactions.</p>
            </div>
            <InlineAIAssistComponent
                id="defaultInlineAssist"
                ref={assistRef}
                relateTo="#summarizeBtn"
                promptRequest={handlePromptRequest}
                responseSettings=
                inlineToolbarSettings=
                popupWidth="500px"
            />
        </div>
    );
}

ReactDOM.render(<App />, document.getElementById('container'));
import { InlineAIAssistComponent, ResponseItemSelectEventArgs, InlinePromptRequestEventArgs, ToolbarItemClickEventArgs } from '@syncfusion/ej2-react-interactive-chat';
import { marked } from 'marked';
import * as React from 'react';

const App: React.FC = () => {
    const assistRef = React.useRef<InlineAIAssistComponent>(null);
    const editableRef = React.useRef<HTMLDivElement>(null);
    const [stopStreaming, setStopStreaming] = React.useState(false);

    // Initialize Azure OpenAI
    const azureOpenAIApiKey = ''; // replace your key
    const azureOpenAIEndpoint = ''; // replace your endpoint
    const azureOpenAIApiVersion = ''; // replace to match your resource
    const azureDeploymentName = ''; // your Azure OpenAI deployment name

    const handleSummarizeBtnClick = (): void => {
        if (assistRef.current && typeof assistRef.current.showPopup === 'function') {
            assistRef.current.showPopup();
        }
    };

    // Stream the model response to the UI in chunks
    const streamResponse = async (response: string): Promise<void> => {
        let lastResponse = "";
        const responseUpdateRate = 10;
        let i = 0;
        const responseLength = response.length;
        while (i < responseLength && !stopStreaming) {
            lastResponse += response[i];
            i++;
            if (i % responseUpdateRate === 0 || i === responseLength) {
                const htmlResponse = await marked.parse(lastResponse);
                if (assistRef.current && typeof assistRef.current.addResponse === 'function') {
                    assistRef.current.addResponse(htmlResponse, i === responseLength);
                }
            }
            await new Promise(resolve => setTimeout(resolve, 15));
        }
    };

    // Handle user prompt: call Azure OpenAI Chat Completions
    const handlePromptRequest = async (args: InlinePromptRequestEventArgs): Promise<void> => {
        const url =
            azureOpenAIEndpoint.replace(/\/$/, '') +
            `/openai/deployments/${encodeURIComponent(azureDeploymentName)}/chat/completions` +
            `?api-version=${encodeURIComponent(azureOpenAIApiVersion)}`;

        try {
            setStopStreaming(false);
            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    Authorization: azureOpenAIApiKey,
                },
                body: JSON.stringify({
                    model: 'gpt-4o-mini',
                    messages: [{ role: 'user', content: args.prompt }],
                    max_tokens: 150,
                    stream: false
                }),
            });

            const reply = await response.json();
            const responseText = reply.choices[0].message.content.trim() || 'No response received.';
            await streamResponse(responseText);
        } catch (error) {
            if (assistRef.current && typeof assistRef.current.addResponse === 'function') {
                assistRef.current.addResponse('⚠️ Something went wrong while connecting to the AI service. Please check your API key, Deployment model, endpoint or try again later.', true);
            }
            setStopStreaming(true);
        }
    };

    const handleResponseItemSelect = (args: ResponseItemSelectEventArgs): void => {
        if (args.command.label === 'Accept') {
            if (editableRef.current && assistRef.current) {
                const lastResponse = assistRef.current.prompts && assistRef.current.prompts.length > 0
                    ? assistRef.current.prompts[assistRef.current.prompts.length - 1].response
                    : '';
                if (lastResponse) {
                    editableRef.current.innerHTML = '<p>' + lastResponse + '</p>';
                }
            }
            if (assistRef.current && typeof assistRef.current.hidePopup === 'function') {
                assistRef.current.hidePopup();
            }
        } else if (args.command.label === 'Discard') {
            if (assistRef.current && typeof assistRef.current.hidePopup === 'function') {
                assistRef.current.hidePopup();
            }
        }
    };

    const handleToolbarItemClick = (args: ToolbarItemClickEventArgs): void => {
        if (args.item && args.item.iconCss === 'e-icons e-inline-stop') {
            setStopStreaming(true);
        }
    };

    return (
        <div>
            <button 
                id="summarizeBtn" 
                className="e-btn e-primary" 
                style=
                onClick={handleSummarizeBtnClick}
            >
                Content Summarize
            </button>
            <div 
                id="editableText" 
                contentEditable="true" 
                ref={editableRef}
            >
                <p>Inline AI Assist component provides intelligent text processing capabilities that enhance user productivity. It leverages advanced natural language processing to understand context and deliver precise suggestions. Users can seamlessly integrate AI-powered features into their applications.</p>
                <p>With real-time response streaming and customizable prompts, developers can create interactive experiences. The component supports multiple response modes including inline editing and popup-based interactions.</p>
            </div>
            <InlineAIAssistComponent
                id="defaultInlineAssist"
                ref={assistRef}
                relateTo="#summarizeBtn"
                promptRequest={handlePromptRequest}
                responseSettings=
                inlineToolbarSettings=
                popupWidth="500px"
            />
        </div>
    );
};

ReactDOM.render(<App />, document.getElementById('container'));
#loader {
    color: #008cff;
    height: 40px;
    left: 45%;
    position: absolute;
    top: 45%;
    width: 30%;
}

#container {
    margin: 20px auto;
}

#editableText {
    width: 100%;
    min-height: 120px;
    max-height: 300px;
    overflow-y: auto;
    font-size: 16px;
    padding: 12px;
    border-radius: 4px;
    border: 1px solid;
}