feat(web): Agent add ai prompt

This commit is contained in:
zhaoying
2025-12-25 16:18:26 +08:00
parent bfed5404b4
commit 29ffd0d810
8 changed files with 348 additions and 53 deletions

12
web/src/api/prompt.ts Normal file
View File

@@ -0,0 +1,12 @@
import { request } from '@/utils/request'
import type { AiPromptForm } from '@/views/ApplicationConfig/types'
export const createPromptSessions = () => {
return request.post(`/prompt/sessions`)
}
export const getPrompt = (session_id: string) => {
return request.get(`/prompt/sessions/${session_id}`)
}
export const updatePromptMessages = (session_id: string, data: AiPromptForm) => {
return request.post(`/prompt/sessions/${session_id}/messages`, data)
}

View File

@@ -990,6 +990,15 @@ export const en = {
apiKeyDeleteContent: 'Once deleted, it cannot be recovered, and applications using this Key will not be able to access the API',
currentValue: 'Current Value',
qpsLimitUnit: 'times/second',
addVariable: 'Insert Variable',
defineVariableName: 'Custom Variable Name',
defineVariableNamePlaceholder: 'Enter variable name, e.g.: user_name',
defineVariableNameExtra: 'Format: Variable name will be automatically wrapped with {{}}',
you: 'You',
ai: 'AI Assistant',
promptChatPlaceholder: 'Describe the prompt you need, e.g.: I need a customer service assistant',
promptChatEmpty: 'No conversation content available',
promptEmpty: 'Describe your use case on the left, and the orchestration preview will be displayed here.',
},
userMemory: {
userMemory: 'User Memory',

View File

@@ -505,6 +505,15 @@ export const zh = {
apiKeyDeleteContent: '删除后将无法恢复使用此Key的应用将无法访问 API',
currentValue: '当前值',
qpsLimitUnit: '次/秒',
addVariable: '插入变量',
defineVariableName: '自定义变量名',
defineVariableNamePlaceholder: '输入变量名例如user_name',
defineVariableNameExtra: '格式:变量名会自动添加{{}}包裹',
you: '你',
ai: 'AI 助手',
promptChatPlaceholder: '描述你需要的提示词,例如:我需要一个客服助手',
promptChatEmpty: '目前没有对话内容',
promptEmpty: '在左侧描述您的用例,编排预览将在此处显示。',
},
// 角色管理相关翻译
role: {

View File

@@ -17,6 +17,7 @@ import type {
KnowledgeConfig,
Variable,
MemoryConfig,
AiPromptModalRef
} from './types'
import type { Model } from '@/views/ModelManagement/types'
import { getModelList } from '@/api/models';
@@ -27,19 +28,19 @@ import { getApplicationConfig } from '@/api/application'
import { getKnowledgeBaseList } from '@/api/knowledgeBase'
import { memoryConfigListUrl } from '@/api/memory'
import CustomSelect from '@/components/CustomSelect'
import aiPrompt from '@/assets/images/application/aiPrompt.png'
import AiPromptModal from './components/AiPromptModal'
const DescWrapper: FC<{desc: string, className?: string}> = ({desc, className}) => {
return (
<div className={clsx(className, "rb:text-[12px] rb:text-[#5B6167] rb:font-regular rb:leading-[16px] ")}>
<div className={clsx(className, "rb:text-[12px] rb:text-[#5B6167] rb:font-regular rb:leading-4 ")}>
{desc}
</div>
)
}
const LabelWrapper: FC<{title: string, className?: string; children?: ReactNode}> = ({title, className, children}) => {
return (
<div className={clsx(className, "rb:text-[14px] rb:font-medium rb:leading-[20px]")}>
<div className={clsx(className, "rb:text-[14px] rb:font-medium rb:leading-5")}>
{title}
{children}
</div>
@@ -50,12 +51,12 @@ const SwitchWrapper: FC<{ title: string, desc: string, name: string }> = ({ titl
return (
<div className="rb:flex rb:items-center rb:justify-between">
<LabelWrapper title={t(`application.${title}`)}>
<DescWrapper desc={t(`application.${desc}`)} className="rb:mt-[8px]" />
<DescWrapper desc={t(`application.${desc}`)} className="rb:mt-2" />
</LabelWrapper>
<Form.Item
name={name}
valuePropName="checked"
className="rb:mb-[0px]!"
className="rb:mb-0!"
>
<Switch />
</Form.Item>
@@ -66,11 +67,11 @@ const SelectWrapper: FC<{ title: string, desc: string, name: string, url: string
const { t } = useTranslation();
return (
<>
<LabelWrapper title={t(`application.${title}`)} className="rb:mb-[8px]">
<LabelWrapper title={t(`application.${title}`)} className="rb:mb-2">
</LabelWrapper>
<Form.Item
name={name}
className="rb:mb-[0px]!"
className="rb:mb-0!"
>
<CustomSelect
url={url}
@@ -79,7 +80,7 @@ const SelectWrapper: FC<{ title: string, desc: string, name: string, url: string
labelKey="config_name"
/>
</Form.Item>
<DescWrapper desc={t(`application.${desc}`)} className="rb:mt-[8px]" />
<DescWrapper desc={t(`application.${desc}`)} className="rb:mt-2" />
</>
)
}
@@ -336,15 +337,22 @@ const Agent = forwardRef<AgentRef>((_props, ref) => {
handleSave
}))
const aiPromptModalRef = useRef<AiPromptModalRef>(null)
const handlePrompt = () => {
aiPromptModalRef.current?.handleOpen()
}
const updatePrompt = (value: string) => {
form.setFieldValue('system_prompt', value)
}
return (
<>
{loading && <Spin fullscreen></Spin>}
<Row className="rb:h-[calc(100vh-64px)]">
<Col span={12} className="rb:h-full rb:overflow-x-auto rb:border-r rb:border-[#DFE4ED] rb:p-[20px_16px_24px_16px]">
<div className="rb:flex rb:items-center rb:justify-end rb:mb-[20px]">
<div className="rb:flex rb:items-center rb:justify-end rb:mb-5">
<Space size={10}>
<Button onClick={handleModelConfig} className="rb:group">
{defaultModel?.name ? <div className="rb:w-[16px] rb:h-[16px] rb:bg-[url('@/assets/images/application/model.svg')] rb:group-hover:bg-[url('@/assets/images/application/model_hover.svg')]"></div> : null}
{defaultModel?.name ? <div className="rb:w-4 rb:h-4 rb:bg-[url('@/assets/images/application/model.svg')] rb:group-hover:bg-[url('@/assets/images/application/model_hover.svg')]"></div> : null}
{defaultModel?.name || t('application.chooseModel')}
</Button>
<Button type="primary" onClick={() => handleSave()}>
@@ -356,14 +364,18 @@ const Agent = forwardRef<AgentRef>((_props, ref) => {
<Space size={16} direction="vertical" style={{ width: '100%' }}>
{/* 提示词 */}
<Card title={t('application.promptConfiguration')}>
<div className="rb:flex rb:items-center rb:justify-between rb:mb-[11px]">
<div className="rb:font-medium rb:leading-[20px]">
<div className="rb:flex rb:items-center rb:justify-between rb:mb-2.75">
<div className="rb:font-medium rb:leading-5">
{t('application.configuration')}
<span className="rb:font-regular rb:text-[12px] rb:text-[#5B6167]"> ({t('application.configurationDesc')})</span>
</div>
<Button style={{ padding: '0 8px', height: '24px' }} onClick={handlePrompt}>
<img src={aiPrompt} className="rb:size-5" />
{t('application.aiPrompt')}
</Button>
</div>
<Form.Item name="system_prompt" className="rb:mb-[0]!">
<Form.Item name="system_prompt" className="rb:mb-0!">
<Input.TextArea
placeholder={t('application.promptPlaceholder')}
styles={{
@@ -412,14 +424,14 @@ const Agent = forwardRef<AgentRef>((_props, ref) => {
</Form>
</Col>
<Col span={12} className="rb:h-full rb:overflow-x-hidden rb:p-[20px_16px_24px_16px]">
<div className="rb:flex rb:items-center rb:justify-between rb:mb-[20px]">
<div className="rb:flex rb:items-center rb:justify-between rb:mb-5">
{t('application.debuggingAndPreview')}
<Space size={10}>
<Button type="primary" ghost onClick={handleAddModel}>
+{t('application.addModel')}
</Button>
<div className="rb:w-[32px] rb:h-[32px] rb:cursor-pointer rb:bg-[url('@/assets/images/application/clean.svg')]" onClick={handleClearDebugging}></div>
<div className="rb:w-8 rb:h-8 rb:cursor-pointer rb:bg-[url('@/assets/images/application/clean.svg')]" onClick={handleClearDebugging}></div>
</Space>
</div>
<RbCard height="calc(100vh - 160px)" bodyClassName="rb:p-[0]! rb:h-full rb:overflow-hidden">
@@ -440,6 +452,11 @@ const Agent = forwardRef<AgentRef>((_props, ref) => {
ref={modelConfigModalRef}
refresh={refresh}
/>
<AiPromptModal
ref={aiPromptModalRef}
defaultModel={defaultModel}
refresh={updatePrompt}
/>
</>
);
});

View File

@@ -1,43 +1,136 @@
import { forwardRef, useImperativeHandle, useState } from 'react';
import { Row, Col, Space, Button } from 'antd';
import { forwardRef, useImperativeHandle, useState, useRef } from 'react';
import { Button, Form, Input, App, Row, Col } from 'antd';
import { useTranslation } from 'react-i18next';
import clsx from 'clsx'
import copy from 'copy-to-clipboard';
import type { AiPromptModalRef } from '../types'
// import { request } from '@/utils/request'
import { updatePromptMessages, createPromptSessions } from '@/api/prompt'
import { getModelListUrl } from '@/api/models'
import type { AiPromptModalRef, AiPromptVariableModalRef, AiPromptForm } from '../types'
import RbModal from '@/components/RbModal'
import Markdown from '@/components/Markdown';
import type { Model } from '@/views/ModelManagement/types'
import ChatContent from '@/components/Chat/ChatContent'
import Empty from '@/components/Empty'
import ChatSendIcon from '@/assets/images/application/chatSend.svg'
import ConversationEmptyIcon from '@/assets/images/conversation/conversationEmpty.svg'
import type { ChatItem } from '@/components/Chat/types'
import CustomSelect from '@/components/CustomSelect'
import AiPromptVariableModal from './AiPromptVariableModal'
interface AiPromptModalProps {
refresh: () => void;
refresh: (value: string) => void;
defaultModel: Model | null;
}
const AiPromptModal = forwardRef<AiPromptModalRef, AiPromptModalProps>(({
// refresh
refresh,
defaultModel,
}, ref) => {
const { t } = useTranslation();
const { message } = App.useApp()
const [visible, setVisible] = useState(false);
const [loading, setLoading] = useState(false)
const [content, setContent] = useState('');
const [form] = Form.useForm<AiPromptForm>()
const [chatList, setChatList] = useState<ChatItem[]>([])
const [variables, setVariables] = useState<string[]>([])
const [promptSession, setPromptSession] = useState<string | null>(null)
const aiPromptVariableModalRef = useRef<AiPromptVariableModalRef>(null)
const currentPromptRef = useRef<any>(null)
const values = Form.useWatch([], form)
// 封装取消方法,添加关闭弹窗逻辑
const handleClose = () => {
setVisible(false);
setLoading(false)
setChatList([])
setVariables([])
form.setFieldsValue({
message: undefined,
current_prompt: undefined,
})
};
const handleOpen = () => {
setVisible(true);
createPromptSessions()
.then(res => {
const response = res as { id: string }
setPromptSession(response.id)
if (!values.model_id && defaultModel?.id) {
form.setFieldValue('model_id', defaultModel?.id)
}
setVisible(true);
})
};
// 封装保存方法,添加提交逻辑
// const handleSave = () => {
// }
const handleSend = () => {
if (!promptSession) return
if (!values.model_id) {
message.warning(t('common.selectPlaceholder', { title: t('application.model') }))
return
}
if (!values.message) {
message.warning(t('application.promptChatPlaceholder'))
return
}
const messageContent = values.message
setLoading(true)
setChatList(prev => {
return [...prev, { role: 'user', content: messageContent}]
})
form.setFieldsValue({ message: undefined })
updatePromptMessages(promptSession, values)
.then(res => {
const response = res as { prompt: string; desc: string; variables: string[] }
form.setFieldsValue({ current_prompt: response.prompt })
setChatList(prev => {
return [...prev, { role: 'assistant', content: response.desc }]
})
setVariables(response.variables)
})
.finally(() => {
setLoading(false)
})
}
const handleCopy = () => {
if (!values.current_prompt || values?.current_prompt?.trim() === '') return
copy(values.current_prompt)
message.success(t('common.copySuccess'))
}
const handleAdd = () => {
aiPromptVariableModalRef.current?.handleOpen()
}
const handleVariableApply = (value: string) => {
const textArea = currentPromptRef.current?.resizableTextArea?.textArea
if (textArea) {
const cursorPosition = textArea.selectionStart
const currentValue = values.current_prompt || ''
const newValue = currentValue.slice(0, cursorPosition) + value + currentValue.slice(cursorPosition)
form.setFieldValue('current_prompt', newValue)
// 设置新的光标位置
setTimeout(() => {
textArea.focus()
textArea.setSelectionRange(cursorPosition + value.length, cursorPosition + value.length)
}, 0)
} else {
form.setFieldValue('current_prompt', (values.current_prompt || '') + value)
}
}
const handleApply = () => {
if (!values.current_prompt) {
return
}
refresh(values.current_prompt)
handleClose()
}
// 暴露给父组件的方法
useImperativeHandle(ref, () => ({
handleOpen,
}));
console.log(values)
return (
<RbModal
title={t('application.AIPromptAssistant')}
@@ -46,34 +139,73 @@ const AiPromptModal = forwardRef<AiPromptModalRef, AiPromptModalProps>(({
footer={null}
width={1000}
>
<Row className="rb:rounded-[12px] rb:border rb:border-[#DFE4ED]">
<Col span={12} className="rb:border-r rb:border-[#DFE4ED]">
<div className="rb:p-[12px_17px] rb:border-b rb:border-[#DFE4ED]">{t('application.generatedPrompt')}</div>
<div className="rb:h-[200px] rb:p-[16px]">
<div className="rb:bg-[#F0F3F8] rb:h-full rb:w-full">
<Markdown
content={content}
<Form form={form}>
<div className="rb:grid rb:grid-cols-2 rb:border-t rb:border-t-[#EBEBEB]">
<div className="rb:border-r rb:border-r-[#EBEBEB] rb:pr-6 rb:pt-3">
<Form.Item
label={t('application.model')}
name="model_id"
rules={[{ required: true, message: t('common.pleaseSelect') }]}
>
<CustomSelect
url={getModelListUrl}
params={{ type: 'llm,chat', pagesize: 100 }}
valueKey="id"
labelKey="name"
hasAll={false}
style={{ width: '100%' }}
/>
</Form.Item>
<ChatContent
classNames="rb:h-100.5 rb:px-[16px] rb:py-[20px] rb:bg-[#FBFDFF] rb:border rb:border-[#DFE4ED] rb:rounded-[8px]"
contentClassNames="rb:max-w-[260px]!"
empty={<Empty url={ConversationEmptyIcon} title={t('application.promptChatEmpty')} isNeedSubTitle={false} size={[240, 200]} className="rb:h-full" />}
data={chatList || []}
streamLoading={false}
labelPosition="top"
labelFormat={(item) => item.role === 'user' ? t('application.you') : t('application.ai')}
/>
<div className="rb:flex rb:items-center rb:gap-2.5 rb:py-4">
<Form.Item name="message" className="rb:mb-0!" style={{ width: 'calc(100% - 54px)' }}>
<Input
className="rb:h-11 rb:shadow-[0px_2px_8px_0px_rgba(33,35,50,0.1)]"
placeholder={t('application.promptChatPlaceholder')}
onPressEnter={handleSend}
/>
</Form.Item>
<img src={ChatSendIcon} className={clsx("rb:w-11 rb:h-11 rb:cursor-pointer", {
'rb:opacity-50': loading,
})} onClick={handleSend} />
</div>
</div>
</Col>
<Col span={12}>
<div className="rb:p-[12px_17px] rb:border-b rb:border-[#DFE4ED]">{t('application.conversationOptimizationPrompt')}</div>
<div className="rb:h-[200px] rb:p-[16px]">
<div className="rb:bg-[#F0F3F8] rb:h-full rb:w-full">
<div className="rb:pl-6 rb:pt-3">
<Row>
<Col span={12}>
<Form.Item label={t('application.conversationOptimizationPrompt')}></Form.Item>
</Col>
<Col span={12} className="rb:text-right">
<Button onClick={handleAdd}>+ {t('application.addVariable')}</Button>
</Col>
</Row>
<Form.Item name="current_prompt">
<Input.TextArea ref={currentPromptRef} className="rb:bg-[#FBFDFF]! rb:h-100.5!" />
</Form.Item>
<div className="rb:grid rb:grid-cols-2 rb:gap-4 rb:mt-6">
<Button block disabled={!values.current_prompt} onClick={handleCopy}>{t('common.copy')}</Button>
<Button type="primary" block disabled={!values.current_prompt} onClick={handleApply}>{t('application.apply')}</Button>
</div>
</div>
</Col>
<Col span={12} className="rb:border-r rb:border-[#DFE4ED]">
<Space>
<Button>{t('common.copy')}</Button>
<Button type="primary">{t('common.apply')}</Button>
</Space>
</Col>
<Col span={12}>
</Col>
</Row>
</div>
</Form>
<AiPromptVariableModal
ref={aiPromptVariableModalRef}
variables={variables}
refresh={handleVariableApply}
/>
</RbModal>
);
});

View File

@@ -0,0 +1,107 @@
import { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import { Form, Input, App, Select, AutoComplete, type AutoCompleteProps } from 'antd';
import { useTranslation } from 'react-i18next';
import type { Application } from '@/views/ApplicationManagement/types'
import type { AiPromptVariableModalRef } from '../types'
import { createApiKey } from '@/api/apiKey';
import RbModal from '@/components/RbModal'
const FormItem = Form.Item;
interface AiPromptVariableModalProps {
refresh: (value: string) => void;
variables: string[];
}
const AiPromptVariableModal = forwardRef<AiPromptVariableModalRef, AiPromptVariableModalProps>(({
refresh,
variables
}, ref) => {
const { t } = useTranslation();
const { message } = App.useApp();
const [visible, setVisible] = useState(false);
const [form] = Form.useForm();
const [loading, setLoading] = useState(false)
const [options, setOptions] = useState<AutoCompleteProps['options']>([])
useEffect(() => {
setOptions(variables.map(key => ({
value: key,
label: `{{${key}}}`
})))
}, [variables])
const handleSearch = (value: string) => {
const filterKeys = variables?.filter(key => key.includes(value))
if (filterKeys.length) {
setOptions(filterKeys.map(key => ({
value: key,
label: `{{${key}}}`
})))
} else {
setOptions([{
value: value,
label: `{{${value}}}`
}])
}
}
// 封装取消方法,添加关闭弹窗逻辑
const handleClose = () => {
setVisible(false);
form.resetFields();
setLoading(false)
};
const handleOpen = () => {
setVisible(true);
form.resetFields();
};
// 封装保存方法,添加提交逻辑
const handleSave = () => {
const variableName = form.getFieldValue('variableName')
if (!variableName) return
refresh(`{{${variableName}}}`)
handleClose()
}
// 暴露给父组件的方法
useImperativeHandle(ref, () => ({
handleOpen,
handleClose
}));
return (
<RbModal
title={t('application.addVariable')}
open={visible}
onCancel={handleClose}
confirmLoading={loading}
onOk={handleSave}
okText={t('application.apply')}
>
<Form
form={form}
layout="vertical"
scrollToFirstError={{ behavior: 'instant', block: 'end', focus: true }}
>
<FormItem
name="variableName"
label={t('application.defineVariableName')}
extra={t('application.defineVariableNameExtra')}
>
<AutoComplete
placeholder={t('application.defineVariableNamePlaceholder')}
onSearch={handleSearch}
options={options}
/>
</FormItem>
</Form>
</RbModal>
);
});
export default AiPromptVariableModal;

View File

@@ -361,7 +361,7 @@ const Chat: FC<ChatProps> = ({ chatList, data, updateChatList, handleSave, sourc
data={chat.list || []}
streamLoading={compareLoading}
labelPosition="top"
labelFormat={(item) => item.role === 'user' ? 'You' : chat.label}
labelFormat={(item) => item.role === 'user' ? t('application.you') : chat.label}
errorDesc={t('application.ReplyException')}
/>

View File

@@ -137,7 +137,7 @@ export interface ModelConfigModalData {
[key: string]: string;
}
export interface AiPromptModalRef {
handleOpen: (application?: Config) => void;
handleOpen: () => void;
}
export interface KnowledgeModalRef {
handleOpen: (config?: KnowledgeConfig[]) => void;
@@ -203,4 +203,13 @@ export interface ApiKeyModalRef {
}
export interface ApiKeyConfigModalRef {
handleOpen: (apiKey: ApiKey) => void;
}
export interface AiPromptVariableModalRef {
handleOpen: () => void;
}
export interface AiPromptForm {
model_id?: string;
message?: string;
current_prompt?: string;
}