- Notifications
You must be signed in to change notification settings - Fork254
[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
Open
iamfaran wants to merge32 commits intolowcoder-org:feat/assistantChoose a base branch fromiamfaran:feat/chat-component
base:feat/assistant
Could not load branches
Branch not found:{{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline, and old review comments may become outdated.
Uh oh!
There was an error while loading.Please reload this page.
Open
Changes fromall commits
Commits
Show all changes
32 commits Select commitHold shift + click to select a range
158de18
[feat] replace mock data with query
iamfaranfacd5e0
Merge branch 'feat/assistant' of github.com:lowcoder-org/lowcoder int…
iamfaranc3beba5
[Feat]: make chat component flexible
iamfaran6376c83
setup sse http query
iamfaranf8bf78d
fix linter errors
iamfaran0ed0fc7
setup http streaming with dummy data
iamfaran8542399
setup frontend for ssehttpquery
iamfaran2925949
chat component refactor
iamfaran9d67db7
Created test case for the ApplicationApiService.
thomas37-starf9128ea
Created test case for the ApplicationEndpointsTest.
thomas37-star1a587df
fix workspaces updated myorg endpoint
iamfaran53fb65d
fix orglist active org icon
iamfaran56c1c55
Updated CustomSelector UI
kamalqureshid2f2a4c
Adding Tooltip to Multiselect custom tags
kamalqureshi1de8ae6
add unique storage / expose convo history
iamfaran34c6351
Merge pull request #1859 from iamfaran/fix/myorg-endpoint
raheeliftikhar5e6a450d
Merge pull request #1858 from kamalqureshi/publish_app_groups_members
raheeliftikhar5d6ff092
Merge pull request #1860 from kamalqureshi/custom_tag_multiselect
raheeliftikhar5cc2e8d5
Created test case for the ApplicationHistorySnapshotEndpoints.
thomas37-starab233a5
Created test case for the ApplicationHistorySnapshotEndpoints.
thomas37-star6560014
fixed text input glitch
raheeliftikhar5bf68435
Adding function Calls to Timer Component
6c28494
add event listeners for the chat component
iamfaranf60c3e6
Created test case for the AuthenticationEndpoints.
thomas37-starbff7af5
add system prompt and improve edit UI
iamfaran955650d
Merge branch 'dev' of github.com:lowcoder-org/lowcoder into feat/chat…
iamfaranc2f66db
add docs button in chat component
iamfaran70b8640
fix no threads infinite re render
iamfarandbfda30
fix table name for better queries
iamfarane164f09
add custom loader
iamfaran8aa7438
add translations for the chat component
iamfaran948ac7d
remove console logs
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
9 changes: 5 additions & 4 deletionsclient/packages/lowcoder-design/src/components/customSelect.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
11 changes: 7 additions & 4 deletionsclient/packages/lowcoder/src/api/userApi.ts
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
2 changes: 1 addition & 1 deletionclient/packages/lowcoder/src/components/PermissionDialog/Permission.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
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.