- Notifications
You must be signed in to change notification settings - Fork278
[Feat] AI Chat Component#1850
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Merged
raheeliftikhar5 merged 17 commits intolowcoder-org:feat/assistantfromiamfaran:feat/chat-componentJul 22, 2025
Uh oh!
There was an error while loading.Please reload this page.
Merged
Changes fromall commits
Commits
Show all changes
17 commits Select commitHold shift + click to select a range
4585d15
[feat] replace mock data with query
iamfaran75e635a
[Feat]: make chat component flexible
iamfaran56e5247
setup sse http query
iamfaran4664b5b
fix linter errors
iamfaran188f9cb
setup http streaming with dummy data
iamfaran7b68581
setup frontend for ssehttpquery
iamfarancf0b99c
chat component refactor
iamfarana349af4
add unique storage / expose convo history
iamfaran5d88dbe
add event listeners for the chat component
iamfaranac38c66
add system prompt and improve edit UI
iamfaranb2dcf3f
add docs button in chat component
iamfaran35b0614
fix no threads infinite re render
iamfaranb2d9d11
fix table name for better queries
iamfaranaa40585
add custom loader
iamfaranb1bc01a
add translations for the chat component
iamfaran68b2802
remove console logs
iamfaran4f9fbba
add file attachments components
iamfaranFile filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
2 changes: 2 additions & 0 deletionsclient/packages/lowcoder/package.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
12 changes: 11 additions & 1 deletionclient/packages/lowcoder/src/components/ResCreatePanel.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
302 changes: 257 additions & 45 deletionsclient/packages/lowcoder/src/comps/comps/chatComp/chatComp.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,46 +1,258 @@ | ||
// client/packages/lowcoder/src/comps/comps/chatComp/chatComp.tsx | ||
import { UICompBuilder } from "comps/generators"; | ||
import { NameConfig, withExposingConfigs } from "comps/generators/withExposing"; | ||
import { StringControl } from "comps/controls/codeControl"; | ||
import { arrayObjectExposingStateControl, stringExposingStateControl } from "comps/controls/codeStateControl"; | ||
import { withDefault } from "comps/generators"; | ||
import { BoolControl } from "comps/controls/boolControl"; | ||
import { dropdownControl } from "comps/controls/dropdownControl"; | ||
import QuerySelectControl from "comps/controls/querySelectControl"; | ||
import { eventHandlerControl, EventConfigType } from "comps/controls/eventHandlerControl"; | ||
import { ChatCore } from "./components/ChatCore"; | ||
import { ChatPropertyView } from "./chatPropertyView"; | ||
import { createChatStorage } from "./utils/storageFactory"; | ||
import { QueryHandler, createMessageHandler } from "./handlers/messageHandlers"; | ||
import { useMemo, useRef, useEffect } from "react"; | ||
import { changeChildAction } from "lowcoder-core"; | ||
import { ChatMessage } from "./types/chatTypes"; | ||
import { trans } from "i18n"; | ||
import "@assistant-ui/styles/index.css"; | ||
import "@assistant-ui/styles/markdown.css"; | ||
// ============================================================================ | ||
// CHAT-SPECIFIC EVENTS | ||
// ============================================================================ | ||
export const componentLoadEvent: EventConfigType = { | ||
label: trans("chat.componentLoad"), | ||
value: "componentLoad", | ||
description: trans("chat.componentLoadDesc"), | ||
}; | ||
export const messageSentEvent: EventConfigType = { | ||
label: trans("chat.messageSent"), | ||
value: "messageSent", | ||
description: trans("chat.messageSentDesc"), | ||
}; | ||
export const messageReceivedEvent: EventConfigType = { | ||
label: trans("chat.messageReceived"), | ||
value: "messageReceived", | ||
description: trans("chat.messageReceivedDesc"), | ||
}; | ||
export const threadCreatedEvent: EventConfigType = { | ||
label: trans("chat.threadCreated"), | ||
value: "threadCreated", | ||
description: trans("chat.threadCreatedDesc"), | ||
}; | ||
export const threadUpdatedEvent: EventConfigType = { | ||
label: trans("chat.threadUpdated"), | ||
value: "threadUpdated", | ||
description: trans("chat.threadUpdatedDesc"), | ||
}; | ||
export const threadDeletedEvent: EventConfigType = { | ||
label: trans("chat.threadDeleted"), | ||
value: "threadDeleted", | ||
description: trans("chat.threadDeletedDesc"), | ||
}; | ||
const ChatEventOptions = [ | ||
componentLoadEvent, | ||
messageSentEvent, | ||
messageReceivedEvent, | ||
threadCreatedEvent, | ||
threadUpdatedEvent, | ||
threadDeletedEvent, | ||
] as const; | ||
export const ChatEventHandlerControl = eventHandlerControl(ChatEventOptions); | ||
// ============================================================================ | ||
// SIMPLIFIED CHILDREN MAP - WITH EVENT HANDLERS | ||
// ============================================================================ | ||
export function addSystemPromptToHistory( | ||
conversationHistory: ChatMessage[], | ||
systemPrompt: string | ||
): Array<{ role: string; content: string; timestamp: number }> { | ||
// Format conversation history for use in queries | ||
const formattedHistory = conversationHistory.map(msg => ({ | ||
role: msg.role, | ||
content: msg.text, | ||
timestamp: msg.timestamp | ||
})); | ||
// Create system message (always exists since we have default) | ||
const systemMessage = [{ | ||
role: "system" as const, | ||
content: systemPrompt, | ||
timestamp: Date.now() - 1000000 // Ensure it's always first chronologically | ||
}]; | ||
// Return complete history with system prompt prepended | ||
return [...systemMessage, ...formattedHistory]; | ||
} | ||
function generateUniqueTableName(): string { | ||
return `chat${Math.floor(1000 + Math.random() * 9000)}`; | ||
} | ||
const ModelTypeOptions = [ | ||
{ label: trans("chat.handlerTypeQuery"), value: "query" }, | ||
{ label: trans("chat.handlerTypeN8N"), value: "n8n" }, | ||
] as const; | ||
export const chatChildrenMap = { | ||
// Storage | ||
// Storage (add the hidden property here) | ||
_internalDbName: withDefault(StringControl, ""), | ||
// Message Handler Configuration | ||
handlerType: dropdownControl(ModelTypeOptions, "query"), | ||
chatQuery: QuerySelectControl, // Only used for "query" type | ||
modelHost: withDefault(StringControl, ""), // Only used for "n8n" type | ||
systemPrompt: withDefault(StringControl, trans("chat.defaultSystemPrompt")), | ||
streaming: BoolControl.DEFAULT_TRUE, | ||
// UI Configuration | ||
placeholder: withDefault(StringControl, trans("chat.defaultPlaceholder")), | ||
// Database Information (read-only) | ||
databaseName: withDefault(StringControl, ""), | ||
// Event Handlers | ||
onEvent: ChatEventHandlerControl, | ||
// Exposed Variables (not shown in Property View) | ||
currentMessage: stringExposingStateControl("currentMessage", ""), | ||
conversationHistory: stringExposingStateControl("conversationHistory", "[]"), | ||
}; | ||
// ============================================================================ | ||
// CLEAN CHATCOMP - USES NEW ARCHITECTURE | ||
// ============================================================================ | ||
const ChatTmpComp = new UICompBuilder( | ||
chatChildrenMap, | ||
(props, dispatch) => { | ||
const uniqueTableName = useRef<string>(); | ||
// Generate unique table name once (with persistence) | ||
if (!uniqueTableName.current) { | ||
// Use persisted name if exists, otherwise generate new one | ||
uniqueTableName.current = props._internalDbName || generateUniqueTableName(); | ||
// Save the name for future refreshes | ||
if (!props._internalDbName) { | ||
dispatch(changeChildAction("_internalDbName", uniqueTableName.current, false)); | ||
} | ||
// Update the database name in the props for display | ||
const dbName = `ChatDB_${uniqueTableName.current}`; | ||
dispatch(changeChildAction("databaseName", dbName, false)); | ||
} | ||
// Create storage with unique table name | ||
const storage = useMemo(() => | ||
createChatStorage(uniqueTableName.current!), | ||
[] | ||
); | ||
// Create message handler based on type | ||
const messageHandler = useMemo(() => { | ||
const handlerType = props.handlerType; | ||
if (handlerType === "query") { | ||
return new QueryHandler({ | ||
chatQuery: props.chatQuery.value, | ||
dispatch, | ||
streaming: props.streaming, | ||
}); | ||
} else if (handlerType === "n8n") { | ||
return createMessageHandler("n8n", { | ||
modelHost: props.modelHost, | ||
systemPrompt: props.systemPrompt, | ||
streaming: props.streaming | ||
}); | ||
} else { | ||
// Fallback to mock handler | ||
return createMessageHandler("mock", { | ||
chatQuery: props.chatQuery.value, | ||
dispatch, | ||
streaming: props.streaming | ||
}); | ||
} | ||
}, [ | ||
props.handlerType, | ||
props.chatQuery, | ||
props.modelHost, | ||
props.systemPrompt, | ||
props.streaming, | ||
dispatch, | ||
]); | ||
// Handle message updates for exposed variable | ||
const handleMessageUpdate = (message: string) => { | ||
dispatch(changeChildAction("currentMessage", message, false)); | ||
// Trigger messageSent event | ||
props.onEvent("messageSent"); | ||
}; | ||
// Handle conversation history updates for exposed variable | ||
// Handle conversation history updates for exposed variable | ||
const handleConversationUpdate = (conversationHistory: any[]) => { | ||
// Use utility function to create complete history with system prompt | ||
const historyWithSystemPrompt = addSystemPromptToHistory( | ||
conversationHistory, | ||
props.systemPrompt | ||
); | ||
// Expose the complete history (with system prompt) for use in queries | ||
dispatch(changeChildAction("conversationHistory", JSON.stringify(historyWithSystemPrompt), false)); | ||
// Trigger messageReceived event when bot responds | ||
const lastMessage = conversationHistory[conversationHistory.length - 1]; | ||
if (lastMessage && lastMessage.role === 'assistant') { | ||
props.onEvent("messageReceived"); | ||
} | ||
}; | ||
// Cleanup on unmount | ||
useEffect(() => { | ||
return () => { | ||
const tableName = uniqueTableName.current; | ||
if (tableName) { | ||
storage.cleanup(); | ||
} | ||
}; | ||
}, []); | ||
return ( | ||
<ChatCore | ||
storage={storage} | ||
messageHandler={messageHandler} | ||
placeholder={props.placeholder} | ||
onMessageUpdate={handleMessageUpdate} | ||
onConversationUpdate={handleConversationUpdate} | ||
onEvent={props.onEvent} | ||
/> | ||
); | ||
} | ||
) | ||
.setPropertyViewFn((children) => <ChatPropertyView children={children} />) | ||
.build(); | ||
// ============================================================================ | ||
// EXPORT WITH EXPOSED VARIABLES | ||
// ============================================================================ | ||
export const ChatComp = withExposingConfigs(ChatTmpComp, [ | ||
new NameConfig("currentMessage", "Current user message"), | ||
new NameConfig("conversationHistory", "Full conversation history as JSON array (includes system prompt for API calls)"), | ||
new NameConfig("databaseName", "Database name for SQL queries (ChatDB_<componentName>)"), | ||
]); |
Oops, something went wrong.
Uh oh!
There was an error while loading.Please reload this page.
Oops, something went wrong.
Uh oh!
There was an error while loading.Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.