Skip to content

Commit 0d941ce

Browse files
committed
Added several new actions to support various workflows
1 parent e74747e commit 0d941ce

16 files changed

+479
-21
lines changed

‎.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,8 @@ ENV/
129129
env.bak/
130130
venv.bak/
131131

132+
assistant_outputs/
133+
132134
logs.txt
133135

134136
# Spyder project settings

‎btree.py

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
import threading
2+
import time
3+
4+
import py_trees
5+
6+
from playground.assistants_api import api
7+
8+
9+
# Define the ActionWithThread class
10+
class ActionWrapper(py_trees.behaviour.Behaviour):
11+
def __init__(self, name, action_function=None):
12+
super(ActionWrapper, self).__init__(name=name)
13+
self.thread = None
14+
self.thread_running = False
15+
self.thread_success = False
16+
self.action_function = action_function
17+
18+
def setup(self):
19+
# This is called once at the beginning to setup any necessary state or resources
20+
print("%s.setup()" % self.name)
21+
return py_trees.common.Status.SUCCESS
22+
23+
def initialise(self):
24+
# This is called once each time the behavior is started
25+
print("%s.initialise()" % self.name)
26+
self.thread_running = True
27+
self.thread_success = False
28+
self.thread = threading.Thread(target=self.long_running_process)
29+
self.thread.start()
30+
31+
def long_running_process(self):
32+
# Simulate a long-running process
33+
try:
34+
print("%s: Thread started, running process..." % self.name)
35+
result = self.action_function()
36+
print(result)
37+
self.thread_success = True
38+
print("%s: Thread completed successfully." % self.name)
39+
except Exception as e:
40+
print("%s: Exception in thread: %s" % (self.name, str(e)))
41+
finally:
42+
self.thread_running = False
43+
44+
def update(self):
45+
# This is called every tick to update the status of the behavior
46+
print("%s.update()" % self.name)
47+
if self.thread_running:
48+
return py_trees.common.Status.RUNNING
49+
else:
50+
return (
51+
py_trees.common.Status.SUCCESS
52+
if self.thread_success
53+
else py_trees.common.Status.FAILURE
54+
)
55+
56+
def terminate(self, new_status):
57+
# This is called once each time the behavior terminates
58+
print("%s.terminate(%s)" % (self.name, new_status))
59+
if self.thread is not None:
60+
self.thread.join()
61+
self.thread = None
62+
self.thread_running = False
63+
self.thread_success = False
64+
65+
66+
# Create the root node (sequence)
67+
root = py_trees.composites.Sequence("RootSequence", memory=True)
68+
69+
thread = api.create_thread()
70+
assistant = api.get_assistant_by_name("manager")
71+
message = "check the status of the thread, if there are no recent user messages, do nothing and return the word 'success'"
72+
73+
action_function = lambda: api.call_assistant_with_thread(thread, assistant.id, message)
74+
75+
# Create an instance of ActionWithThread and add it to the root node
76+
long_running_action = ActionWithThread(
77+
name="LongRunningAction", action_function=action_function
78+
)
79+
root.add_child(long_running_action)
80+
81+
# Create the behavior tree
82+
tree = py_trees.trees.BehaviourTree(root)
83+
84+
# Tick the tree to run it
85+
for i in range(100):
86+
print(f"Tick {i + 1}")
87+
tree.tick()
88+
time.sleep(5) # Simulate time between ticks
89+
90+
# Add a blackboard watcher to visualize the tree
91+
# py_trees.display.render_dot_tree(tree.root)

‎logs/logs.txt

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
Running on local URL: http://127.0.0.1:7860
2+
3+
To create a public link, set `share=True` in `launch()`.
4+
# >>> Code Interpreter
5+
import matplotlib.pyplot as plt
6+
import numpy as np
7+
8+
# Define the linear function
9+
def linear_function(x):
10+
return 3*x + 6
11+
12+
# Generate x values
13+
x = np.linspace(-10, 10, 400)
14+
# Generate y values
15+
y = linear_function(x)
16+
17+
# Create the plot
18+
plt.figure(figsize=(8, 6))
19+
plt.plot(x, y, label='y = 3x + 6', color='blue')
20+
plt.xlabel('x')
21+
plt.ylabel('y')
22+
plt.title('Plot of y = 3x + 6')
23+
plt.axhline(0, color='black',linewidth=0.5)
24+
plt.axvline(0, color='black',linewidth=0.5)
25+
plt.legend()
26+
plt.grid(True)
27+
plt.show()
28+
Output >
29+
assistant > File saved as assistant_outputs\file_20240526150025.png
30+
File saved as assistant_outputs\file_20240526150025.png

