mirror of
https://github.com/open-webui/open-webui
synced 2025-06-26 18:26:48 +00:00
refac: toolkit editor
This commit is contained in:
parent
55dfc2013a
commit
84bd4994cd
@ -1,127 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
import CodeEditor from '$lib/components/common/CodeEditor.svelte';
|
|
||||||
import { createEventDispatcher } from 'svelte';
|
|
||||||
|
|
||||||
const dispatch = createEventDispatcher();
|
|
||||||
|
|
||||||
export let value = '';
|
|
||||||
|
|
||||||
let codeEditor;
|
|
||||||
let boilerplate = `import os
|
|
||||||
import requests
|
|
||||||
from datetime import datetime
|
|
||||||
|
|
||||||
|
|
||||||
class Tools:
|
|
||||||
def __init__(self):
|
|
||||||
pass
|
|
||||||
|
|
||||||
# Add your custom tools using pure Python code here, make sure to add type hints
|
|
||||||
# Use Sphinx-style docstrings to document your tools, they will be used for generating tools specifications
|
|
||||||
# Please refer to function_calling_filter_pipeline.py file from pipelines project for an example
|
|
||||||
|
|
||||||
def get_user_name_and_email_and_id(self, __user__: dict = {}) -> str:
|
|
||||||
"""
|
|
||||||
Get the user name, Email and ID from the user object.
|
|
||||||
"""
|
|
||||||
|
|
||||||
# Do not include :param for __user__ in the docstring as it should not be shown in the tool's specification
|
|
||||||
# The session user object will be passed as a parameter when the function is called
|
|
||||||
|
|
||||||
print(__user__)
|
|
||||||
result = ""
|
|
||||||
|
|
||||||
if "name" in __user__:
|
|
||||||
result += f"User: {__user__['name']}"
|
|
||||||
if "id" in __user__:
|
|
||||||
result += f" (ID: {__user__['id']})"
|
|
||||||
if "email" in __user__:
|
|
||||||
result += f" (Email: {__user__['email']})"
|
|
||||||
|
|
||||||
if result == "":
|
|
||||||
result = "User: Unknown"
|
|
||||||
|
|
||||||
return result
|
|
||||||
|
|
||||||
def get_current_time(self) -> str:
|
|
||||||
"""
|
|
||||||
Get the current time in a more human-readable format.
|
|
||||||
:return: The current time.
|
|
||||||
"""
|
|
||||||
|
|
||||||
now = datetime.now()
|
|
||||||
current_time = now.strftime("%I:%M:%S %p") # Using 12-hour format with AM/PM
|
|
||||||
current_date = now.strftime(
|
|
||||||
"%A, %B %d, %Y"
|
|
||||||
) # Full weekday, month name, day, and year
|
|
||||||
|
|
||||||
return f"Current Date and Time = {current_date}, {current_time}"
|
|
||||||
|
|
||||||
def calculator(self, equation: str) -> str:
|
|
||||||
"""
|
|
||||||
Calculate the result of an equation.
|
|
||||||
:param equation: The equation to calculate.
|
|
||||||
"""
|
|
||||||
|
|
||||||
# Avoid using eval in production code
|
|
||||||
# https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html
|
|
||||||
try:
|
|
||||||
result = eval(equation)
|
|
||||||
return f"{equation} = {result}"
|
|
||||||
except Exception as e:
|
|
||||||
print(e)
|
|
||||||
return "Invalid equation"
|
|
||||||
|
|
||||||
def get_current_weather(self, city: str) -> str:
|
|
||||||
"""
|
|
||||||
Get the current weather for a given city.
|
|
||||||
:param city: The name of the city to get the weather for.
|
|
||||||
:return: The current weather information or an error message.
|
|
||||||
"""
|
|
||||||
api_key = os.getenv("OPENWEATHER_API_KEY")
|
|
||||||
if not api_key:
|
|
||||||
return (
|
|
||||||
"API key is not set in the environment variable 'OPENWEATHER_API_KEY'."
|
|
||||||
)
|
|
||||||
|
|
||||||
base_url = "http://api.openweathermap.org/data/2.5/weather"
|
|
||||||
params = {
|
|
||||||
"q": city,
|
|
||||||
"appid": api_key,
|
|
||||||
"units": "metric", # Optional: Use 'imperial' for Fahrenheit
|
|
||||||
}
|
|
||||||
|
|
||||||
try:
|
|
||||||
response = requests.get(base_url, params=params)
|
|
||||||
response.raise_for_status() # Raise HTTPError for bad responses (4xx and 5xx)
|
|
||||||
data = response.json()
|
|
||||||
|
|
||||||
if data.get("cod") != 200:
|
|
||||||
return f"Error fetching weather data: {data.get('message')}"
|
|
||||||
|
|
||||||
weather_description = data["weather"][0]["description"]
|
|
||||||
temperature = data["main"]["temp"]
|
|
||||||
humidity = data["main"]["humidity"]
|
|
||||||
wind_speed = data["wind"]["speed"]
|
|
||||||
|
|
||||||
return f"Weather in {city}: {temperature}°C"
|
|
||||||
except requests.RequestException as e:
|
|
||||||
return f"Error fetching weather data: {str(e)}"
|
|
||||||
`;
|
|
||||||
|
|
||||||
export const formatHandler = async () => {
|
|
||||||
if (codeEditor) {
|
|
||||||
return await codeEditor.formatPythonCodeHandler();
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
};
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<CodeEditor
|
|
||||||
bind:value
|
|
||||||
{boilerplate}
|
|
||||||
bind:this={codeEditor}
|
|
||||||
on:save={() => {
|
|
||||||
dispatch('save');
|
|
||||||
}}
|
|
||||||
/>
|
|
@ -3,7 +3,7 @@
|
|||||||
|
|
||||||
const i18n = getContext('i18n');
|
const i18n = getContext('i18n');
|
||||||
|
|
||||||
import CodeEditor from './CodeEditor.svelte';
|
import CodeEditor from '$lib/components/common/CodeEditor.svelte';
|
||||||
import { goto } from '$app/navigation';
|
import { goto } from '$app/navigation';
|
||||||
import ConfirmDialog from '$lib/components/common/ConfirmDialog.svelte';
|
import ConfirmDialog from '$lib/components/common/ConfirmDialog.svelte';
|
||||||
|
|
||||||
@ -28,6 +28,107 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
let codeEditor;
|
let codeEditor;
|
||||||
|
let boilerplate = `import os
|
||||||
|
import requests
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
|
||||||
|
class Tools:
|
||||||
|
def __init__(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Add your custom tools using pure Python code here, make sure to add type hints
|
||||||
|
# Use Sphinx-style docstrings to document your tools, they will be used for generating tools specifications
|
||||||
|
# Please refer to function_calling_filter_pipeline.py file from pipelines project for an example
|
||||||
|
|
||||||
|
def get_user_name_and_email_and_id(self, __user__: dict = {}) -> str:
|
||||||
|
"""
|
||||||
|
Get the user name, Email and ID from the user object.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Do not include :param for __user__ in the docstring as it should not be shown in the tool's specification
|
||||||
|
# The session user object will be passed as a parameter when the function is called
|
||||||
|
|
||||||
|
print(__user__)
|
||||||
|
result = ""
|
||||||
|
|
||||||
|
if "name" in __user__:
|
||||||
|
result += f"User: {__user__['name']}"
|
||||||
|
if "id" in __user__:
|
||||||
|
result += f" (ID: {__user__['id']})"
|
||||||
|
if "email" in __user__:
|
||||||
|
result += f" (Email: {__user__['email']})"
|
||||||
|
|
||||||
|
if result == "":
|
||||||
|
result = "User: Unknown"
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
|
def get_current_time(self) -> str:
|
||||||
|
"""
|
||||||
|
Get the current time in a more human-readable format.
|
||||||
|
:return: The current time.
|
||||||
|
"""
|
||||||
|
|
||||||
|
now = datetime.now()
|
||||||
|
current_time = now.strftime("%I:%M:%S %p") # Using 12-hour format with AM/PM
|
||||||
|
current_date = now.strftime(
|
||||||
|
"%A, %B %d, %Y"
|
||||||
|
) # Full weekday, month name, day, and year
|
||||||
|
|
||||||
|
return f"Current Date and Time = {current_date}, {current_time}"
|
||||||
|
|
||||||
|
def calculator(self, equation: str) -> str:
|
||||||
|
"""
|
||||||
|
Calculate the result of an equation.
|
||||||
|
:param equation: The equation to calculate.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Avoid using eval in production code
|
||||||
|
# https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html
|
||||||
|
try:
|
||||||
|
result = eval(equation)
|
||||||
|
return f"{equation} = {result}"
|
||||||
|
except Exception as e:
|
||||||
|
print(e)
|
||||||
|
return "Invalid equation"
|
||||||
|
|
||||||
|
def get_current_weather(self, city: str) -> str:
|
||||||
|
"""
|
||||||
|
Get the current weather for a given city.
|
||||||
|
:param city: The name of the city to get the weather for.
|
||||||
|
:return: The current weather information or an error message.
|
||||||
|
"""
|
||||||
|
api_key = os.getenv("OPENWEATHER_API_KEY")
|
||||||
|
if not api_key:
|
||||||
|
return (
|
||||||
|
"API key is not set in the environment variable 'OPENWEATHER_API_KEY'."
|
||||||
|
)
|
||||||
|
|
||||||
|
base_url = "http://api.openweathermap.org/data/2.5/weather"
|
||||||
|
params = {
|
||||||
|
"q": city,
|
||||||
|
"appid": api_key,
|
||||||
|
"units": "metric", # Optional: Use 'imperial' for Fahrenheit
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
response = requests.get(base_url, params=params)
|
||||||
|
response.raise_for_status() # Raise HTTPError for bad responses (4xx and 5xx)
|
||||||
|
data = response.json()
|
||||||
|
|
||||||
|
if data.get("cod") != 200:
|
||||||
|
return f"Error fetching weather data: {data.get('message')}"
|
||||||
|
|
||||||
|
weather_description = data["weather"][0]["description"]
|
||||||
|
temperature = data["main"]["temp"]
|
||||||
|
humidity = data["main"]["humidity"]
|
||||||
|
wind_speed = data["wind"]["speed"]
|
||||||
|
|
||||||
|
return f"Weather in {city}: {temperature}°C"
|
||||||
|
except requests.RequestException as e:
|
||||||
|
return f"Error fetching weather data: {str(e)}"
|
||||||
|
`;
|
||||||
|
|
||||||
const saveHandler = async () => {
|
const saveHandler = async () => {
|
||||||
loading = true;
|
loading = true;
|
||||||
@ -41,7 +142,7 @@
|
|||||||
|
|
||||||
const submitHandler = async () => {
|
const submitHandler = async () => {
|
||||||
if (codeEditor) {
|
if (codeEditor) {
|
||||||
const res = await codeEditor.formatHandler();
|
const res = await codeEditor.formatPythonCodeHandler();
|
||||||
|
|
||||||
if (res) {
|
if (res) {
|
||||||
console.log('Code formatted successfully');
|
console.log('Code formatted successfully');
|
||||||
@ -123,6 +224,7 @@
|
|||||||
<CodeEditor
|
<CodeEditor
|
||||||
bind:value={content}
|
bind:value={content}
|
||||||
bind:this={codeEditor}
|
bind:this={codeEditor}
|
||||||
|
{boilerplate}
|
||||||
on:save={() => {
|
on:save={() => {
|
||||||
if (formElement) {
|
if (formElement) {
|
||||||
formElement.requestSubmit();
|
formElement.requestSubmit();
|
||||||
|
Loading…
Reference in New Issue
Block a user