CodeEditor.svelte 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. <script lang="ts">
  2. import CodeEditor from '$lib/components/common/CodeEditor.svelte';
  3. import { createEventDispatcher } from 'svelte';
  4. const dispatch = createEventDispatcher();
  5. export let value = '';
  6. let codeEditor;
  7. let boilerplate = `import os
  8. import requests
  9. from datetime import datetime
  10. class Tools:
  11. def __init__(self):
  12. pass
  13. # Add your custom tools using pure Python code here, make sure to add type hints
  14. # Use Sphinx-style docstrings to document your tools, they will be used for generating tools specifications
  15. # Please refer to function_calling_filter_pipeline.py file from pipelines project for an example
  16. def get_environment_variable(self, variable_name: str) -> str:
  17. """
  18. Get the value of an environment variable.
  19. :param variable_name: The name of the environment variable.
  20. :return: The value of the environment variable or a message if it doesn't exist.
  21. """
  22. value = os.getenv(variable_name)
  23. if value is not None:
  24. return (
  25. f"The value of the environment variable '{variable_name}' is '{value}'"
  26. )
  27. else:
  28. return f"The environment variable '{variable_name}' does not exist."
  29. def get_current_time(self) -> str:
  30. """
  31. Get the current time.
  32. :return: The current time.
  33. """
  34. now = datetime.now()
  35. current_time = now.strftime("%H:%M:%S")
  36. return f"Current Time = {current_time}"
  37. def calculator(self, equation: str) -> str:
  38. """
  39. Calculate the result of an equation.
  40. :param equation: The equation to calculate.
  41. """
  42. # Avoid using eval in production code
  43. # https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html
  44. try:
  45. result = eval(equation)
  46. return f"{equation} = {result}"
  47. except Exception as e:
  48. print(e)
  49. return "Invalid equation"
  50. def get_current_weather(self, city: str) -> str:
  51. """
  52. Get the current weather for a given city.
  53. :param city: The name of the city to get the weather for.
  54. :return: The current weather information or an error message.
  55. """
  56. api_key = os.getenv("OPENWEATHER_API_KEY")
  57. if not api_key:
  58. return (
  59. "API key is not set in the environment variable 'OPENWEATHER_API_KEY'."
  60. )
  61. base_url = "http://api.openweathermap.org/data/2.5/weather"
  62. params = {
  63. "q": city,
  64. "appid": api_key,
  65. "units": "metric", # Optional: Use 'imperial' for Fahrenheit
  66. }
  67. try:
  68. response = requests.get(base_url, params=params)
  69. response.raise_for_status() # Raise HTTPError for bad responses (4xx and 5xx)
  70. data = response.json()
  71. if data.get("cod") != 200:
  72. return f"Error fetching weather data: {data.get('message')}"
  73. weather_description = data["weather"][0]["description"]
  74. temperature = data["main"]["temp"]
  75. humidity = data["main"]["humidity"]
  76. wind_speed = data["wind"]["speed"]
  77. return f"Weather in {city}: {temperature}°C"
  78. except requests.RequestException as e:
  79. return f"Error fetching weather data: {str(e)}"
  80. `;
  81. export const formatHandler = async () => {
  82. if (codeEditor) {
  83. return await codeEditor.formatPythonCodeHandler();
  84. }
  85. return false;
  86. };
  87. </script>
  88. <CodeEditor
  89. bind:value
  90. {boilerplate}
  91. bind:this={codeEditor}
  92. on:save={() => {
  93. dispatch('save');
  94. }}
  95. />