使用Ollama、Llama 3.2和Milvus进行函数调用

2024年10月14日 由 alex 发表 29 0

使用 LLM 进行函数调用,就好比赋予人工智能与世界连接的能力。通过将 LLM 与用户自定义函数或 API 等外部工具集成,你可以构建能解决实际问题的应用程序。


在本文中,我们将介绍如何将 Llama 3.2 与 Milvus 和 API 等外部工具集成,以构建强大的上下文感知应用程序。


函数调用简介

GPT-4、Mistral Nemo 和 Llama 3.2 等 LLM 现在可以检测何时需要调用函数,然后输出带有参数的 JSON 来调用该函数。这将使你的人工智能应用更加灵活和强大。


功能调用使开发人员能够创建:

  • 由 LLM 驱动的用于提取和标记数据的解决方案(例如,从维基百科文章中提取人名)
  • 可帮助将自然语言转换为 API 调用或有效数据库查询的应用程序
  • 与知识库交互的会话知识检索引擎


工具

  • Ollama:将 LLM 的强大功能带到你的笔记本电脑上,简化本地操作。
  • Milvus:我们的矢量数据库,用于高效数据存储和检索。
  • Llama 3.2-3B:3.1 模型的升级版本,支持多种语言,上下文长度大幅延长至 128K,并可充分利用工具的使用。


2


使用 Llama 3.2 和 Ollama

Llama 3.2 对函数调用进行了微调。它支持单次、嵌套和并行函数调用,以及多轮函数调用。这意味着你的人工智能可以处理涉及多个步骤或并行流程的复杂任务。


在我们的示例中,我们将实现不同的函数来模拟 API 调用,以获取航班时间并在 Milvus 中执行搜索。Llama 3.2 将根据用户的查询决定调用哪个函数。


安装依赖项

首先,让我们做好一切准备。使用 Ollama 下载 Llama 3.2:


ollama run llama3.2


这将把模型下载到你的笔记本电脑,使其可以与 Ollama 一起使用。接下来,安装必要的依赖项:


! pip install ollama openai "pymilvus[model]"


我们在安装 Milvus Lite 时使用了模型扩展,它允许你使用 Milvus 中可用的模型嵌入数据。


将数据插入 Milvus

现在,让我们在 Milvus 中插入一些数据。如果 Llama 3.2 认为这些数据是相关的,它稍后就会决定搜索这些数据!


创建并插入数据


from pymilvus import MilvusClient, model
embedding_fn = model.DefaultEmbeddingFunction()
docs = [
    "Artificial intelligence was founded as an academic discipline in 1956.",
    "Alan Turing was the first person to conduct substantial research in AI.",
    "Born in Maida Vale, London, Turing was raised in southern England.",
]
vectors = embedding_fn.encode_documents(docs)
# The output vector has 768 dimensions, matching the collection that we just created.
print("Dim:", embedding_fn.dim, vectors[0].shape)  # Dim: 768 (768,)
# Each entity has id, vector representation, raw text, and a subject label.
data = [
    {"id": i, "vector": vectors[i], "text": docs[i], "subject": "history"}
    for i in range(len(vectors))
]
print("Data has", len(data), "entities, each with fields: ", data[0].keys())
print("Vector dim:", len(data[0]["vector"]))
# Create a collection and insert the data
client = MilvusClient('./milvus_local.db')
client.create_collection(
    collection_name="demo_collection",
    dimension=768,  # The vectors we will use in this demo has 768 dimensions
)
client.insert(collection_name="demo_collection", data=data)


这样,你的新集合中就会有 3 个元素。


定义要使用的函数

在本例中,我们要定义两个函数。第一个函数模拟 API 调用,以获取航班时间。第二个函数在 Milvus 中运行搜索查询。


from pymilvus import model
import json
import ollama
embedding_fn = model.DefaultEmbeddingFunction()
# Simulates an API call to get flight times
# In a real application, this would fetch data from a live database or API
def get_flight_times(departure: str, arrival: str) -> str:
    flights = {
        'NYC-LAX': {'departure': '08:00 AM', 'arrival': '11:30 AM', 'duration': '5h 30m'},
        'LAX-NYC': {'departure': '02:00 PM', 'arrival': '10:30 PM', 'duration': '5h 30m'},
        'LHR-JFK': {'departure': '10:00 AM', 'arrival': '01:00 PM', 'duration': '8h 00m'},
        'JFK-LHR': {'departure': '09:00 PM', 'arrival': '09:00 AM', 'duration': '7h 00m'},
        'CDG-DXB': {'departure': '11:00 AM', 'arrival': '08:00 PM', 'duration': '6h 00m'},
        'DXB-CDG': {'departure': '03:00 AM', 'arrival': '07:30 AM', 'duration': '7h 30m'},
    }
    key = f'{departure}-{arrival}'.upper()
    return json.dumps(flights.get(key, {'error': 'Flight not found'}))
# Search data related to Artificial Intelligence in a vector database
def search_data_in_vector_db(query: str) -> str:
    query_vectors = embedding_fn.encode_queries([query])
    res = client.search(
        collection_name="demo_collection",
        data=query_vectors,
        limit=2,
        output_fields=["text", "subject"],  # specifies fields to be returned
    )
    print(res)
    return json.dumps(res)


向 LLM 提供使用这些功能的说明

现在,让我们给 LLM 下达指令,使它能够使用我们定义的函数。


def run(model: str, question: str):
    client = ollama.Client()
    # Initialize conversation with a user query
    messages = [{"role": "user", "content": question}]
    # First API call: Send the query and function description to the model
    response = client.chat(
        model=model,
        messages=messages,
        tools=[
            {
                "type": "function",
                "function": {
                    "name": "get_flight_times",
                    "description": "Get the flight times between two cities",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "departure": {
                                "type": "string",
                                "description": "The departure city (airport code)",
                            },
                            "arrival": {
                                "type": "string",
                                "description": "The arrival city (airport code)",
                            },
                        },
                        "required": ["departure", "arrival"],
                    },
                },
            },
            {
                "type": "function",
                "function": {
                    "name": "search_data_in_vector_db",
                    "description": "Search about Artificial Intelligence data in a vector database",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "query": {
                                "type": "string",
                                "description": "The search query",
                            },
                        },
                        "required": ["query"],
                    },
                },
            },
        ],
    )
    # Add the model's response to the conversation history
    messages.append(response["message"])
    # Check if the model decided to use the provided function
    if not response["message"].get("tool_calls"):
        print("The model didn't use the function. Its response was:")
        print(response["message"]["content"])
        return
    # Process function calls made by the model
    if response["message"].get("tool_calls"):
        available_functions = {
            "get_flight_times": get_flight_times,
            "search_data_in_vector_db": search_data_in_vector_db,
        }
        for tool in response["message"]["tool_calls"]:
            function_to_call = available_functions[tool["function"]["name"]]
            function_args = tool["function"]["arguments"]
            function_response = function_to_call(**function_args)
            # Add function response to the conversation
            messages.append(
                {
                    "role": "tool",
                    "content": function_response,
                }
            )
    # Second API call: Get final response from the model
    final_response = client.chat(model=model, messages=messages)
    print(final_response["message"]["content"])


使用示例

让我们检查一下能否获取特定航班的时间:


question = "What is the flight time from New York (NYC) to Los Angeles (LAX)?"
run('llama3.2', question)


结果是:


The flight time from New York (JFK/LGA/EWR) to Los Angeles (LAX) is approximately 5 hours and 30 minutes. However, please note that this time may vary depending on the airline, flight schedule, and any potential layovers or delays. It's always best to check with your airline for the most up-to-date and accurate flight information.


现在,让我们看看 Llama 3.2 能否使用 Milvus 进行矢量搜索。


question = "When was Artificial Intelligence founded?"
run("llama3.2", question)


返回 Milvus 搜索:


data: ["[{'id': 0, 'distance': 0.5738513469696045, 'entity': {'text': 'Artificial intelligence was founded as an academic discipline in 1956.', 'subject': 'history'}}, {'id': 1, 'distance': 0.4090226888656616, 'entity': {'text': 'Alan Turing was the first person to conduct substantial research in AI.', 'subject': 'history'}}]"] 
Artificial Intelligence was founded as an academic discipline in 1956.


结论

使用 LLM 的函数调用开辟了一个充满可能性的世界。通过将 Llama 3.2 与 Milvus 和 API 等外部工具集成,你可以构建功能强大的上下文感知应用程序,以满足特定用例和实际问题的需要。

文章来源:https://medium.com/@zilliz_learn/function-calling-with-ollama-llama-3-2-and-milvus-ac2bc2122538
欢迎关注ATYUN官方公众号
商务合作及内容投稿请联系邮箱:bd@atyun.com
评论 登录
热门职位
Maluuba
20000~40000/月
Cisco
25000~30000/月 深圳市
PilotAILabs
30000~60000/年 深圳市
写评论取消
回复取消