Action Orchestration
In this example, we will demonstrate how to use ActionWeaver to orchestrate the design of hierarchies and chains of action.
Keep in mind that orchestration is limited to a single action invoked per API call. If multiple actions are invoked, same set of actions will be available to LLM again
[2]:
import os
import openai
from openai import OpenAI
openai.api_key = os.getenv("OPENAI_API_KEY")
Patch OpenAI client
[3]:
from actionweaver.llms import wrap
openai_client = wrap(OpenAI())
Define function you want model to invoke
[4]:
from actionweaver import action
from typing import List
@action(name="FileHandler")
def handle_file(instruction: str) -> str:
"""
Handles user instructions related to file operations. Put every context in the instruction only!
Args:
instruction (str): The user's instruction about file handling.
Returns:
str: The response to the user's question.
"""
print ("Handling file...")
return instruction
@action(name="ListFiles")
def list_all_files_in_repo(repo_path: str ='.') -> List:
"""
Lists all the files in the given repository.
:param repo_path: Path to the repository. Defaults to the current directory.
:return: List of file paths.
"""
print (f"List all files in {repo_path}...")
file_list = []
for root, _, files in os.walk(repo_path):
for file in files:
file_list.append(os.path.join(root, file))
break
return file_list
@action(name="ReadFile")
def read_from_file(file_path: str) -> str:
"""
Reads the content of a file and returns it as a string.
:param file_path: The path to the file that needs to be read.
:return: A string containing the content of the file.
"""
print (f"Read file from {file_path}")
with open(file_path, 'r') as file:
content = file.read()
return f"The file content: \n{content}"
Build a hierarchy of actions
Once FileHandler invoked by LLM, LLM can access actions from ListFiles, ReadFile, or reply with a message.
FileHandler
|
|-- ListFiles
|
|-- ReadFile
[12]:
response = openai_client.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": "list all files"}],
actions = [handle_file],
orch = {
handle_file.name: [read_from_file, list_all_files_in_repo]
},
stream=False,
)
Handling file...
List all files in ....