自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

使用本地部署的Hermes 2 Pro構(gòu)建開放的LLM應(yīng)用程序

譯文
人工智能
本文介紹了如何使用基于Meta Llama 3架構(gòu)的功能強(qiáng)大的大語(yǔ)言模型(LLM)Hermes 2 Pro-Llama- 3 8B進(jìn)行函數(shù)調(diào)用,并在Hugging Face上運(yùn)行。

譯者 | 布加迪

審校 | 重樓

之前我介紹了如何使用OpenAI最新的LLM GPT-4o,通過函數(shù)調(diào)用將實(shí)時(shí)數(shù)據(jù)引入到LLM。在這篇后續(xù)文章中我將介紹使用Hermes 2 Pro -Llama- 3 8B進(jìn)行函數(shù)調(diào)用,這是一Nous Research開發(fā)的功能強(qiáng)大的LLM,基于MetaLlama 3架構(gòu),有80億個(gè)參數(shù)。它是開放模型,我們將在Hugging Face的文本生成推理上運(yùn)行它。

我們將把Fightaware.comAPI LLM集成起來,以便實(shí)時(shí)跟蹤航班狀態(tài)。

FlightAwareAeroAPI是開發(fā)人員獲取全面航班信息的一種完美工具。它支持實(shí)時(shí)航班跟蹤、歷史和未來航班數(shù)據(jù)以及按各種標(biāo)準(zhǔn)進(jìn)行航班搜索。該API以用戶友好的JSON格式呈現(xiàn)數(shù)據(jù),因而高度可用、易于集成。我們將調(diào)用REST API,根據(jù)用戶發(fā)送給LLM的提示獲取航班的實(shí)時(shí)狀態(tài)。

Hermes 2 Pro簡(jiǎn)介

Hermes 2 Pro -Llama- 3 8B擅長(zhǎng)自然語(yǔ)言處理任務(wù)、創(chuàng)意寫作和編程協(xié)助等。它的一項(xiàng)突出功能是出色的函數(shù)調(diào)用功能,便于執(zhí)行外部函數(shù),并檢索與股票價(jià)格、公司基本面、財(cái)務(wù)報(bào)表等相關(guān)的信息。

該模型利用特殊的系統(tǒng)提示和多輪函數(shù)調(diào)用結(jié)構(gòu)以及新的ChatML角色,使得函數(shù)調(diào)用可靠且易于解析。據(jù)基準(zhǔn)測(cè)試顯示,Hermes 2 Pro-Llama-3在與Fireworks AI合作構(gòu)建的函數(shù)調(diào)用評(píng)估中獲得了出色90%。

本地部署Hermes 2 Pro

這個(gè)環(huán)境而言,我使用一臺(tái)基于英偉達(dá)GeForce RTX 4090 GPULinux服務(wù)器,搭載24GBVRAM。它運(yùn)行Docker英偉達(dá)容器工具包,使容器能夠訪問GPU

我們將使用來自Hugging Face的文本生成推理服務(wù)器來運(yùn)行Hermes 2 Pro。

下面的命令在端口8080上啟動(dòng)推理引擎,通過REST端點(diǎn)為L(zhǎng)LM提供服務(wù)。

export token="YOUR_HF_TOKEN"
 
export model="NousResearch/Hermes-2-Pro-Llama-3-8B"
 
export volume="/home/ubuntu/data"
 
docker run --name hermes -d --gpus all -e HUGGING_FACE_HUB_TOKEN=$token --shm-size 1g -p 8080:80 -v $volume:/data ghcr.io/huggingface/text-generation-inference:2.0.3 --model-id $model --max-total-tokens 8096

   	
To test the endpoint, run the following command:

	curl 127.0.0.1:8081  \
  -X POST \
   -H 'Content-Type: application/json' \
 -d '{"inputs":"What is Deep Learning?"}'

如果一切正常,您應(yīng)該看到Hermes 2 Pro的響應(yīng)。

跟蹤航班狀態(tài)的函數(shù)

在繼續(xù)下一步之前,注冊(cè)FlightAware并獲取API密鑰,使用REST API需要API密鑰。免費(fèi)的個(gè)人版本足以完成本教程。

獲得API密鑰后,Python創(chuàng)建以下函數(shù),以檢索任何航班的狀態(tài)。

	import ast
	import json
