偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

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

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

譯者 | 布加迪

審校 | 重樓

之前我介紹了如何使用OpenAI最新的LLM GPT-4o,通過函數(shù)調(diào)用將實時數(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億個參數(shù)。它是開放模型,我們將在Hugging Face的文本生成推理上運行它。

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

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

Hermes 2 Pro簡介

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

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

本地部署Hermes 2 Pro

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

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

下面的命令在端口8080上啟動推理引擎,通過REST端點為LLM提供服務(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ù)下一步之前,注冊FlightAware并獲取API密鑰,使用REST API需要API密鑰。免費的個人版本足以完成本教程。

獲得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"}'

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

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

不妨看看腳本的組件:

API憑據(jù):

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

AEROAPI_KEY是用于身份驗證的API密鑰。

話管理

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

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

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

間轉(zhuǎn)換

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

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

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

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

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

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

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

pip install --upgrade huggingface_hub

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

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用作工具的一個或多個函數(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ù)的輸出得到與事實相符的正確答案。

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期望的提示的自動格式化是使用Hugging Face Python庫的一個好處。比如說,使用函數(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時,LLM給出以下答案作為響應(yīng):

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

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

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

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)推薦

2025-06-18 08:12:14

2025-05-06 08:09:02

2012-03-30 15:54:43

ibmdw

2024-11-08 09:53:01

2023-12-12 13:49:35

LLMAIChatGPT

2024-09-06 10:46:04

2023-08-22 20:55:04

AzureLLMTypeChat

2009-01-03 14:25:10

ibmdwWeb

2009-06-11 17:07:49

WebsphereJ2EE應(yīng)用程序

2010-03-29 13:35:39

ibmdwRIA

2010-06-13 09:22:37

jQuery

2024-03-07 09:15:57

2021-07-30 10:11:14

HelmKubernetes包管理

2012-04-19 09:34:21

ibmdw

2024-03-12 10:05:47

大型語言模型

2022-11-22 10:52:00

云計算工具

2010-12-15 16:17:59

服務(wù)部署

2009-09-22 12:59:07

ibmdwWeb

2012-03-14 10:02:58

ibmdw

2009-04-13 11:35:55

IBMdWEclipseJava
點贊
收藏

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