"""Methods for creating function specs in the style of Bedrock Functionsfor supported model providers"""importjsonfromtypingimport(Any,Callable,Dict,List,Literal,Optional,Union,cast,)fromlangchain_core.messagesimportToolCallfromlangchain_core.output_parsersimportBaseGenerationOutputParserfromlangchain_core.outputsimportChatGeneration,Generationfromlangchain_core.prompts.chatimportAIMessagefromlangchain_core.pydantic_v1importBaseModelfromlangchain_core.toolsimportBaseToolfromlangchain_core.utils.function_callingimportconvert_to_openai_toolfromlangchain_core.utils.pydanticimportTypeBaseModelfromtyping_extensionsimportTypedDictPYTHON_TO_JSON_TYPES={"str":"string","int":"integer","float":"number","bool":"boolean",}SYSTEM_PROMPT_FORMAT="""In this environment you have access to a set of tools you can use to answer the user's question.You may call them like this:<function_calls><invoke><tool_name>$TOOL_NAME</tool_name><parameters><$PARAMETER_NAME>$PARAMETER_VALUE</$PARAMETER_NAME>...</parameters></invoke></function_calls>Here are the tools available:<tools>{formatted_tools}</tools>"""# noqa: E501TOOL_FORMAT="""<tool_description><tool_name>{tool_name}</tool_name><description>{tool_description}</description><parameters>{formatted_parameters}</parameters></tool_description>"""TOOL_PARAMETER_FORMAT="""<parameter><name>{parameter_name}</name><type>{parameter_type}</type><description>{parameter_description}</description></parameter>"""
[docs]classFunctionDescription(TypedDict):"""Representation of a callable function to send to an LLM."""name:str"""The name of the function."""description:str"""A description of the function."""parameters:dict"""The parameters of the function."""
[docs]classToolDescription(TypedDict):"""Representation of a callable function to the OpenAI API."""type:Literal["function"]function:FunctionDescription
[docs]defparse_result(self,result:List[Generation],*,partial:bool=False)->Any:"""Parse a list of candidate model Generations into a specific format. Args: result: A list of Generations to be parsed. The Generations are assumed to be different candidate outputs for a single model input. Returns: Structured output. """if(notresultornotisinstance(result[0],ChatGeneration)ornotisinstance(result[0].message,AIMessage)ornotresult[0].message.tool_calls):returnNoneifself.first_tool_onlyelse[]tool_calls:Any=result[0].message.tool_callsifself.pydantic_schemas:tool_calls=[self._pydantic_parse(tc)fortcintool_calls]elifself.args_only:tool_calls=[tc["args"]fortcintool_calls]else:passifself.first_tool_only:returntool_calls[0]else:returntool_calls