CodeEditor.svelte 3.79 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_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 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
29
30
31
32
33
34
35
36
37
38
39
40
41
42

        # Do not include :param for __user__ in the docstring as it should not be shown in the tool's documentation
        # The 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 result == "":
            result = "User: Unknown"

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

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

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

    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
72

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

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

        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
96
97

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

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

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

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