Package: taifun
Taifun - Typed AI FunctionsA simple framework for creating typed AI functions.
It inspects the function's docstring and parameters to provide functions for OpenAI's API.
You can either use theTaifunclass to create a dict of functions to pass to OpenAI's API or use theTaifunConversationRunnerclass to run a conversation with functions.InstallationpipinstalltaifunUsageInitialize a Taifun instance and decorate your functions with@taifun.fn()taifun=Taifun()@taifun.fn()defweather_forcast(location:str)->str:"""Get the weather forcast for a given locationParameters----------location: strthe user's location like a Ciry and State, e.g. San Francisco, CA"""returnf"The weather in{location}is rainy"Then you can use thefunctions_as_dictmethod to get a dict that can be passed to OpenAI's functions fieldfunctions=taifun.functions_as_dict()Then you can use thehandle_function_callmethod to handle a function call from OpenAI's APIfunctionsis a dict that can be passed to OpenAI's functions field[{"name":"weather_forcast","description":"Get the weather forcast for a given location","parameters":{"properties":{"location":{"description":"the user's location like a Ciry and State, e.g. San Francisco, CA","title":"Location","type":"string"}},"required":["location"],"title":"FunctionParameters","type":"object"}}]Pass functions to thefunctionsfield of OpenAI's APImessages=[...]result=openai.ChatCompletion.create(model="gpt-4",messages=messages,functions=functions,function_call="auto",)If the response from OpenAI's API has a function call, you can handle it withhandle_function_callfunction_call=result["choices"][0]["message"].get("function_call")iffunction_callisnotNone:# handle the function callfunction_response=taifun.handle_function_call(function_call)# return the function responsemessages.append({"role":"function","name":function_call["name"],"content":function_response,})# replyDemo with functions to pass to OpenAItaifun=Taifun()@taifun.fn()defweather_forcast(location:str)->str:"""Get the weather forcast for a given locationParameters----------location: strthe location to get the weather forcast for"""# random weatherweather=random.choice(["sunny","rainy","cloudy","snowy"])returnf"The weather in{location}is{weather}"messages=[{"role":"user","content":"Is it rainingy in berlin today?",},]# export functions as json schema dict for openaifunctions=taifun.functions_as_dict()result=openai.ChatCompletion.create(model="gpt-4",messages=messages,functions=functions,function_call="auto",)response_message=result["choices"][0]["message"]print(f"assistant:{response_message['content']}")function_call=response_message.get("function_call")messages.append(response_message)iffunction_callisnotNone:# handle the function callfunction_response=taifun.handle_function_call(function_call)# responed with the function responseprint(f"function response:{function_response}")messages.append({"role":"function","name":function_call["name"],"content":function_response,})result2=openai.ChatCompletion.create(model="gpt-4",messages=messages,functions=functions,function_call="auto",)response_message2=result2["choices"][0]["message"]print(f"assistant:{response_message2['content']}")A full example including the TaifunConversationRunnertaifun=Taifun()@taifun.fn()defget_location()->str:"""Get the user's locationreturns: the user's location like a Ciry and State, e.g. San Francisco, CA"""location=Prompt.ask("What is your location?")returnlocation@taifun.fn()defget_lang_lat(location:str)->dict:"""Get the latitude and longitude of a locationParameters----------location: strthe user's location like a Ciry and State, e.g. San Francisco, CA"""response=httpx.get(f"https://nominatim.openstreetmap.org/search/{urlparse.quote(location)}",params={"format":"json",},)response.raise_for_status()data=response.json()lat=data[0]["lat"]lng=data[0]["lon"]return{"latitute":lat,"longitude":lng}classCoordinates(BaseModel):latitude:float=Field(...,title="Latitude",description="The latitude of a location")longitude:float=Field(...,title="Longitude",description="The longitude of a location")@taifun.fn()defget_current_weather(coordinates:Coordinates):"""Get the current weather in a given longitude and latitudeParameters----------coordinates: Coordinatesthe latitude and longitude of a locationReturns:dict: a dictionary of the current weather"""response=httpx.get("https://api.open-meteo.com/v1/forecast",params={"latitude":coordinates.latitude,"longitude":coordinates.longitude,"current_weather":True,},)response.raise_for_status()data=response.json()returndataif__name__=="__main__":openai.api_key_path=os.path.expanduser("~")+"/.openai_api_key"runner=TaifunConversationRunner(taifun)result=runner.run("Will I need an umbrella today?")rich.print(result)