import random
	from datetime import datetime, timedelta
	import requests
	import pytz

	
	def get_flight_status(flight):
	    """Returns Flight Information"""
	

	    AEROAPI_BASE_URL = "https://aeroapi.flightaware.com/aeroapi"
	    AEROAPI_KEY="YOUR FLIGHTAWARE API KEY"
	    
	    def get_api_session():
	        session = requests.Session()
	        session.headers.update({"x-apikey": AEROAPI_KEY})
	        return session
	
	    
def fetch_flight_data(flight_id, session):
	        if "flight_id=" in flight_id:
	            flight_id = flight_id.split("flight_id=")[1]    
	        
	       
 start_date = datetime.now().date().strftime('%Y-%m-%d')
	        end_date = (datetime.now().date() + timedelta(days=1)).strftime('%Y-%m-%d')
	        api_resource = f"/flights/{flight_id}?start={start_date}&end={end_date}"
	        response = session.get(f"{AEROAPI_BASE_URL}{api_resource}")
	        response.raise_for_status()
	        return response.json()['flights'][0]
	
	    def utc_to_local(utc_date_str, local_timezone_str):
	        utc_datetime = datetime.strptime(utc_date_str, '%Y-%m-%dT%H:%M:%SZ').replace(tzinfo=pytz.utc)
	        local_timezone = pytz.timezone(local_timezone_str)
	        local_datetime = utc_datetime.astimezone(local_timezone)
	        return local_datetime.strftime('%Y-%m-%d %H:%M:%S')    
	    
	    session = get_api_session()
	    flight_data = fetch_flight_data(flight, session)
	    
	    dep_key = 'estimated_out' if 'estimated_out' in flight_data and flight_data['estimated_out'] else \
	          'actual_out' if 'actual_out' in flight_data and flight_data['actual_out'] else \
	          'scheduled_out'
	    
	    arr_key = 'estimated_in' if 'estimated_in' in flight_data and flight_data['estimated_in'] else \
	          'actual_in' if 'actual_in' in flight_data and flight_data['actual_in'] else \
	          'scheduled_in'    
	    
	    flight_details = {
	        'flight':flight,
	        'source': flight_data['origin']['city'],
	        'destination': flight_data['destination']['city'],
	        'depart_time': utc_to_local(flight_data[dep_key], flight_data['origin']['timezone']),
	        'arrival_time': utc_to_local(flight_data[arr_key], flight_data['destination']['timezone']),
	        'status': flight_data['status']
	    }
	return json.dumps(flight_details)

	
	flight_info = get_flight_status("EK524")
	print(flight_info)
	#'{"flight": "EK524", "source": "Dubai", "destination": "Hyderabad", "depart_time": "2024-05-23 22:00:00", "arrival_time": "2024-05-24 03:05:00", "status": "Scheduled"}'

雖然代碼簡(jiǎn)單直觀,還是讓我解釋關(guān)鍵步驟。

get_flight_status函數(shù)接受航班參數(shù)假設(shè)是航班標(biāo)識(shí)符,并以JSON格式返回格式化的航班詳細(xì)信息。它查詢AeroAPI以根據(jù)特定的航班標(biāo)識(shí)符獲取航班數(shù)據(jù),并格式化關(guān)鍵細(xì)節(jié),比如、目的地、駛離時(shí)間、到達(dá)時(shí)間和狀態(tài)。

不妨看看腳本的組件:

API憑據(jù):

AEROAPI_BASE_URL是FlightAware AeroAPI的基礎(chǔ)URL。

AEROAPI_KEY是用于身份驗(yàn)證的API密鑰。

會(huì)話管理

get_api_session這個(gè)嵌套函數(shù)初始化請(qǐng)求。這將使用API密鑰設(shè)置所需的報(bào)頭,并返回會(huì)話對(duì)象。會(huì)話將處理所有API請(qǐng)求。

數(shù)據(jù)獲取

fetch_flight_data這個(gè)函數(shù)接受flight_id和session作為參數(shù)。它用適當(dāng)?shù)娜掌谶^濾器構(gòu)造端點(diǎn)URL,用于獲取一天的數(shù)據(jù),并發(fā)送GET請(qǐng)求檢索航班數(shù)據(jù)。該函數(shù)處理API響應(yīng),并提取相關(guān)航班信息。

