Lite LLM in React Inline AI Assist
11 Aug 202624 minutes to read
The Inline AI Assist component can also be integrated with LiteLLM, an open-source proxy that provides a unified, OpenAI-compatible API for multiple LLM providers such as OpenAI and Azure OpenAI.
In this setup:
- Inline AI Assist serves as the user interface for entering prompts.
- Prompts are sent to the LiteLLM proxy, which forwards them to the configured LLM provider.
- The LLM provider processes the prompt and returns a response through LiteLLM.
- This enables natural language understanding and context-aware responses without changing the Inline AI Assist integration logic, as LiteLLM uses the same OpenAI-style API.
Prerequisites
Before starting, ensure you have the following:
-
Node.js: Version 16 or higher with npm installed.
-
OpenAI Account: Access to OpenAI services and a generated API key.
-
Python: Required to run the LiteLLM proxy.
-
Syncfusion Inline AI Assist: Package @syncfusion/ej2-react-interactive-chat installed.
-
Marked Library: For parsing Markdown responses
-
Marked Library: For parsing Markdown responses (
npm install marked --save).
Configure Inline AI Assist with LiteLLM
To integrate LiteLLM with the Syncfusion Inline AI Assist component, update the index.tsx file in your React application. The component will send user prompts to the LiteLLM proxy, which forwards them to the configured LLM provider (e.g., OpenAI or Azure OpenAI) and returns natural language responses.
In the following example:
- The promptRequest event sends the user prompt to the LiteLLM proxy at
/v1/chat/completions. - The proxy uses the model alias defined in
config.yaml(e.g.,openai/gpt-4o-mini) and routes the request to the actual LLM provider. - The response is parsed as Markdown using the
markedlibrary and displayed in the Inline AI Assist component.
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);
// LiteLLM settings
const LITELLM_HOST = 'http://localhost:4000';
const LITELLM_API_KEY = ''; // If your LiteLLM proxy uses a master_key, set this to the same value; otherwise, leave as empty string
const handleSummarizeBtnClick = () => {
if (assistRef.current && typeof assistRef.current.showPopup === 'function') {
assistRef.current.showPopup();
}
};
// Stream AI response 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 LiteLLM proxy
const handlePromptRequest = async (args) => {
const url = `${LITELLM_HOST.replace(/\/$/, '')}/v1/chat/completions`;
try {
setStopStreaming(false);
const res = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...(LITELLM_API_KEY ? { Authorization: `Bearer ${LITELLM_API_KEY}` } : {}),
},
body: JSON.stringify({
model: 'openai/gpt-4o-mini', // Must match model_name in config.yaml
messages: [{ role: 'user', content: args.prompt }],
temperature: 0.7,
max_tokens: 300,
stream: false,
}),
});
if (!res.ok) {
throw new Error(`HTTP ${res.status}`);
}
const reply = await res.json();
const responseText = reply.choices?.[0]?.message?.content?.trim() || 'No response received.';
await streamResponse(responseText);
} catch (error) {
console.error(error);
if (assistRef.current && typeof assistRef.current.addResponse === 'function') {
assistRef.current.addResponse(
'⚠️ Something went wrong while connecting to the AI service. Please check your LiteLLM proxy, model name, or try again later.'
);
}
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);
// LiteLLM settings
const LITELLM_HOST = 'http://localhost:4000';
const LITELLM_API_KEY = ''; // If your LiteLLM proxy uses a master_key, set this to the same value; otherwise, leave as empty string
const handleSummarizeBtnClick = (): void => {
if (assistRef.current && typeof assistRef.current.showPopup === 'function') {
assistRef.current.showPopup();
}
};
// Stream AI response 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 LiteLLM proxy
const handlePromptRequest = async (args: InlinePromptRequestEventArgs): Promise<void> => {
const url = `${LITELLM_HOST.replace(/\/$/, '')}/v1/chat/completions`;
try {
setStopStreaming(false);
const res = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...(LITELLM_API_KEY ? { Authorization: `Bearer ${LITELLM_API_KEY}` } : {}),
},
body: JSON.stringify({
model: 'openai/gpt-4o-mini', // Must match model_name in config.yaml
messages: [{ role: 'user', content: args.prompt }],
temperature: 0.7,
max_tokens: 300,
stream: false,
}),
});
if (!res.ok) {
throw new Error(`HTTP ${res.status}`);
}
const reply = await res.json();
const responseText = reply.choices?.[0]?.message?.content?.trim() || 'No response received.';
await streamResponse(responseText);
} catch (error) {
console.error(error);
if (assistRef.current && typeof assistRef.current.addResponse === 'function') {
assistRef.current.addResponse(
'⚠️ Something went wrong while connecting to the AI service. Please check your LiteLLM proxy, model name, or try again later.'
);
}
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;
}Run and test
Start the proxy:
Navigate to your project folder and run the following command to start the proxy:
pip install "litellm[proxy]"
litellm --config "./config.yaml" --port 4000 --host 0.0.0.0Start the frontend:
In a separate terminal window, navigate to your project folder, start the React application
npm startOpen your app to interact with the Inline AI Assist component integrated with LiteLLM.
Troubleshooting
-
401 Unauthorized: Verify yourAPI_KEYand model deployment name. -
Model not found: Ensure model matchesmodel_nameinconfig.yaml. -
CORS issues: Configurerouter_settings.cors_allow_originsproperly.