CodeEditor.svelte 3.74 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
refac  
Timothy J. Baek committed
23
24
25
26
27
28
29
30
    def get_environment_variable(self, variable_name: str) -> str:
        """
        Get the value of an environment variable.
        :param variable_name: The name of the environment variable.
        :return: The value of the environment variable or a message if it doesn't exist.
        """
        value = os.getenv(variable_name)
        if value is not None:
Timothy J. Baek's avatar
Timothy J. Baek committed
31
32
33
            return (
                f"The value of the environment variable '{variable_name}' is '{value}'"
            )
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
34
35
36
        else:
            return f"The environment variable '{variable_name}' does not exist."

Timothy J. Baek's avatar
Timothy J. Baek committed
37
38
    def get_current_time(self) -> str:
        """
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
39
        Get the current time in a more human-readable format.
Timothy J. Baek's avatar
Timothy J. Baek committed
40
41
42
43
        :return: The current time.
        """

        now = datetime.now()
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
44
45
46
47
48
49
        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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64

    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
65

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
66
67
68
69
70
71
    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
72
        api_key = os.getenv("OPENWEATHER_API_KEY")
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
73
        if not api_key:
Timothy J. Baek's avatar
Timothy J. Baek committed
74
75
76
            return (
                "API key is not set in the environment variable 'OPENWEATHER_API_KEY'."
            )
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
77
78
79

        base_url = "http://api.openweathermap.org/data/2.5/weather"
        params = {
Timothy J. Baek's avatar
Timothy J. Baek committed
80
81
82
            "q": city,
            "appid": api_key,
            "units": "metric",  # Optional: Use 'imperial' for Fahrenheit
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
83
84
85
86
87
88
        }

        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
89
90

            if data.get("cod") != 200:
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
91
                return f"Error fetching weather data: {data.get('message')}"
Timothy J. Baek's avatar
Timothy J. Baek committed
92
93
94
95
96
97
98

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

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
103
	export const formatHandler = async () => {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
104
		if (codeEditor) {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
105
			return await codeEditor.formatPythonCodeHandler();
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
106
		}
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
107
		return false;
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
108
	};
Timothy J. Baek's avatar
Timothy J. Baek committed
109
110
</script>

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
111
112
113
114
115
<CodeEditor
	bind:value
	{boilerplate}
	bind:this={codeEditor}
	on:save={() => {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
116
		dispatch('save');
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
117
118
	}}
/>