Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion ui/public/fx/langsearch/detail.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ LangSearch 是一个提供免费Web Search API和Rerank API的服务,支持新

1. 获取API Key 
在[Langsearch](https://langsearch.com/overview) 上申请 API 密钥。
![API Key](/ui/fx/img/langsearchAPI_Key.jpg)
![API Key](/ui/fx/img/langsearch_APIKey.jpg)
2. 在函数库中配置
在函数库的LangSearch函数面板中,点击 … > 启用参数,填写 API 密钥,并启用该函数。
![启动参数](/ui/fx/img/langsearch_setting.jpg)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -780,6 +780,4 @@ onMounted(() => {
}
}
}
.chat-pc {
}
</style>
13 changes: 9 additions & 4 deletions ui/src/components/ai-chat/component/user-form/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,9 @@ import { useRoute } from 'vue-router'
import { MsgWarning } from '@/utils/message'
import { t } from '@/locales'
const route = useRoute()
const {
params: { accessToken }
} = route
const props = defineProps<{
application: any
type: 'log' | 'ai-chat' | 'debug-ai-chat'
Expand All @@ -78,6 +81,8 @@ const inputFieldList = ref<FormField[]>([])
const apiInputFieldList = ref<FormField[]>([])
const inputFieldConfig = ref({ title: t('chat.userInput') })
const showUserInput = ref(true)
const firstMounted = ref(false)

const emit = defineEmits(['update:api_form_data', 'update:form_data', 'confirm', 'cancel'])

const api_form_data_context = computed({
Expand All @@ -100,7 +105,7 @@ const form_data_context = computed({

watch(
() => props.application,
() => {
(data) => {
handleInputFieldList()
}
)
Expand Down Expand Up @@ -352,15 +357,15 @@ const decodeQuery = (query: string) => {
}
}
const confirmHandle = () => {
if (checkInputParam()) {
emit('confirm')
}
localStorage.setItem(`${accessToken}userForm`, JSON.stringify(form_data_context.value))
emit('confirm')
}
const cancelHandle = () => {
emit('cancel')
}
defineExpose({ checkInputParam })
onMounted(() => {
firstMounted.value = true
handleInputFieldList()
})
</script>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The provided code is generally well-written with proper imports, data declarations, watcher functions, and event emitters. However, there are a few minor improvements and optimizations that can be made:

  1. Avoid using useRef for strings: Since params.accessToken will always return a string, you don't need to wrap it in ref. Use let or const directly.

  2. Simplify watch, handle default values properly for showUderInput.

  3. Remove redundant check in handleConfirmHandle:

// Original check for required input parameters
if (checkInputParam()) {
  emit('confirm');
}

If checkInputParam() already checks if the user has filled out the necessary fields and emits an error message if not, this can be removed since the logic might have been intended to prevent confirm action in such cases, but removing it doesn't alter the functionality significantly unless needed otherwise.

  1. Remove unnecessary line breaks within template literals inside single quotes (''). The current format seems correct though, so no change is needed here.

By making these small adjustments, you could make the code cleaner and slightly more efficient. Keep up the good practices!

Expand Down
22 changes: 20 additions & 2 deletions ui/src/components/ai-chat/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -196,13 +196,27 @@ const toggleUserInput = () => {
}

function UserFormConfirm() {
firsUserInput.value = false
showUserInput.value = false
if (userFormRef.value?.checkInputParam()) {
firsUserInput.value = false
showUserInput.value = false
}
}

function sendMessage(val: string, other_params_data?: any, chat?: chatType) {
if (!userFormRef.value?.checkInputParam()) {
if (isUserInput.value) {
showUserInput.value = true
}
return
} else {
let userFormData = JSON.parse(localStorage.getItem(`${accessToken}userForm`) || '{}')
const newData = Object.keys(form_data.value).reduce((result: any, key: string) => {
result[key] = Object.prototype.hasOwnProperty.call(userFormData, key)
? userFormData[key]
: form_data.value[key]
return result
}, {})
localStorage.setItem(`${accessToken}userForm`, JSON.stringify(newData))
}
if (!loading.value && props.applicationDetails?.name) {
handleDebounceClick(val, other_params_data, chat)
Expand Down Expand Up @@ -505,6 +519,10 @@ const handleScroll = () => {
}

onMounted(() => {
if (isUserInput.value && localStorage.getItem(`${accessToken}userForm`)) {
let userFormData = JSON.parse(localStorage.getItem(`${accessToken}userForm`) || '{}')
form_data.value = userFormData
}
window.speechSynthesis.cancel()
window.sendMessage = sendMessage
bus.on('on:transcribing', (status: boolean) => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are a few potential areas of improvement and corrections in the given code:

  1. Undefined Check: The function toggleUserInput uses firsUserInput.value = false and showUserInput.value = false. Ensure that firsUserInput and showUserInput are properly initialized before being used.

  2. Nullish Coalescing Operator: Consider using the nullish coalescing operator (??) when accessing properties like localStorage.getItem() to avoid errors if localStorage is not supported.

  3. Stringify/Parse JSON Safely: When handling local storage, ensure that you parse and stringify objects safely by checking their validity. Use methods like JSON.parse(...) with defaults to prevent crashes.

  4. Logical Order: In sendMessage function, there's an unnecessary nested condition inside the check for userFormRef.value?.checkInputParam(). Move it outside if necessary.

Here’s an updated version of the relevant parts of the code with some improvements:

function toggleUserInput() {
  if (userFormRef.value?.checkInputParam()) {
    firsUserInput.value ??= false;
    showUserInput.value ??= false;
  }
}

function sendMessage(val: string, other_params_data?: any, chat?: chatType) {
  const shouldProcessInput = !!userFormRef.value?.checkInputParam();

  // Show input if needed after processing
  if (!shouldProcessInput && isUserInput.value) {
    showUserInput.value = true;
  }

  if (!loading.value && props.applicationDetails?.name) {
    if (shouldProcessInput) {
      let userFormData = JSON.parse(localStorage.getItem(`${accessToken}userForm`) || '{}') ?? {};
      const newData = Object.fromEntries(
        Object.entries<Object>(form_data.value).filter(([key]) =>
          Object.prototype.hasOwnProperty.call(userFormData, key)
        )
      );
      localStorage.setItem(`${accessToken}userForm`, JSON.stringify(newData));
    }

    handleDebounceClick(val, other_params_data, chat);
  }
}
  1. Additional Comments: Add comments where appropriate to explain complex logic or steps for future reference.

These changes aim to improve the robustness and readability of the代码 while maintaining its functionality.

Expand Down
24 changes: 16 additions & 8 deletions ui/src/views/function-lib/index.vue
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
<template>
<div class="function-lib-list-container p-24" style="padding-top: 16px">
<el-tabs v-model="functionType" @tab-change="selectUserId = ''">
<el-tabs
v-model="functionType"
@tab-change="
tabChangeHandle

"
>
<el-tab-pane :label="$t('views.functionLib.title')" name="PUBLIC"></el-tab-pane>
<el-tab-pane :label="$t('views.functionLib.internalTitle')" name="INTERNAL"></el-tab-pane>
</el-tabs>
Expand Down Expand Up @@ -280,11 +286,6 @@ import { isAppIcon } from '@/utils/application'
import InfiniteScroll from '@/components/infinite-scroll/index.vue'
import CardBox from '@/components/card-box/index.vue'
import AddInternalFunctionDialog from '@/views/function-lib/component/AddInternalFunctionDialog.vue'
// const internalDesc: Record<string, any> = import.meta.glob('/fx/*/detail.md', {
// eager: true,
// as: 'raw'
// })
// console.log(internalDesc)

const { user } = useStore()

Expand Down Expand Up @@ -331,6 +332,11 @@ watch(
{ immediate: true }
)

function tabChangeHandle() {
selectUserId.value = 'all'
searchValue.value = ''
}

const canEdit = (row: any) => {
return user.userInfo?.id === row?.user_id
}
Expand Down Expand Up @@ -404,10 +410,12 @@ async function changeState(bool: Boolean, row: any) {
})
} else {
const res = await functionLibApi.getFunctionLibById(row.id, changeStateloading)
if (!res.data.init_params &&
if (
!res.data.init_params &&
res.data.init_field_list &&
res.data.init_field_list.length > 0 &&
res.data.init_field_list.filter((item: any) => item.default_value).length !== res.data.init_field_list.length
res.data.init_field_list.filter((item: any) => item.default_value).length !==
res.data.init_field_list.length
) {
InitParamDrawerRef.value.open(res.data, bool)
row.is_active = false
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The provided code has several issues and optimizations that can be addressed:

  1. Tabs Handling Issue:
    The v-model of the tabs does not update correctly when selected to "INTERNAL". The event handler tabChangeHandle() should ensure that selectUserId is reset to 'all' and searchValue is cleared when switching between tabs.

  2. Raw Markdown Importing:
    The import statement for raw markdown files (...import.meta.glob('/fx/*/detail.md, ...)seems unnecessary as it will only work in development mode with a build environment. Consider usinguseFetch` or similar methods to dynamically retrieve data during runtime.

  3. Code Duplicity:
    The code snippets around line 407 have duplicative logic where you check if init_fields exist before checking each field's default value. Simplify this condition to:

    if (
      res.data.init_params && // Check init_params first
      res.data.init_field_list &&
      [...]
      res.data.init_field_list.some(item => item.default_value)
    )

Here's the optimized version of the key segments affected by these issues:

<template>
  <!-- Template remains unchanged -->
</template>

<script setup lang='ts'>
import { ref, watch } from 'vue';
import type { Ref } from 'vue';

const functionName = ref('');
const selectUserId: Ref<string> = ref('') as Ref<string>;
const searchValue: Ref<string> = ref('');
// No need for const internalDesc

const { user } = useStore();

watch(
  () => selectUserId.value,
  newVal => {
    if (newVal !== 'all') {
      searchValue.value = ''; // Reset searchValue on userId change
    }
  },
  { immediate: true }
);

async function tabChangeHandle() {
  selectUserId.value = 'all'; // Always set selectUserId to 'all' when changing tabs
  searchValue.value = '';
}

// Rest of the script...

Optimized Code Summary:

  • Removed raw markdown importing which may slow down production runs.
  • Corrected handling of funcType changes to include resetting selectUserId to 'all'.
  • Simplified logical checks for determining whether form fields have defaults.

These optimizations should improve both performance and usability.

Expand Down