Source code for langchain_experimental.llms.ollama_functions
importjsonimportuuidfromoperatorimportitemgetterfromtypingimport(Any,Callable,Dict,List,Optional,Sequence,Type,TypedDict,TypeVar,Union,)fromlangchain_community.chat_models.ollamaimportChatOllamafromlangchain_core._apiimportdeprecatedfromlangchain_core.callbacksimport(AsyncCallbackManagerForLLMRun,CallbackManagerForLLMRun,)fromlangchain_core.language_modelsimportLanguageModelInputfromlangchain_core.messagesimport(AIMessage,BaseMessage,ToolCall,)fromlangchain_core.output_parsers.baseimportOutputParserLikefromlangchain_core.output_parsers.jsonimportJsonOutputParserfromlangchain_core.output_parsers.pydanticimportPydanticOutputParserfromlangchain_core.outputsimportChatGeneration,ChatResultfromlangchain_core.promptsimportSystemMessagePromptTemplatefromlangchain_core.runnablesimportRunnable,RunnableLambdafromlangchain_core.runnables.baseimportRunnableMapfromlangchain_core.runnables.passthroughimportRunnablePassthroughfromlangchain_core.toolsimportBaseToolfromlangchain_core.utils.pydanticimportis_basemodel_instance,is_basemodel_subclassfrompydanticimport(BaseModel,)DEFAULT_SYSTEM_TEMPLATE="""You have access to the following tools:{tools}You must always select one of the above tools and respond with only a JSON object matching the following schema:{{ "tool": <name of the selected tool>, "tool_input": <parameters for the selected tool, matching the tool's JSON schema>}}"""# noqa: E501DEFAULT_RESPONSE_FUNCTION={"name":"__conversational_response","description":("Respond conversationally if no other tools should be called for a given query."),"parameters":{"type":"object","properties":{"response":{"type":"string","description":"Conversational response to the user.",},},"required":["response"],},}_BM=TypeVar("_BM",bound=BaseModel)_DictOrPydantic=Union[Dict,_BM]def_is_pydantic_class(obj:Any)->bool:returnisinstance(obj,type)and(is_basemodel_subclass(obj)orBaseModelinobj.__bases__)
[docs]defconvert_to_ollama_tool(tool:Any)->Dict:"""Convert a tool to an Ollama tool."""description=Noneif_is_pydantic_class(tool):schema=tool.model_construct().model_json_schema()name=schema["title"]elifisinstance(tool,BaseTool):schema=tool.tool_call_schema.model_json_schema()name=tool.get_name()description=tool.descriptionelifis_basemodel_instance(tool):schema=tool.get_input_schema().model_json_schema()name=tool.get_name()description=tool.descriptionelifisinstance(tool,dict)and"name"intooland"parameters"intool:returntool.copy()else:raiseValueError(f"""Cannot convert {tool} to an Ollama tool. {tool} needs to be a Pydantic class, model, or a dict.""")definition={"name":name,"parameters":schema}ifdescription:definition["description"]=descriptionreturndefinition
[docs]defparse_response(message:BaseMessage)->str:"""Extract `function_call` from `AIMessage`."""ifisinstance(message,AIMessage):kwargs=message.additional_kwargstool_calls=message.tool_callsiflen(tool_calls)>0:tool_call=tool_calls[-1]args=tool_call.get("args")returnjson.dumps(args)elif"function_call"inkwargs:if"arguments"inkwargs["function_call"]:returnkwargs["function_call"]["arguments"]raiseValueError(f"`arguments` missing from `function_call` within AIMessage: {message}")else:raiseValueError("`tool_calls` missing from AIMessage: {message}")raiseValueError(f"`message` is not an instance of `AIMessage`: {message}")
[docs]@deprecated(# type: ignore[arg-type]since="0.0.64",removal="1.0",alternative_import="langchain_ollama.ChatOllama")classOllamaFunctions(ChatOllama):"""Function chat model that uses Ollama API."""tool_system_prompt_template:str=DEFAULT_SYSTEM_TEMPLATEdef__init__(self,**kwargs:Any)->None:super().__init__(**kwargs)
[docs]defwith_structured_output(self,schema:Union[Dict,Type[BaseModel]],*,include_raw:bool=False,**kwargs:Any,)->Runnable[LanguageModelInput,Union[Dict,BaseModel]]:"""Model wrapper that returns outputs formatted to match the given schema. Args: schema: The output schema as a dict or a Pydantic class. If a Pydantic class then the model output will be an object of that class. If a dict then the model output will be a dict. With a Pydantic class the returned attributes will be validated, whereas with a dict they will not be. include_raw: If False then only the parsed structured output is returned. If an error occurs during model output parsing it will be raised. If True then both the raw model response (a BaseMessage) and the parsed model response will be returned. If an error occurs during output parsing it will be caught and returned as well. The final output is always a dict with keys "raw", "parsed", and "parsing_error". Returns: A Runnable that takes any ChatModel input and returns as output: If include_raw is True then a dict with keys: raw: BaseMessage parsed: Optional[_DictOrPydantic] parsing_error: Optional[BaseException] If include_raw is False then just _DictOrPydantic is returned, where _DictOrPydantic depends on the schema: If schema is a Pydantic class then _DictOrPydantic is the Pydantic class. If schema is a dict then _DictOrPydantic is a dict. Example: Pydantic schema (include_raw=False): .. code-block:: python from langchain_experimental.llms import OllamaFunctions from pydantic import BaseModel class AnswerWithJustification(BaseModel): '''An answer to the user question along with justification for the answer.''' answer: str justification: str llm = OllamaFunctions(model="phi3", format="json", temperature=0) structured_llm = llm.with_structured_output(AnswerWithJustification) structured_llm.invoke("What weighs more a pound of bricks or a pound of feathers") # -> AnswerWithJustification( # answer='They weigh the same', # justification='Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume or density of the objects may differ.' # ) Example: Pydantic schema (include_raw=True): .. code-block:: python from langchain_experimental.llms import OllamaFunctions from pydantic import BaseModel class AnswerWithJustification(BaseModel): '''An answer to the user question along with justification for the answer.''' answer: str justification: str llm = OllamaFunctions(model="phi3", format="json", temperature=0) structured_llm = llm.with_structured_output(AnswerWithJustification, include_raw=True) structured_llm.invoke("What weighs more a pound of bricks or a pound of feathers") # -> { # 'raw': AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_Ao02pnFYXD6GN1yzc0uXPsvF', 'function': {'arguments': '{"answer":"They weigh the same.","justification":"Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume or density of the objects may differ."}', 'name': 'AnswerWithJustification'}, 'type': 'function'}]}), # 'parsed': AnswerWithJustification(answer='They weigh the same.', justification='Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume or density of the objects may differ.'), # 'parsing_error': None # } Example: dict schema (method="include_raw=False): .. code-block:: python from langchain_experimental.llms import OllamaFunctions, convert_to_ollama_tool from pydantic import BaseModel class AnswerWithJustification(BaseModel): '''An answer to the user question along with justification for the answer.''' answer: str justification: str dict_schema = convert_to_ollama_tool(AnswerWithJustification) llm = OllamaFunctions(model="phi3", format="json", temperature=0) structured_llm = llm.with_structured_output(dict_schema) structured_llm.invoke("What weighs more a pound of bricks or a pound of feathers") # -> { # 'answer': 'They weigh the same', # 'justification': 'Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume and density of the two substances differ.' # } """# noqa: E501ifkwargs:raiseValueError(f"Received unsupported arguments {kwargs}")is_pydantic_schema=_is_pydantic_class(schema)ifschemaisNone:raiseValueError("schema must be specified when method is 'function_calling'. ""Received None.")llm=self.bind_tools(tools=[schema],format="json")ifis_pydantic_schema:output_parser:OutputParserLike=PydanticOutputParser(# type: ignore[type-var]pydantic_object=schema# type: ignore[arg-type])else:output_parser=JsonOutputParser()parser_chain=RunnableLambda(parse_response)|output_parserifinclude_raw:parser_assign=RunnablePassthrough.assign(parsed=itemgetter("raw")|parser_chain,parsing_error=lambda_:None)parser_none=RunnablePassthrough.assign(parsed=lambda_:None)parser_with_fallback=parser_assign.with_fallbacks([parser_none],exception_key="parsing_error")returnRunnableMap(raw=llm)|parser_with_fallbackelse:returnllm|parser_chain
def_generate(self,messages:List[BaseMessage],stop:Optional[List[str]]=None,run_manager:Optional[CallbackManagerForLLMRun]=None,**kwargs:Any,)->ChatResult:functions=kwargs.get("functions",[])if"functions"inkwargs:delkwargs["functions"]if"function_call"inkwargs:functions=[fnforfninfunctionsiffn["name"]==kwargs["function_call"]["name"]]ifnotfunctions:raiseValueError("If `function_call` is specified, you must also pass a ""matching function in `functions`.")delkwargs["function_call"]functions=[convert_to_ollama_tool(fn)forfninfunctions]functions.append(DEFAULT_RESPONSE_FUNCTION)system_message_prompt_template=SystemMessagePromptTemplate.from_template(self.tool_system_prompt_template)system_message=system_message_prompt_template.format(tools=json.dumps(functions,indent=2))response_message=super()._generate([system_message]+messages,stop=stop,run_manager=run_manager,**kwargs)chat_generation_content=response_message.generations[0].textifnotisinstance(chat_generation_content,str):raiseValueError("OllamaFunctions does not support non-string output.")try:parsed_chat_result=json.loads(chat_generation_content)exceptjson.JSONDecodeError:raiseValueError(f"""'{self.model}' did not respond with valid JSON. Please try again. Response: {chat_generation_content}""")called_tool_name=(parsed_chat_result["tool"]if"tool"inparsed_chat_resultelseNone)called_tool=next((fnforfninfunctionsiffn["name"]==called_tool_name),None)if(called_toolisNoneorcalled_tool["name"]==DEFAULT_RESPONSE_FUNCTION["name"]):if("tool_input"inparsed_chat_resultand"response"inparsed_chat_result["tool_input"]):response=parsed_chat_result["tool_input"]["response"]elif"response"inparsed_chat_result:response=parsed_chat_result["response"]else:raiseValueError(f"Failed to parse a response from {self.model} output: "f"{chat_generation_content}")returnChatResult(generations=[ChatGeneration(message=AIMessage(content=response,))])called_tool_arguments=(parsed_chat_result["tool_input"]if"tool_input"inparsed_chat_resultelse{})response_message_with_functions=AIMessage(content="",tool_calls=[ToolCall(name=called_tool_name,args=called_tool_argumentsifcalled_tool_argumentselse{},id=f"call_{str(uuid.uuid4()).replace('-','')}",)],)returnChatResult(generations=[ChatGeneration(message=response_message_with_functions)])asyncdef_agenerate(self,messages:List[BaseMessage],stop:Optional[List[str]]=None,run_manager:Optional[AsyncCallbackManagerForLLMRun]=None,**kwargs:Any,)->ChatResult:functions=kwargs.get("functions",[])if"functions"inkwargs:delkwargs["functions"]if"function_call"inkwargs:functions=[fnforfninfunctionsiffn["name"]==kwargs["function_call"]["name"]]ifnotfunctions:raiseValueError("If `function_call` is specified, you must also pass a ""matching function in `functions`.")delkwargs["function_call"]elifnotfunctions:functions.append(DEFAULT_RESPONSE_FUNCTION)if_is_pydantic_class(functions[0]):functions=[convert_to_ollama_tool(fn)forfninfunctions]system_message_prompt_template=SystemMessagePromptTemplate.from_template(self.tool_system_prompt_template)system_message=system_message_prompt_template.format(tools=json.dumps(functions,indent=2))response_message=awaitsuper()._agenerate([system_message]+messages,stop=stop,run_manager=run_manager,**kwargs)chat_generation_content=response_message.generations[0].textifnotisinstance(chat_generation_content,str):raiseValueError("OllamaFunctions does not support non-string output.")try:parsed_chat_result=json.loads(chat_generation_content)exceptjson.JSONDecodeError:raiseValueError(f"""'{self.model}' did not respond with valid JSON. Please try again. Response: {chat_generation_content}""")called_tool_name=parsed_chat_result["tool"]called_tool_arguments=parsed_chat_result["tool_input"]called_tool=next((fnforfninfunctionsiffn["name"]==called_tool_name),None)ifcalled_toolisNone:raiseValueError(f"Failed to parse a function call from {self.model} output: "f"{chat_generation_content}")ifcalled_tool["name"]==DEFAULT_RESPONSE_FUNCTION["name"]:returnChatResult(generations=[ChatGeneration(message=AIMessage(content=called_tool_arguments["response"],))])response_message_with_functions=AIMessage(content="",additional_kwargs={"function_call":{"name":called_tool_name,"arguments":json.dumps(called_tool_arguments)ifcalled_tool_argumentselse"",},},)returnChatResult(generations=[ChatGeneration(message=response_message_with_functions)])@propertydef_llm_type(self)->str:return"ollama_functions"