refac
This commit is contained in:
1 parent
b6acd3cc45
commit
212eec408c
10 files changed
+440
-10
No files matched your search
@@ -0,0 +1,31 @@
|
|||||||
|
"""add user variables
|
||||||
|
|
||||||
|
Revision ID: b0018471bbbe
|
||||||
|
Revises: c49178636c78
|
||||||
|
Create Date: 2026-07-24 01:21:46.457057
|
||||||
|
|
||||||
|
"""
|
||||||
|
from typing import Sequence, Union
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision: str = 'b0018471bbbe'
|
||||||
|
down_revision: Union[str, None] = 'c49178636c78'
|
||||||
|
branch_labels: Union[str, Sequence[str], None] = None
|
||||||
|
depends_on: Union[str, Sequence[str], None] = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
conn = op.get_bind()
|
||||||
|
inspector = sa.inspect(conn)
|
||||||
|
columns = [col['name'] for col in inspector.get_columns('user')]
|
||||||
|
|
||||||
|
if 'variables' not in columns:
|
||||||
|
op.add_column('user', sa.Column('variables', sa.JSON(), nullable=True))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_column('user', 'variables')
|
||||||
@@ -9,7 +9,7 @@ from open_webui.env import DATABASE_USER_ACTIVE_STATUS_UPDATE_INTERVAL
|
|||||||
from open_webui.internal.db import Base, JSONField, get_async_db_context
|
from open_webui.internal.db import Base, JSONField, get_async_db_context
|
||||||
from open_webui.utils.misc import throttle
|
from open_webui.utils.misc import throttle
|
||||||
from open_webui.utils.validate import validate_profile_image_url
|
from open_webui.utils.validate import validate_profile_image_url
|
||||||
from pydantic import BaseModel, ConfigDict, field_validator, model_validator
|
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||||
from sqlalchemy import (
|
from sqlalchemy import (
|
||||||
JSON,
|
JSON,
|
||||||
BigInteger,
|
BigInteger,
|
||||||
@@ -69,6 +69,7 @@ class User(Base): # identity & profile
|
|||||||
|
|
||||||
# Metadata
|
# Metadata
|
||||||
info = Column(JSON, nullable=True)
|
info = Column(JSON, nullable=True)
|
||||||
|
variables = Column(JSON, nullable=True)
|
||||||
settings = Column(JSON, nullable=True)
|
settings = Column(JSON, nullable=True)
|
||||||
oauth = Column(JSON, nullable=True)
|
oauth = Column(JSON, nullable=True)
|
||||||
scim = Column(JSON, nullable=True)
|
scim = Column(JSON, nullable=True)
|
||||||
@@ -105,6 +106,7 @@ class UserModel(BaseModel):
|
|||||||
status_expires_at: int | None = None
|
status_expires_at: int | None = None
|
||||||
|
|
||||||
info: dict | None = None
|
info: dict | None = None
|
||||||
|
variables: dict = Field(default_factory=dict, exclude=True)
|
||||||
settings: UserSettings | None = None
|
settings: UserSettings | None = None
|
||||||
|
|
||||||
oauth: dict | None = None
|
oauth: dict | None = None
|
||||||
@@ -126,6 +128,11 @@ class UserModel(BaseModel):
|
|||||||
self.profile_image_url = self.profile_image_url or _DEFAULT_PROFILE_IMAGE_URL.format(user_id=self.id)
|
self.profile_image_url = self.profile_image_url or _DEFAULT_PROFILE_IMAGE_URL.format(user_id=self.id)
|
||||||
return self
|
return self
|
||||||
|
|
||||||
|
@field_validator('variables', mode='before')
|
||||||
|
@classmethod
|
||||||
|
def normalize_variables(cls, value):
|
||||||
|
return value if isinstance(value, dict) else {}
|
||||||
|
|
||||||
|
|
||||||
class UserStatusModel(UserModel):
|
class UserStatusModel(UserModel):
|
||||||
is_active: bool = False
|
is_active: bool = False
|
||||||
|
|||||||
@@ -44,6 +44,7 @@ from open_webui.utils.auth import (
|
|||||||
get_verified_user,
|
get_verified_user,
|
||||||
validate_password,
|
validate_password,
|
||||||
)
|
)
|
||||||
|
from open_webui.utils.chat_variables import ChatVariablesError, normalize_user_variables, validate_user_variables
|
||||||
from pydantic import BaseModel, ConfigDict, Field
|
from pydantic import BaseModel, ConfigDict, Field
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
@@ -574,6 +575,52 @@ async def get_user_info_by_session_user(user=Depends(get_verified_user), db: Asy
|
|||||||
return user.info
|
return user.info
|
||||||
|
|
||||||
|
|
||||||
|
class UserVariablesForm(BaseModel):
|
||||||
|
variables: dict = Field(default_factory=dict)
|
||||||
|
|
||||||
|
|
||||||
|
class UserVariablesResponse(BaseModel):
|
||||||
|
variables: dict[str, str] = Field(default_factory=dict)
|
||||||
|
|
||||||
|
|
||||||
|
############################
|
||||||
|
# GetUserVariablesBySessionUser
|
||||||
|
############################
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/user/variables', response_model=UserVariablesResponse)
|
||||||
|
async def get_user_variables_by_session_user(user=Depends(get_verified_user)):
|
||||||
|
return UserVariablesResponse(variables=normalize_user_variables(user.variables))
|
||||||
|
|
||||||
|
|
||||||
|
############################
|
||||||
|
# UpdateUserVariablesBySessionUser
|
||||||
|
############################
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/user/variables/update', response_model=UserVariablesResponse)
|
||||||
|
async def update_user_variables_by_session_user(
|
||||||
|
form_data: UserVariablesForm,
|
||||||
|
user=Depends(get_verified_user),
|
||||||
|
db: AsyncSession = Depends(get_async_session),
|
||||||
|
):
|
||||||
|
try:
|
||||||
|
variables = validate_user_variables(form_data.variables)
|
||||||
|
except ChatVariablesError as exc:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST,
|
||||||
|
detail=str(exc),
|
||||||
|
)
|
||||||
|
|
||||||
|
updated = await Users.update_user_by_id(user.id, {'variables': variables}, db=db)
|
||||||
|
if not updated:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST,
|
||||||
|
detail=ERROR_MESSAGES.USER_NOT_FOUND,
|
||||||
|
)
|
||||||
|
return UserVariablesResponse(variables=variables)
|
||||||
|
|
||||||
|
|
||||||
############################
|
############################
|
||||||
# UpdateUserInfoBySessionUser
|
# UpdateUserInfoBySessionUser
|
||||||
############################
|
############################
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ from typing import Any
|
|||||||
|
|
||||||
CHAT_VARIABLE_KEY_RE = re.compile(r'^[a-z][a-z0-9_]*$')
|
CHAT_VARIABLE_KEY_RE = re.compile(r'^[a-z][a-z0-9_]*$')
|
||||||
CHAT_VARIABLE_ANY_RE = re.compile(r'{{\s*chat\.variables\.([^\s|}]+)(?:\s*\|\s*([^}]*))?\s*}}')
|
CHAT_VARIABLE_ANY_RE = re.compile(r'{{\s*chat\.variables\.([^\s|}]+)(?:\s*\|\s*([^}]*))?\s*}}')
|
||||||
|
USER_VARIABLE_ANY_RE = re.compile(r'{{\s*user\.variables\.([^\s|}]+)(?:\s*\|\s*([^}]*))?\s*}}')
|
||||||
MAX_VARIABLE_VALUE_LENGTH = 20_000
|
MAX_VARIABLE_VALUE_LENGTH = 20_000
|
||||||
MAX_VARIABLES_JSON_LENGTH = 100_000
|
MAX_VARIABLES_JSON_LENGTH = 100_000
|
||||||
|
|
||||||
@@ -173,6 +174,36 @@ def normalize_chat_variables(variables: Any) -> dict[str, Any]:
|
|||||||
return variables
|
return variables
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_user_variables(variables: Any) -> dict[str, str]:
|
||||||
|
if not isinstance(variables, dict):
|
||||||
|
return {}
|
||||||
|
return {key: value for key, value in variables.items() if isinstance(key, str) and isinstance(value, str)}
|
||||||
|
|
||||||
|
|
||||||
|
def validate_user_variables(variables: Any) -> dict[str, str]:
|
||||||
|
if not isinstance(variables, dict):
|
||||||
|
raise ChatVariablesError('User variables must be an object.')
|
||||||
|
|
||||||
|
try:
|
||||||
|
if len(json.dumps(variables)) > MAX_VARIABLES_JSON_LENGTH:
|
||||||
|
raise ChatVariablesError('User variables are too large.')
|
||||||
|
except TypeError:
|
||||||
|
raise ChatVariablesError('User variables must be JSON serializable.')
|
||||||
|
|
||||||
|
validated: dict[str, str] = {}
|
||||||
|
for key, value in variables.items():
|
||||||
|
if not isinstance(key, str) or not CHAT_VARIABLE_KEY_RE.match(key):
|
||||||
|
raise ChatVariablesError(f'Invalid user variable key: {key}')
|
||||||
|
if not isinstance(value, str):
|
||||||
|
raise ChatVariablesError(f'User variable must be a string: {key}')
|
||||||
|
value = value.replace('\r\n', '\n')
|
||||||
|
if len(value) > MAX_VARIABLE_VALUE_LENGTH:
|
||||||
|
raise ChatVariablesError(f'User variable is too long: {key}')
|
||||||
|
validated[key] = value
|
||||||
|
|
||||||
|
return validated
|
||||||
|
|
||||||
|
|
||||||
def validate_chat_variables(
|
def validate_chat_variables(
|
||||||
system_prompt: str | None,
|
system_prompt: str | None,
|
||||||
variables: Any,
|
variables: Any,
|
||||||
@@ -240,3 +271,18 @@ def render_chat_variables(
|
|||||||
return '' if value is None else str(value)
|
return '' if value is None else str(value)
|
||||||
|
|
||||||
return CHAT_VARIABLE_ANY_RE.sub(replace, system_prompt)
|
return CHAT_VARIABLE_ANY_RE.sub(replace, system_prompt)
|
||||||
|
|
||||||
|
|
||||||
|
def render_user_variables(system_prompt: str | None, variables: Any) -> str | None:
|
||||||
|
if not system_prompt:
|
||||||
|
return system_prompt
|
||||||
|
|
||||||
|
variables = normalize_user_variables(variables)
|
||||||
|
|
||||||
|
def replace(match: re.Match) -> str:
|
||||||
|
key = match.group(1).strip()
|
||||||
|
if not CHAT_VARIABLE_KEY_RE.match(key):
|
||||||
|
return ''
|
||||||
|
return variables.get(key, '')
|
||||||
|
|
||||||
|
return USER_VARIABLE_ANY_RE.sub(replace, system_prompt)
|
||||||
@@ -7,7 +7,7 @@ from open_webui.utils.misc import (
|
|||||||
deep_update,
|
deep_update,
|
||||||
replace_system_message_content,
|
replace_system_message_content,
|
||||||
)
|
)
|
||||||
from open_webui.utils.chat_variables import render_chat_variables
|
from open_webui.utils.chat_variables import render_chat_variables, render_user_variables
|
||||||
from open_webui.utils.task import prompt_template, prompt_variables_template
|
from open_webui.utils.task import prompt_template, prompt_variables_template
|
||||||
|
|
||||||
|
|
||||||
@@ -26,6 +26,8 @@ async def resolve_system_prompt(
|
|||||||
required=False,
|
required=False,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
system = render_user_variables(system, getattr(user, 'variables', {}) if user else {})
|
||||||
|
|
||||||
# Metadata (WebUI Usage)
|
# Metadata (WebUI Usage)
|
||||||
if metadata:
|
if metadata:
|
||||||
variables = metadata.get('variables', {})
|
variables = metadata.get('variables', {})
|
||||||
|
|||||||
@@ -440,6 +440,62 @@ export const updateUserInfo = async (token: string, info: object) => {
|
|||||||
return res;
|
return res;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const getUserVariables = async (token: string) => {
|
||||||
|
let error = null;
|
||||||
|
const res = await fetch(`${WEBUI_API_BASE_URL}/users/user/variables`, {
|
||||||
|
method: 'GET',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
Authorization: `Bearer ${token}`
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.then(async (res) => {
|
||||||
|
if (!res.ok) throw await res.json();
|
||||||
|
return res.json();
|
||||||
|
})
|
||||||
|
.catch((err) => {
|
||||||
|
console.error(err);
|
||||||
|
error = err.detail;
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
return res;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const updateUserVariables = async (token: string, variables: Record<string, string>) => {
|
||||||
|
let error = null;
|
||||||
|
|
||||||
|
const res = await fetch(`${WEBUI_API_BASE_URL}/users/user/variables/update`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
Authorization: `Bearer ${token}`
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
variables
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.then(async (res) => {
|
||||||
|
if (!res.ok) throw await res.json();
|
||||||
|
return res.json();
|
||||||
|
})
|
||||||
|
.catch((err) => {
|
||||||
|
console.error(err);
|
||||||
|
error = err.detail;
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
return res;
|
||||||
|
};
|
||||||
|
|
||||||
export const getAndUpdateUserLocation = async (token: string) => {
|
export const getAndUpdateUserLocation = async (token: string) => {
|
||||||
const location = await getUserPosition().catch((err) => {
|
const location = await getUserPosition().catch((err) => {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
|
|
||||||
import { user, config } from '$lib/stores';
|
import { user, config } from '$lib/stores';
|
||||||
import { updateUserProfile, createAPIKey, getAPIKey, getSessionUser } from '$lib/apis/auths';
|
import { updateUserProfile, createAPIKey, getAPIKey, getSessionUser } from '$lib/apis/auths';
|
||||||
|
import { getUserVariables, updateUserVariables } from '$lib/apis/users';
|
||||||
import { WEBUI_BASE_URL } from '$lib/constants';
|
import { WEBUI_BASE_URL } from '$lib/constants';
|
||||||
|
|
||||||
import UpdatePassword from './Account/UpdatePassword.svelte';
|
import UpdatePassword from './Account/UpdatePassword.svelte';
|
||||||
@@ -14,6 +15,7 @@
|
|||||||
import Tooltip from '$lib/components/common/Tooltip.svelte';
|
import Tooltip from '$lib/components/common/Tooltip.svelte';
|
||||||
import SensitiveInput from '$lib/components/common/SensitiveInput.svelte';
|
import SensitiveInput from '$lib/components/common/SensitiveInput.svelte';
|
||||||
import Textarea from '$lib/components/common/Textarea.svelte';
|
import Textarea from '$lib/components/common/Textarea.svelte';
|
||||||
|
import Modal from '$lib/components/common/Modal.svelte';
|
||||||
import UserProfileImage from './Account/UserProfileImage.svelte';
|
import UserProfileImage from './Account/UserProfileImage.svelte';
|
||||||
import UserSettingField from './UserSettingField.svelte';
|
import UserSettingField from './UserSettingField.svelte';
|
||||||
import UserSettingRow from './UserSettingRow.svelte';
|
import UserSettingRow from './UserSettingRow.svelte';
|
||||||
@@ -38,15 +40,99 @@
|
|||||||
|
|
||||||
let APIKey = '';
|
let APIKey = '';
|
||||||
let APIKeyCopied = false;
|
let APIKeyCopied = false;
|
||||||
|
let variableRows: { key: string; value: string }[] = [];
|
||||||
|
let variableModalOpen = false;
|
||||||
|
let variableFormIndex: number | null = null;
|
||||||
|
let variableFormKey = '';
|
||||||
|
let variableFormValue = '';
|
||||||
|
|
||||||
const textareaClass =
|
const textareaClass =
|
||||||
'w-full resize-y rounded-lg border border-gray-100/50 bg-gray-50/40 px-2 py-1.5 text-xs text-gray-700 outline-hidden transition-colors placeholder:text-gray-300 focus:border-blue-400 dark:border-white/[0.04] dark:bg-white/[0.03] dark:text-gray-300 dark:placeholder:text-gray-700 dark:focus:border-blue-500';
|
'w-full resize-y rounded-lg border border-gray-100/50 bg-gray-50/40 px-2 py-1.5 text-xs text-gray-700 outline-hidden transition-colors placeholder:text-gray-300 focus:border-blue-400 dark:border-white/[0.04] dark:bg-white/[0.03] dark:text-gray-300 dark:placeholder:text-gray-700 dark:focus:border-blue-500';
|
||||||
const inputClass =
|
const inputClass =
|
||||||
'h-7 w-full rounded-lg border border-gray-100/50 bg-gray-50/40 px-2 text-xs text-gray-700 outline-hidden transition-colors placeholder:text-gray-300 focus:border-blue-400 dark:border-white/[0.04] dark:bg-white/[0.03] dark:text-gray-300 dark:placeholder:text-gray-700 dark:focus:border-blue-500';
|
'h-7 w-full rounded-lg border border-gray-100/50 bg-gray-50/40 px-2 text-xs text-gray-700 outline-hidden transition-colors placeholder:text-gray-300 focus:border-blue-400 dark:border-white/[0.04] dark:bg-white/[0.03] dark:text-gray-300 dark:placeholder:text-gray-700 dark:focus:border-blue-500';
|
||||||
|
const variableValueClass =
|
||||||
|
'w-full resize-none rounded-lg border border-gray-100/50 bg-gray-50/40 px-2 py-1.5 text-xs text-gray-700 outline-hidden transition-colors placeholder:text-gray-300 focus:border-blue-400 dark:border-white/[0.04] dark:bg-white/[0.03] dark:text-gray-300 dark:placeholder:text-gray-700 dark:focus:border-blue-500';
|
||||||
const actionButtonClass =
|
const actionButtonClass =
|
||||||
'text-xs text-gray-500 transition-colors hover:text-gray-900 dark:text-gray-500 dark:hover:text-white';
|
'text-xs text-gray-500 transition-colors hover:text-gray-900 dark:text-gray-500 dark:hover:text-white';
|
||||||
|
const variableRowClass = (idx: number) =>
|
||||||
|
`flex min-h-7 w-full items-center gap-2 py-0.5 ${
|
||||||
|
idx > 0 ? 'border-t border-gray-50 dark:border-white/[0.04]' : ''
|
||||||
|
}`;
|
||||||
|
const variableKeyRegex = /^[a-z][a-z0-9_]*$/;
|
||||||
|
|
||||||
|
const setVariableRows = (variables = {}) => {
|
||||||
|
variableRows = Object.entries(variables).map(([key, value]) => ({
|
||||||
|
key,
|
||||||
|
value: String(value ?? '')
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
|
||||||
|
const openVariableModal = (idx: number | null = null) => {
|
||||||
|
const row = idx === null ? null : variableRows[idx];
|
||||||
|
variableFormIndex = idx;
|
||||||
|
variableFormKey = row?.key ?? '';
|
||||||
|
variableFormValue = row?.value ?? '';
|
||||||
|
variableModalOpen = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
const removeVariable = (idx: number) => {
|
||||||
|
variableRows = variableRows.filter((_, rowIdx) => rowIdx !== idx);
|
||||||
|
};
|
||||||
|
|
||||||
|
const saveVariableForm = () => {
|
||||||
|
const key = variableFormKey.trim();
|
||||||
|
|
||||||
|
if (!variableKeyRegex.test(key)) {
|
||||||
|
toast.error($i18n.t('Variable keys must use lowercase snake case.'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (variableRows.some((row, idx) => idx !== variableFormIndex && row.key === key)) {
|
||||||
|
toast.error($i18n.t('Variable keys must be unique.'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const row = { key, value: variableFormValue ?? '' };
|
||||||
|
variableRows =
|
||||||
|
variableFormIndex === null
|
||||||
|
? [...variableRows, row]
|
||||||
|
: variableRows.map((current, idx) => (idx === variableFormIndex ? row : current));
|
||||||
|
variableModalOpen = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
const deleteVariableForm = () => {
|
||||||
|
if (variableFormIndex !== null) {
|
||||||
|
removeVariable(variableFormIndex);
|
||||||
|
}
|
||||||
|
variableModalOpen = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
const getVariablesPayload = () => {
|
||||||
|
const variables: Record<string, string> = {};
|
||||||
|
for (const row of variableRows) {
|
||||||
|
const key = row.key.trim();
|
||||||
|
if (!key && !row.value) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!variableKeyRegex.test(key)) {
|
||||||
|
throw $i18n.t('Variable keys must use lowercase snake case.');
|
||||||
|
}
|
||||||
|
if (Object.prototype.hasOwnProperty.call(variables, key)) {
|
||||||
|
throw $i18n.t('Variable keys must be unique.');
|
||||||
|
}
|
||||||
|
variables[key] = row.value ?? '';
|
||||||
|
}
|
||||||
|
return variables;
|
||||||
|
};
|
||||||
|
|
||||||
const submitHandler = async () => {
|
const submitHandler = async () => {
|
||||||
|
let variables: Record<string, string>;
|
||||||
|
try {
|
||||||
|
variables = getVariablesPayload();
|
||||||
|
} catch (error) {
|
||||||
|
toast.error(`${error}`);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
if (name !== $user?.name) {
|
if (name !== $user?.name) {
|
||||||
if (profileImageUrl === generateInitialsImage($user?.name) || profileImageUrl === '') {
|
if (profileImageUrl === generateInitialsImage($user?.name) || profileImageUrl === '') {
|
||||||
profileImageUrl = generateInitialsImage(name);
|
profileImageUrl = generateInitialsImage(name);
|
||||||
@@ -63,7 +149,13 @@
|
|||||||
toast.error(`${error}`);
|
toast.error(`${error}`);
|
||||||
});
|
});
|
||||||
|
|
||||||
if (updatedUser) {
|
const variablesRes = await updateUserVariables(localStorage.token, variables).catch((error) => {
|
||||||
|
toast.error(`${error}`);
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (updatedUser && variablesRes) {
|
||||||
|
setVariableRows(variablesRes.variables ?? {});
|
||||||
// Get Session User Info
|
// Get Session User Info
|
||||||
const sessionUser = await getSessionUser(localStorage.token).catch((error) => {
|
const sessionUser = await getSessionUser(localStorage.token).catch((error) => {
|
||||||
toast.error(`${error}`);
|
toast.error(`${error}`);
|
||||||
@@ -102,6 +194,12 @@
|
|||||||
dateOfBirth = user?.date_of_birth ?? '';
|
dateOfBirth = user?.date_of_birth ?? '';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const userVariables = await getUserVariables(localStorage.token).catch((error) => {
|
||||||
|
toast.error(`${error}`);
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
setVariableRows(userVariables?.variables ?? {});
|
||||||
|
|
||||||
// Only fetch API key if the feature is enabled and user has permission
|
// Only fetch API key if the feature is enabled and user has permission
|
||||||
if (
|
if (
|
||||||
user &&
|
user &&
|
||||||
@@ -206,6 +304,52 @@
|
|||||||
</UserSettingField>
|
</UserSettingField>
|
||||||
</UserSettingSection>
|
</UserSettingSection>
|
||||||
|
|
||||||
|
<UserSettingSection title={$i18n.t('User Variables')}>
|
||||||
|
<span slot="suffix" class="text-gray-400 dark:text-gray-600">{variableRows.length}</span>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<div class="flex items-center justify-between gap-2">
|
||||||
|
<div class="text-[0.6875rem] text-gray-400 dark:text-gray-600">
|
||||||
|
{$i18n.t('Use these in model system prompts as {{example}}.', {
|
||||||
|
example: '{{user.variables.key_name}}'
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex shrink-0 items-center gap-2">
|
||||||
|
<button class={actionButtonClass} type="button" on:click={() => openVariableModal()}>
|
||||||
|
{$i18n.t('Add')}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex flex-col">
|
||||||
|
{#each variableRows as row, idx}
|
||||||
|
<div class={variableRowClass(idx)}>
|
||||||
|
<div class="min-w-0 truncate font-mono text-xs text-gray-700 dark:text-gray-300">
|
||||||
|
{row.key || $i18n.t('key_name')}
|
||||||
|
</div>
|
||||||
|
<div class="min-w-0 flex-1 truncate text-xs text-gray-500 dark:text-gray-500">
|
||||||
|
{row.value || $i18n.t('Empty')}
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
class={actionButtonClass}
|
||||||
|
type="button"
|
||||||
|
on:click={() => openVariableModal(idx)}
|
||||||
|
>
|
||||||
|
{$i18n.t('Edit')}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
|
||||||
|
{#if variableRows.length === 0}
|
||||||
|
<div class="text-xs text-gray-400 dark:text-gray-600">
|
||||||
|
{$i18n.t('No user variables configured.')}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</UserSettingSection>
|
||||||
|
|
||||||
{#if $config?.features.enable_login_form && $config?.features.enable_password_change_form}
|
{#if $config?.features.enable_login_form && $config?.features.enable_password_change_form}
|
||||||
<UserSettingSection title={$i18n.t('Password')}>
|
<UserSettingSection title={$i18n.t('Password')}>
|
||||||
<UpdatePassword />
|
<UpdatePassword />
|
||||||
@@ -397,3 +541,68 @@
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<Modal size="sm" bind:show={variableModalOpen}>
|
||||||
|
<form class="p-4" on:submit|preventDefault={saveVariableForm}>
|
||||||
|
<h2 class="mb-3 text-sm font-medium text-gray-900 dark:text-white">
|
||||||
|
{variableFormIndex === null ? $i18n.t('Add User Variable') : $i18n.t('Edit User Variable')}
|
||||||
|
</h2>
|
||||||
|
|
||||||
|
<div class="mb-1 text-[0.625rem] text-gray-400 dark:text-gray-600">
|
||||||
|
{$i18n.t('Key')}
|
||||||
|
</div>
|
||||||
|
<input
|
||||||
|
class={inputClass}
|
||||||
|
type="text"
|
||||||
|
bind:value={variableFormKey}
|
||||||
|
aria-label={$i18n.t('Variable key')}
|
||||||
|
placeholder={$i18n.t('key_name')}
|
||||||
|
autocomplete="off"
|
||||||
|
spellcheck="false"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div class="mb-1 mt-3 text-[0.625rem] text-gray-400 dark:text-gray-600">
|
||||||
|
{$i18n.t('Value')}
|
||||||
|
</div>
|
||||||
|
<Textarea
|
||||||
|
className={variableValueClass}
|
||||||
|
rows="6"
|
||||||
|
minSize={132}
|
||||||
|
bind:value={variableFormValue}
|
||||||
|
ariaLabel={$i18n.t('Variable value')}
|
||||||
|
placeholder={$i18n.t('Value')}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div class="mt-4 flex items-center justify-between gap-2">
|
||||||
|
<div>
|
||||||
|
{#if variableFormIndex !== null}
|
||||||
|
<button
|
||||||
|
class="text-xs text-gray-500 transition-colors hover:text-gray-900 dark:text-gray-500 dark:hover:text-white"
|
||||||
|
type="button"
|
||||||
|
on:click={deleteVariableForm}
|
||||||
|
>
|
||||||
|
{$i18n.t('Delete')}
|
||||||
|
</button>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex items-center gap-3">
|
||||||
|
<button
|
||||||
|
class="text-xs text-gray-500 transition-colors hover:text-gray-900 dark:text-gray-500 dark:hover:text-white"
|
||||||
|
type="button"
|
||||||
|
on:click={() => {
|
||||||
|
variableModalOpen = false;
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{$i18n.t('Cancel')}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
class="rounded-full bg-black px-3.5 py-1.5 text-sm font-normal text-white transition hover:bg-gray-900 dark:bg-white dark:text-black dark:hover:bg-gray-100"
|
||||||
|
type="submit"
|
||||||
|
>
|
||||||
|
{$i18n.t('Done')}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</Modal>
|
||||||
@@ -55,7 +55,7 @@
|
|||||||
}}>{show ? $i18n.t('Hide') : $i18n.t('Show')}</button
|
}}>{show ? $i18n.t('Hide') : $i18n.t('Show')}</button
|
||||||
>
|
>
|
||||||
</div>
|
</div>
|
||||||
<p class="-mt-1 text-[0.6875rem] text-gray-400 dark:text-gray-600">
|
<p class="mt-0.5 text-[0.6875rem] text-gray-400 dark:text-gray-600">
|
||||||
{$i18n.t('Update the password used for email and password sign-in.')}
|
{$i18n.t('Update the password used for email and password sign-in.')}
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
|
|||||||
@@ -6,8 +6,9 @@
|
|||||||
|
|
||||||
<section class="w-full {first ? '' : 'mt-4'} {className}">
|
<section class="w-full {first ? '' : 'mt-4'} {className}">
|
||||||
{#if title}
|
{#if title}
|
||||||
<h3 class="mb-2 text-xs text-gray-400 dark:text-gray-600">
|
<h3 class="mb-2 flex items-center gap-1.5 text-xs text-gray-600 dark:text-gray-400">
|
||||||
{title}
|
{title}
|
||||||
|
<slot name="suffix" />
|
||||||
</h3>
|
</h3>
|
||||||
{/if}
|
{/if}
|
||||||
|
|
||||||
|
|||||||
@@ -120,6 +120,7 @@
|
|||||||
const warnings: string[] = [];
|
const warnings: string[] = [];
|
||||||
const seenDefinitions: Record<string, string> = {};
|
const seenDefinitions: Record<string, string> = {};
|
||||||
const typedRegex = /{{\s*chat\.variables\.([a-zA-Z0-9_.-]+)\s*\|\s*([^}]*)\s*}}/g;
|
const typedRegex = /{{\s*chat\.variables\.([a-zA-Z0-9_.-]+)\s*\|\s*([^}]*)\s*}}/g;
|
||||||
|
const typedUserRegex = /{{\s*user\.variables\.([a-zA-Z0-9_.-]+)\s*\|\s*([^}]*)\s*}}/g;
|
||||||
|
|
||||||
for (const match of prompt.matchAll(typedRegex)) {
|
for (const match of prompt.matchAll(typedRegex)) {
|
||||||
const key = match[1];
|
const key = match[1];
|
||||||
@@ -133,6 +134,13 @@
|
|||||||
const fields = Object.entries(variables)
|
const fields = Object.entries(variables)
|
||||||
.filter(([name]) => name.startsWith('chat.variables.'))
|
.filter(([name]) => name.startsWith('chat.variables.'))
|
||||||
.map(([name, field]) => ({ key: name.replace('chat.variables.', ''), ...(field as any) }));
|
.map(([name, field]) => ({ key: name.replace('chat.variables.', ''), ...(field as any) }));
|
||||||
|
const userFields = Object.entries(variables)
|
||||||
|
.filter(([name]) => name.startsWith('user.variables.'))
|
||||||
|
.map(([name]) => ({ key: name.replace('user.variables.', '') }));
|
||||||
|
|
||||||
|
for (const match of prompt.matchAll(typedUserRegex)) {
|
||||||
|
warnings.push(`${match[1]} uses metadata, but User Variables are configured by each user`);
|
||||||
|
}
|
||||||
|
|
||||||
for (const field of fields) {
|
for (const field of fields) {
|
||||||
const key = field.key;
|
const key = field.key;
|
||||||
@@ -149,7 +157,13 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return { fields, warnings };
|
for (const field of userFields) {
|
||||||
|
if (!chatVariableKeyRegex.test(field.key)) {
|
||||||
|
warnings.push(`${field.key} must be lowercase snake case`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { fields, userFields, warnings };
|
||||||
};
|
};
|
||||||
|
|
||||||
$: chatVariablesPreview = getChatVariablesPreview(system ?? '');
|
$: chatVariablesPreview = getChatVariablesPreview(system ?? '');
|
||||||
@@ -762,20 +776,24 @@
|
|||||||
bind:value={system}
|
bind:value={system}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
{#if chatVariablesPreview.fields.length > 0 || chatVariablesPreview.warnings.length > 0}
|
{#if chatVariablesPreview.fields.length > 0 || chatVariablesPreview.userFields.length > 0 || chatVariablesPreview.warnings.length > 0}
|
||||||
<div class="mt-2 border-t border-gray-100/60 pt-2 dark:border-gray-850/60">
|
<div class="mt-2 border-t border-gray-100/60 pt-2 dark:border-gray-850/60">
|
||||||
<div class="mb-1.5 flex items-center justify-between gap-2">
|
<div class="mb-1.5 flex items-center justify-between gap-2">
|
||||||
<div class="text-xs text-gray-500 dark:text-gray-400">
|
<div class="text-xs text-gray-500 dark:text-gray-400">
|
||||||
{$i18n.t('Detected Chat Variables')}
|
{$i18n.t('Detected Variables')}
|
||||||
</div>
|
</div>
|
||||||
{#if chatVariablesPreview.fields.length > 0}
|
{#if chatVariablesPreview.fields.length + chatVariablesPreview.userFields.length > 0}
|
||||||
<div class="text-[0.6875rem] text-gray-400 dark:text-gray-600">
|
<div class="text-[0.6875rem] text-gray-400 dark:text-gray-600">
|
||||||
{chatVariablesPreview.fields.length}
|
{chatVariablesPreview.fields.length +
|
||||||
|
chatVariablesPreview.userFields.length}
|
||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{#if chatVariablesPreview.fields.length > 0}
|
{#if chatVariablesPreview.fields.length > 0}
|
||||||
|
<div class="mb-1 text-[0.6875rem] text-gray-400 dark:text-gray-600">
|
||||||
|
{$i18n.t('Chat Variables')}
|
||||||
|
</div>
|
||||||
<div class="flex flex-wrap gap-x-3 gap-y-1.5 text-xs">
|
<div class="flex flex-wrap gap-x-3 gap-y-1.5 text-xs">
|
||||||
{#each chatVariablesPreview.fields as field}
|
{#each chatVariablesPreview.fields as field}
|
||||||
<div class="flex items-center gap-1 text-gray-600 dark:text-gray-300">
|
<div class="flex items-center gap-1 text-gray-600 dark:text-gray-300">
|
||||||
@@ -789,6 +807,19 @@
|
|||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
|
|
||||||
|
{#if chatVariablesPreview.userFields.length > 0}
|
||||||
|
<div class="mb-1 mt-2 text-[0.6875rem] text-gray-400 dark:text-gray-600">
|
||||||
|
{$i18n.t('User Variables')}
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-wrap gap-x-3 gap-y-1.5 text-xs">
|
||||||
|
{#each chatVariablesPreview.userFields as field}
|
||||||
|
<div class="flex items-center gap-1 text-gray-600 dark:text-gray-300">
|
||||||
|
<span class="font-medium">{field.key}</span>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
{#if chatVariablesPreview.warnings.length > 0}
|
{#if chatVariablesPreview.warnings.length > 0}
|
||||||
<div
|
<div
|
||||||
class="mt-2 flex flex-col gap-1 text-xs text-amber-600 dark:text-amber-400"
|
class="mt-2 flex flex-col gap-1 text-xs text-amber-600 dark:text-amber-400"
|
||||||
|
|||||||
Reference in new issue
Block a user