時(shí)間轉(zhuǎn)換

utc_to_local根據(jù)提供的時(shí)區(qū)字符串將UTC時(shí)間來自API響應(yīng)轉(zhuǎn)換為本地時(shí)間。該函數(shù)幫助我們獲得基于城市的到達(dá)和離時(shí)間。

數(shù)據(jù)處理

腳本根據(jù)可用的估計(jì)時(shí)間或?qū)嶋H時(shí)間確定駛離和到達(dá)時(shí)間的鍵,并返回到計(jì)劃時(shí)間。然后,它構(gòu)造一個(gè)含格式化航班詳細(xì)信息的字典。

截圖顯示了我們從FlightAware API收到的從迪拜飛往海得拉巴的阿聯(lián)酋航空EK524的響應(yīng)。請(qǐng)注意,到達(dá)和離時(shí)間基于城市的當(dāng)?shù)貢r(shí)間。

我們旨在將該函數(shù)與Gemini 1.0 Pro集成,使其能夠?qū)崟r(shí)訪問航班跟蹤信息。

函數(shù)與Hermes 2 Pro集成

先使用以下命令安裝最新版本的Hugging Face Python SDK

pip install --upgrade huggingface_hub

導(dǎo)入模塊并通過將客戶端指向TGI端點(diǎn)來初始化客戶端。

from huggingface_hub import InferenceClient

client = InferenceClient("http://127.0.0.1:8080")

接下來,定義函數(shù)模式,采用的格式與OpenAPI函數(shù)調(diào)用的格式一樣

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_flight_status",
            "description": "Get status of a flight",
            "parameters": {
                "type": "object",
                "properties": {
                    "flight": {
                        "type": "string",
                        "description": "Flight number"
                    }
                },
                "required": ["flight"]
            }
        }
    }
]

這將使用LLM用作工具的一個(gè)或多個(gè)函數(shù)填充列表。

現(xiàn)在,我們將創(chuàng)建接受提示并確定是否需要調(diào)用函數(shù)的聊天機(jī)器人。如果需要調(diào)用,則LLM先返回函數(shù)名和需要調(diào)用的數(shù)。函數(shù)的輸出作為第二次調(diào)用的一部分發(fā)送給LLM。最終的響應(yīng)將根據(jù)函數(shù)的輸出得到與事實(shí)相符的正確答案。

def chatbot(prompt):
    messages = [
        {
            "role": "system",
            "content": "You're a helpful assistant! Answer the users question best you can based on the tools provided. Be concise in your responses.",
        },
        {
            "role": "user",
            "content": prompt
        },
    ]
 
    response = client.chat_completion(messages=messages, tools=tools)
    tool_calls = response.choices[0].message.tool_calls
 
    if tool_calls:
        available_functions = {
            "get_flight_status": get_flight_status,
        }
        
        for tool_call in tool_calls:
            function_name = tool_call.function.name
            function_to_call = available_functions[function_name]
            function_args = tool_call.function.arguments
        
            function_response = function_to_call(flight=function_args.get("flight"))
            
            messages.append(
                {
                    "role": "tool",
                    "name": function_name,
                    "content": function_response
                }
            )
            
        final_response = client.chat_completion(messages=messages)
        return final_response
        
    return response

目標(biāo)LLM期望的提示的自動(dòng)格式化是使用Hugging Face Python庫(kù)的一個(gè)好處。比如說,使用函數(shù)時(shí),Hermes 2 Pro的提示需要按照特定的格式進(jìn)行結(jié)構(gòu)化

<|im_start|>system
You are a function calling AI model. You are provided with function signatures within XML tags. You may call one or more functions to assist with the user query. Don't make assumptions about what values to plug into functions. Here are the available tools: [{'type': 'function', 'function': {'name': 'get_stock_fundamentals', 'description': 'Get fundamental data for a given stock symbol using yfinance API.', 'parameters': {'type': 'object', 'properties': {'symbol': {'type': 'string'}}, 'required': ['symbol']}}}] Use the following pydantic model json schema for each tool call you will make: {'title': 'FunctionCall', 'type': 'object', 'properties': {'arguments': {'title': 'Arguments', 'type': 'object'}, 'name': {'title': 'Name', 'type': 'string'}}, 'required': 

