QuickstartΒΆ
This demonstration illustrates a straightforward way to utilize any Python function in your OpenAI calls as a function.
[1]:
import logging
import os
import openai
import itertools
from actionweaver.llms.openai.chat import OpenAIChatCompletion
from actionweaver.llms.openai.tokens import TokenUsageTracker
from actionweaver import action
openai.api_key = os.getenv("OPENAI_API_KEY")
[2]:
logging.basicConfig(
filename='agent.log',
filemode='a',
format='%(asctime)s.%(msecs)04d %(levelname)s {%(module)s} [%(funcName)s] %(message)s',
level=logging.INFO,
datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
[3]:
@action(name="GetCurrentTime")
def get_current_time() -> str:
"""
Use this for getting the current time in the specified time zone.
:return: A string representing the current time in the specified time zone.
"""
import datetime
current_time = datetime.datetime.now()
return f"The current time is {current_time}"
@action(name="Sleep")
def sleep(seconds: int) -> str:
"""
Introduces a sleep delay of the specified seconds and returns a message.
Args:
seconds (int): The duration to sleep in seconds.
Returns:
str: A message indicating the completion of the sleep.
"""
import time
time.sleep(seconds)
return f"Now I wake up after sleep {seconds} seconds."
[4]:
chat = OpenAIChatCompletion("gpt-3.5-turbo", token_usage_tracker = TokenUsageTracker(budget=2000, logger=logger), logger=logger)
[5]:
def print_output(output):
if type(output) == itertools._tee:
for chunk in output:
content = chunk.choices[0].delta.content
if content is not None:
print(content, end='')
else:
print (output)
print_output(chat.create([{"role": "user", "content": "what time is it ? "}], actions = [sleep, get_current_time], stream=True))
The current time is 11:07 AM.
[6]:
from pydantic import BaseModel
from actionweaver.actions.factories.pydantic_model_to_action import action_from_model
class User(BaseModel):
name: str
age: int
action_from_model(User).invoke(chat, [{"role": "user", "content": "Tom is 31 years old"}])
[6]:
User(name='Tom', age=31)
[ ]:
[ ]: