通过拥抱人脸端点与 Mistral AI 进行函数调用

问题描述 投票:0回答:1

我正在尝试通过 Hugging Face 端点使用 Mistral AI 执行函数调用。 Mistral AI 需要以特定字符串格式输入(助手:... 用户:...)。但是,所提供的输入格式不被接受为消息列表或提示值(例如 ChatPromptTemplate)。使用字符串格式时,输出仅调用函数,而不将从工具调用中接收到的内容推送回 Mistral AI LLM。

我尝试使用 Mistral AI 执行函数调用,它最初按预期工作。我的流程涉及调用外部 API 来获取实时数据,然后尝试使用带有工具调用名称和 ID 的消息将此数据推送回 LLM(语言模型)。我希望最终的输出能够将我的数据与法学硕士的回答结合起来,从而得到一个有凝聚力的答案。然而,系统并没有得到预期的响应,而是不断返回函数调用作为响应。

# Import necessary libraries
from langchain_huggingface.chat_models import ChatHuggingFace
from langchain.prompts import PromptTemplate
from langchain.chains import RetrievalQA
from langchain.document_loaders import TextLoader
from langchain.llms import HuggingFacePipeline
from langchain_text_splitters.character import CharacterTextSplitter
from langchain.prompts import PromptTemplate
from langchain_core.pydantic_v1 import BaseModel, Field
from langchain_core.output_parsers.openai_tools import PydanticToolsParser
from langchain_huggingface import HuggingFaceEndpoint
from langchain_core.utils.function_calling import convert_to_openai_function
from langchain.prompts import PromptTemplate, ChatPromptTemplate
from langchain_core.messages import (
    HumanMessage,
    SystemMessage,
    AIMessage,
    ChatMessage
)
from dotenv import load_dotenv, find_dotenv
import os
import serpapi
import serpapi.client




# Load environment variables
_ = load_dotenv(find_dotenv())
serp_key = os.getenv('SERP_API_KEY')




# Configure the LLM endpoint
llm = HuggingFaceEndpoint(
    repo_id='mistralai/Mistral-7B-Instruct-v0.3',
    huggingfacehub_api_token='*********',
    task="text-generation",
    model_kwargs={
        "min_length": 200,
        "max_length": 2000,
        "num_return_sequences": 1
    },
    temperature=0.5
)



# Define prompt and functions
prompt_str = "I want you to act as travel organizer, Take input from user extract the necessary details plan the trip route using details you need to plan the route and time going to be spent"
functions = [
    {
        "name": "plan_holiday",
        "description": "Plan a holiday based on user's interests",
        "parameters": {
            "type": "object",
            "properties": {
                "destination": {
                    "type": "string",
                    "description": "The destination of the holiday",
                },
                "duration": {
                    "type": "integer",
                    "description": "The duration of the trip in holiday",
                },
            },
            "required": ["destination", "duration"],
        },
    }
]

# Generate messages
messages = [
    SystemMessage(content=prompt_str),
    HumanMessage(
        content="I am thinking of having a 12 day long vacation in Venice, can you help me plan it?"
    ),
]

# Format prompt
chat_pr = ChatPromptTemplate(messages=messages).format()
print(chat_pr)

# Create ChatHuggingFace model
chat_model = ChatHuggingFace(llm=llm)
functions = [convert_to_openai_function(i) for i in functions]

# Bind tools to the model
llm_with_holiday_planning = chat_model.bind_tools(functions, tool_choice='auto')

# Invoke the model with the formatted prompt
response = llm_with_holiday_planning.invoke(chat_pr)
print(response)

# Append response to messages
messages.append(ChatMessage(role='assistant', content='', tool_calls=response.additional_kwargs['tool_calls'], id=response.additional_kwargs['tool_calls'][0]['id']))

# Function to search Google for a place
def search_google_for(place_search):
    sero_cj = serpapi.Client(api_key=serp_key)
    result = sero_cj.search(
        params={
            "q": "Venice tourist places",
            "location": "India",
            "hl": "en",
            "gl": "In",
            "google_domain": "google.com",
        }
    )
    return result

# Fetch results using the function
results = search_google_for(response.additional_kwargs['tool_calls'][0].function['arguments'])
print(response.additional_kwargs['tool_calls'][0])

# Extract and compile information about places
info_about_places = ""
if results.get("organic_results"):
    for result in results["organic_results"]:
        title = result.get("title")
        snippet = result.get("snippet")
        link = result.get("link")
        info_about_places += snippet

# Append function result to messages
messages.append(ChatMessage(role='function', name=response.additional_kwargs['tool_calls'][0].function['name'], content=info_about_places, tool_call_id=response.additional_kwargs['tool_calls'][0]['id']))

# Format and invoke the updated prompt
chat_pr = ChatPromptTemplate(messages=messages).format()
print(chat_pr)
print(llm_with_holiday_planning.invoke(chat_pr))

设置环境:

加载必要的库和环境变量。 使用 Hugging Face API 配置 Mistral AI 模型端点。 定义提示和功能:

创建了一个提示,指示模型充当旅行组织者。 定义诸如 plan_holiday 之类的函数来处理特定任务。 生成消息:

使用 SystemMessage 和 HumanMessage 构造消息来模拟对话。 将工具绑定到模型:

将定义的函数转换为OpenAI兼容的格式。 使用bind_tools 将这些函数绑定到聊天模型。 调用模型:

尝试使用格式化提示调用模型,并期望它调用定义的函数并使用外部 API 数据。 预期结果: 我希望该模型能够处理函数调用,从外部 API 获取数据,并将这些数据与 LLM 生成的内容一起集成到一致的响应中。 实际结果: 该模型没有提供包含获取的数据和 LLM 生成的内容的组合响应,而是重复返回函数调用作为响应。

your text

artificial-intelligence large-language-model huggingface py-langchain mistral-7b
1个回答
0
投票

函数调用是一个强大但有些敏感的工作流程:

你可能认为这个过程是(这是不对的):

  1. 在您的计算机上:您提交提示
  2. 在 Huggingface 服务器中:LLM 将评估您的提示并决定使用的工具
  3. 在huggingface服务器中:LLM将调用您定义的方法来获取结果
  4. 在huggingface服务器中:LLM将考虑结果返回最终答案。

这是行不通的!仅仅因为你的Python方法

search_google_for()
以及它需要的库安装在你的计算机中并且永远不会上传到拥抱面部服务器,他们无法调用它。

真正的工作流程是:

  1. 在您的计算机上:您提交提示
  2. 在 Huggingface 服务器中:LLM 将评估您的提示并决定要使用的工具 并将其作为响应返回
  3. 在您的计算机上:您将解析响应并调用您定义的方法以获得结果
  4. 您将再次调用法学硕士,并在新一轮中获得结果
  5. 在huggingface服务器中:LLM将考虑结果返回最终答案。

Mistral AI 人员很好地解释了此工作流程 在此文档中

**希望你不需要自己实现这个**:LangChain 实现了工具调用代理来为你管理这个工作流程。看一下这个例子。希望有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.