['arguments', 'name']} For each function call return a json object with function name and arguments within XML tags as follows:

{'arguments': , 'name': }
<|im_end|>

同樣,函數(shù)的輸出可以以以下格式發(fā)送到LLM

<|im_start|>tool

{"name": "get_stock_fundamentals", "content": {'symbol': 'TSLA', 'company_name': 'Tesla, Inc.', 'sector': 'Consumer Cyclical', 'industry': 'Auto Manufacturers', 'market_cap': 611384164352, 'pe_ratio': 49.604652, 'pb_ratio': 9.762013, 'dividend_yield': None, 'eps': 4.3, 'beta': 2.427, '52_week_high': 299.29, '52_week_low': 152.37}}

<|im_end|>

確保提示遵循模板需要仔細(xì)格式化。InferenceClient類可高效地處理這種轉(zhuǎn)換,使開發(fā)人員能夠在提示中使用系統(tǒng)、用戶、工具和助手角色熟悉的OpenAI格式。

在首次調(diào)用聊天完成API時(shí),LLM給出以下答案作為響應(yīng):

隨后,在調(diào)用函數(shù)之后,我們將結(jié)果嵌入到消息中并將其發(fā)回LLM。

正如您所見,集成函數(shù)調(diào)用的工作流程與OpenAI非常相似。

現(xiàn)在是時(shí)候調(diào)用聊天機(jī)器人并通過提示測(cè)試它了。

res=chatbot("What's the status of EK226?")
print(res.choices[0].message.content)

聊天機(jī)器人的完整代碼如下所示。

from huggingface_hub import InferenceClient

client = InferenceClient("http://127.0.0.1:8080")


tools = [
    {
        "type": "function",
        "function": {
            "name": "get_flight_status",
            "description": "Get status of a flight",
            "parameters": {
                "type": "object",
                "properties": {
                    "flight": {
                        "type": "string",
                        "description": "Flight number"
                    }
                },
                "required": ["flight"]
            }
        }
    }
]


def chatbot(prompt):
    messages = [
        {
            "role": "system",
            "content": "You're a helpful assistant! Answer the users question best you can based on the tools provided. Be concise in your responses.",
        },
        {
            "role": "user",
            "content": prompt
        },
]


    response = client.chat_completion(messages=messages, tools=tools)
    tool_calls = response.choices[0].message.tool_calls

    if tool_calls:
        available_functions = {
            "get_flight_status": get_flight_status,
        }
        
        for tool_call in tool_calls:
            function_name = tool_call.function.name
            function_to_call = available_functions[function_name]
            function_args = tool_call.function.arguments
        
            function_response = function_to_call(flight=function_args.get("flight"))
            
            messages.append(
                {
                    "role": "tool",
                    "name": function_name,
                    "content": function_response
                }
            )
            
        final_response = client.chat_completion(messages=messages)
        return final_response
        
    return response


res=chatbot("What's the status of EK226?")

print(res.choices[0].message.content)    

原文標(biāo)題:Building an Open LLM App Using Hermes 2 Pro Deployed Locally,作者:Janakiram MSV


責(zé)任編輯:華軒 來源: 51CTO
相關(guān)推薦

2012-03-30 15:54:43

ibmdw

2024-11-08 09:53:01

2023-12-12 13:49:35

LLMAIChatGPT

2023-08-22 20:55:04

AzureLLMTypeChat

2024-09-06 10:46:04

2009-06-11 17:07:49

WebsphereJ2EE應(yīng)用程序

2009-01-03 14:25:10

ibmdwWeb

2010-03-29 13:35:39

ibmdwRIA

2024-03-07 09:15:57

2010-06-13 09:22:37

jQuery

2021-07-30 10:11:14

HelmKubernetes包管理

2024-03-12 10:05:47

大型語(yǔ)言模型

2012-04-19 09:34:21

ibmdw

2022-11-22 10:52:00

云計(jì)算工具

2010-12-15 16:17:59

服務(wù)部署

2012-03-14 10:02:58

ibmdw

2009-09-22 12:59:07

ibmdwWeb

2009-04-13 11:35:55

IBMdWEclipseJava

2024-06-24 10:53:23

2024-10-16 08:23:15

大型語(yǔ)言模型LLM機(jī)器學(xué)習(xí)
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)