‎playground/assistant_actions/api_actions.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,31 @@ def list_uploaded_files(purpose="assistants"):
1717
return json.dumps(files)
1818

1919

20+
@agent_action
21+
def list_all_working_files():
22+
"""Lists all the uploaded files for the given purpose."""
23+
files = api.list_files(purpose=None).data
24+
files = [
25+
{"id": file.id, "filename": file.filename, "purpose": file.purpose}
26+
for file in files
27+
]
28+
return json.dumps(files)
29+
30+
31+
@agent_action
32+
def download_working_file_and_save(file_id, filename):
33+
"""Downloads the file with the given file_id and saves it with the given name."""
34+
if file_id is None:
35+
return "You must supply a file_id to download."
36+
37+
file = api.retrieve_file(file_id)
38+
if not file:
39+
return f"Unable to retrieve file with ID {file_id}."
40+
with open(filename, "wb") as f:
41+
f.write(file.content)
42+
return f"File with ID {file_id} downloaded and saved as {filename}."
43+
44+
2045
@agent_action
2146
def delete_uploaded_file(file_id):
2247
"""Deletes the uploaded file with the given file_id."""
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
from datetime import datetime
2+
3+
from playground.actions_manager import agent_action
4+
5+
6+
@agent_action
7+
def get_current_date_and_time():
8+
"""Returns the current date and time."""
9+
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
import os
2+
3+
from playground.actions_manager import agent_action
4+
5+
OUTPUT_FOLDER = "assistant_outputs"
6+
7+
8+
@agent_action
9+
def save_file(filename, content):
10+
"""
11+
Save content to a file.
12+
13+
:param filename: The name of the file including extension.
14+
:param content: The content to save in the file.
15+
"""
16+
file_path = os.path.join(OUTPUT_FOLDER, filename)
17+
with open(file_path, "w") as file:
18+
file.write(content)
19+
print(f"File '{filename}' saved successfully.")
20+
21+
22+
@agent_action
23+
def load_file(filename):
24+
"""
25+
Load content from a file.
26+
27+
:param filename: The name of the file including extension.
28+
:return: The content of the file.
29+
"""
30+
file_path = os.path.join(OUTPUT_FOLDER, filename)
31+
if not os.path.exists(file_path):
32+
print(f"File '{filename}' does not exist.")
33+
return None
34+
35+
with open(file_path, "r") as file:
36+
content = file.read()
37+
print(f"File '{filename}' loaded successfully.")
38+
return content
39+
40+
41+
@agent_action
42+
def delete_file(filename):
43+
"""
44+
Delete a file.
45+
46+
:param filename: The name of the file including extension.
47+
"""
48+
file_path = os.path.join(OUTPUT_FOLDER, filename)
49+
if os.path.exists(file_path):
50+
os.remove(file_path)
51+
print(f"File '{filename}' deleted successfully.")
52+
else:
53+
print(f"File '{filename}' does not exist.")
54+
55+
56+
@agent_action
57+
def create_folder(foldername):
58+
"""
59+
Create a folder.
60+
61+
:param foldername: The name of the folder to create.
62+
"""
63+
folder_path = os.path.join(OUTPUT_FOLDER, foldername)
64+
if not os.path.exists(folder_path):
65+
os.makedirs(folder_path)
66+
print(f"Folder '{foldername}' created successfully.")
67+
else:
68+
print(f"Folder '{foldername}' already exists.")
69+
70+
71+
# # Example usage:
72+
# if __name__ == "__main__":
73+
# # Save a file
74+
# save_file('example.txt', 'Hello, world!')
75+
76+
# # Load a file
77+
# content = load_file('example.txt')
78+
# print(content)
79+
80+
# # Delete a file
81+
# delete_file('example.txt')
82+
83+
# # Create a folder
84+
# create_folder('example_folder')
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
from pytrends.request import TrendReq
2+
3+
from playground.actions_manager import agent_action
4+
5+
6+
@agent_action
7+
def get_google_trend_data(keywords):
8+
"""Returns the Google trends trend data for the given keywords.
9+
keywords: list of keywords to search for.
10+
"""
11+
# Connect to Google
12+
pytrends = TrendReq(hl="en-US", tz=360)
13+
14+
if isinstance(keywords, str):
15+
if "," in keywords:
16+
keywords = keywords.split(",")
17+
else:
18+
keywords = [keywords]
19+
20+
# Define the keywords
21+
kw_list = keywords
22+
23+
# Build the payload
24+
pytrends.build_payload(kw_list, cat=0, timeframe="today 1-m", geo="", gprop="")
25+
26+
# Get interest over time
27+
interest_over_time_df = pytrends.interest_over_time()
28+
29+
return interest_over_time_df.to_string()

0 commit comments

Comments
 (0)