赞
踩
本文介绍如何使用langchain中的ollama库实现低参数Llama 3,Phi-3模型实现本地函数调用及结构化文本输出。
函数调用的一个很好的参考是名为 “Gorilla” 的论文,该论文探讨了函数调用的概念,并提供了一个函数调用排行榜。通过这个排行榜,我们可以了解哪些模型擅长函数调用。
例如,我们可以看到 Llama 3 70 亿参数模型在排行榜中位列第七,而 8 亿参数的 Llama 3 模型也在榜单中,尽管性能不及前者,但仍然表现不错。
首先,我们来看一个简单的示例,设置 Llama 3 模型并使用 Ollama 进行函数调用。以下是相关代码:
from langchain import Ollama, ChatPromptTemplate, StringOutputParser
# 设置 Ollama 模型
llm = Ollama(model_name='llama3')
# 设置提示模板
prompt_template = ChatPromptTemplate.from_template("Write me a 500-word article on {topic} from the perspective of {profession}")
# 创建字符串输出解析器
output_parser = StringOutputParser()
# 调用模型生成文章
response = llm(prompt=prompt_template.format(topic="AI", profession="engineer"), output_parser=output_parser)
print(response)
在上述代码中,我们定义了一个简单的提示模板,并使用 Ollama 生成一个 500 字的文章。我们还可以通过设置 keep_alive
属性来保持模型在内存中的活跃状态,避免每次运行时重新加载模型。
接下来,我们来看如何让 Llama 3 模型生成结构化的 JSON 输出。以下是相关代码:
from langchain import JSONOutputParser # 定义 JSON 模式 json_schema = { "type": "object", "properties": { "name": {"type": "string"}, "age": {"type": "integer"}, "hobbies": {"type": "string"} }, "required": ["name", "age"] } # 设置提示模板 prompt_template = ChatPromptTemplate.from_template("Extract the following information in JSON format: {schema}") # 创建 JSON 输出解析器 output_parser = JSONOutputParser() # 调用模型生成 JSON response = llm(prompt=prompt_template.format(schema=json_schema), output_parser=output_parser) print(response)
在上述代码中,我们定义了一个 JSON 模式,并使用 Ollama 生成符合该模式的 JSON 输出。通过设置模型的输出格式为 JSON,可以提高生成结构化输出的概率。
我们还可以使用 Pydantic 定义一个类,用于提取结构化输出。以下是相关代码:
from pydantic import BaseModel from langchain import StructuredOutputLLM # 定义 Pydantic 类 class Person(BaseModel): name: str height: float hair_color: str # 设置提示模板 prompt_template = ChatPromptTemplate.from_template("Extract the following information in JSON format: {context}") # 创建结构化输出 LLM structured_llm = StructuredOutputLLM(llm, output_class=Person) # 调用模型生成结构化输出 context = "Alex is 5 feet tall, Claudia is 6 feet tall, Claudia has brown hair." response = structured_llm(prompt=prompt_template.format(context=context)) print(response)
在上述代码中,我们使用 Pydantic 定义了一个 Person
类,并使用 Ollama 生成符合该类的结构化输出。
最后,我们来看如何使用 Ollama 的新功能进行工具和函数调用。以下是相关代码:
from langchain import OllamaFunctions # 定义工具函数 def get_current_weather(location: str, unit: str = "Celsius"): # 这里是获取当前天气的实现 pass # 设置工具和函数调用 tools = {"get_current_weather": get_current_weather} ollama_functions = OllamaFunctions(llm, tools=tools) # 调用模型进行函数调用 question = "What is the weather in Singapore?" response = ollama_functions(prompt=question) print(response)
在上述代码中,我们定义了一个获取当前天气的工具函数,并使用 Ollama 进行函数调用。模型会根据输入的问题,自动调用相应的工具函数并返回结果。
通过以上示例,我们展示了如何在本地使用 Ollama 和 Llama 3 模型进行函数调用、生成 JSON 输出、定义结构化输出以及使用工具和函数调用。这些方法可以帮助我们在本地构建智能代理,而无需依赖云服务。
参考资料:
1.Function Calling with Local Models & LangChain - Ollama, Llama3 & Phi-3
2.论文:Gorilla: Large Language Model Connected with Massive APIs
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。