CodeEditor.svelte 3.9 KB
Newer Older
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
1
<script lang="ts">
Timothy J. Baek's avatar
Timothy J. Baek committed
2
	import CodeEditor from '$lib/components/common/CodeEditor.svelte';
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
3
4
5
	import { createEventDispatcher } from 'svelte';

	const dispatch = createEventDispatcher();
Timothy J. Baek's avatar
Timothy J. Baek committed
6
7
8

	export let value = '';

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
9
	let codeEditor;
Timothy J. Baek's avatar
Timothy J. Baek committed
10
	let boilerplate = `import os
Timothy J. Baek's avatar
Timothy J. Baek committed
11
import requests
Timothy J. Baek's avatar
Timothy J. Baek committed
12
13
from datetime import datetime

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
14

Timothy J. Baek's avatar
Timothy J. Baek committed
15
16
17
18
class Tools:
    def __init__(self):
        pass

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
19
20
21
22
    # 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

Timothy J. Baek's avatar
Timothy J. Baek committed
23
    def get_user_name_and_email_and_id(self, __user__: dict = {}) -> str:
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
24
        """
Timothy J. Baek's avatar
Timothy J. Baek committed
25
        Get the user name, Email and ID from the user object.
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
26
        """
Timothy J. Baek's avatar
Timothy J. Baek committed
27
28

        # Do not include :param for __user__ in the docstring as it should not be shown in the tool's documentation
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
29
        # The session user object will be passed as a parameter when the function is called
Timothy J. Baek's avatar
Timothy J. Baek committed
30
31
32
33
34
35
36
37

        print(__user__)
        result = ""

        if "name" in __user__:
            result += f"User: {__user__['name']}"
        if "id" in __user__:
            result += f" (ID: {__user__['id']})"
Timothy J. Baek's avatar
Timothy J. Baek committed
38
39
        if "email" in __user__:
            result += f" (Email: {__user__['email']})"
Timothy J. Baek's avatar
Timothy J. Baek committed
40
41
42
43
44

        if result == "":
            result = "User: Unknown"

        return result
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
45

Timothy J. Baek's avatar
Timothy J. Baek committed
46
47
    def get_current_time(self) -> str:
        """
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
48
        Get the current time in a more human-readable format.
Timothy J. Baek's avatar
Timothy J. Baek committed
49
50
51
52
        :return: The current time.
        """

        now = datetime.now()
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
53
54
55
56
57
58
        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}"
Timothy J. Baek's avatar
Timothy J. Baek committed
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73

    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"
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
74

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
75
76
77
78
79
80
    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.
        """
Timothy J. Baek's avatar
Timothy J. Baek committed
81
        api_key = os.getenv("OPENWEATHER_API_KEY")
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
82
        if not api_key:
Timothy J. Baek's avatar
Timothy J. Baek committed
83
84
85
            return (
                "API key is not set in the environment variable 'OPENWEATHER_API_KEY'."
            )
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
86
87
88

        base_url = "http://api.openweathermap.org/data/2.5/weather"
        params = {
Timothy J. Baek's avatar
Timothy J. Baek committed
89
90
91
            "q": city,
            "appid": api_key,
            "units": "metric",  # Optional: Use 'imperial' for Fahrenheit
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
92
93
94
95
96
97
        }

        try:
            response = requests.get(base_url, params=params)
            response.raise_for_status()  # Raise HTTPError for bad responses (4xx and 5xx)
            data = response.json()
Timothy J. Baek's avatar
Timothy J. Baek committed
98
99

            if data.get("cod") != 200:
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
100
                return f"Error fetching weather data: {data.get('message')}"
Timothy J. Baek's avatar
Timothy J. Baek committed
101
102
103
104
105
106
107

            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"
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
108
109
        except requests.RequestException as e:
            return f"Error fetching weather data: {str(e)}"
Timothy J. Baek's avatar
Timothy J. Baek committed
110
`;
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
111

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
112
	export const formatHandler = async () => {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
113
		if (codeEditor) {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
114
			return await codeEditor.formatPythonCodeHandler();
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
115
		}
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
116
		return false;
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
117
	};
Timothy J. Baek's avatar
Timothy J. Baek committed
118
119
</script>

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
120
121
122
123
124
<CodeEditor
	bind:value
	{boilerplate}
	bind:this={codeEditor}
	on:save={() => {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
125
		dispatch('save');
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
126
127
	}}
/>