成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

使用本地部署的Hermes 2 Pro構建開放的LLM應用程序

譯文
人工智能
本文介紹了如何使用基于Meta Llama 3架構的功能強大的大語言模型(LLM)Hermes 2 Pro-Llama- 3 8B進行函數調用,并在Hugging Face上運行。

譯者 | 布加迪

審校 | 重樓

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

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

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

Hermes 2 Pro簡介

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

該模型利用特殊的系統提示和多輪函數調用結構以及新的ChatML角色,使得函數調用可靠且易于解析。據基準測試顯示Hermes 2 Pro-Llama-3在與Fireworks AI合作構建的函數調用評估中獲得了出色90%

本地部署Hermes 2 Pro

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

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

下面的命令在端口8080上啟動推理引擎,通過REST端點為LLM提供服務。

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?"}'

如果一切正常,您應該看到Hermes 2 Pro的響應。

跟蹤航班狀態的函數

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

獲得API密鑰后,Python創建以下函數,以檢索任何航班的狀態。

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

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

get_flight_status函數接受航班參數假設是航班標識符,并以JSON格式返回格式化的航班詳細信息。它查詢AeroAPI以根據特定的航班標識符獲取航班數據,并格式化關鍵細節,比如、目的地、駛離時間、到達時間和狀態。

不妨看看腳本的組件:

API憑據:

AEROAPI_BASE_URL是FlightAware AeroAPI的基礎URL。

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

話管理

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

數據獲取

fetch_flight_data這個函數接受flight_id和session作為參數。它用適當的日期過濾器構造端點URL,用于獲取一天的數據,并發送GET請求檢索航班數據。該函數處理API響應并提取相關航班信息。

間轉換

utc_to_local根據提供的時區字符串將UTC時間來自API響應轉換為本地時間。該函數幫助我們獲得基于城市的到達和離時間。

數據處理

腳本根據可用的估計時間或實際時間確定駛離和到達時間的鍵,并返回到計劃時間。然后,它構造一個含格式化航班詳細信息的字典。

截圖顯示了我們從FlightAware API收到的從迪拜飛往海得拉巴的阿聯酋航空EK524的響應。請注意,到達和離時間基于城市的當地時間。

我們旨在將該函數與Gemini 1.0 Pro集成,使其能夠實時訪問航班跟蹤信息。

函數與Hermes 2 Pro集成

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

pip install --upgrade huggingface_hub

導入模塊并通過將客戶端指向TGI端點來初始化客戶端。

from huggingface_hub import InferenceClient

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

接下來,定義函數模式,采用的格式與OpenAPI函數調用的格式一樣

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用作工具的一個或多個函數填充列表。

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

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

目標LLM期望的提示的自動格式化是使用Hugging Face Python庫的一個好處。比如說,使用函數時,Hermes 2 Pro的提示需要按照特定的格式進行結構化

<|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|>

同樣,函數的輸出可以以以下格式發送到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|>

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

在首次調用聊天完成API時,LLM給出以下答案作為響應:

隨后,在調用函數之后,我們將結果嵌入到消息中并將其發回LLM。

正如您所見,集成函數調用的工作流程與OpenAI非常相似。

現在是時候調用聊天機器人并通過提示測試它了。

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

聊天機器人的完整代碼如下所示。

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)    

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


責任編輯:華軒 來源: 51CTO
相關推薦

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

2009-06-11 17:07:49

WebsphereJ2EE應用程序

2009-01-03 14:25:10

ibmdwWeb

2024-09-06 10:46:04

2023-08-22 20:55:04

AzureLLMTypeChat

2010-03-29 13:35:39

ibmdwRIA

2010-06-13 09:22:37

jQuery

2021-07-30 10:11:14

HelmKubernetes包管理

2024-03-07 09:15:57

2012-04-19 09:34:21

ibmdw

2022-11-22 10:52:00

云計算工具

2010-12-15 16:17:59

服務部署

2012-03-14 10:02:58

ibmdw

2009-09-22 12:59:07

ibmdwWeb

2009-04-13 11:35:55

IBMdWEclipseJava

2024-03-12 10:05:47

大型語言模型
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 亚洲国产精品一区二区三区 | 亚洲天堂色 | 国产精品久久久久久久久久久免费看 | 日韩欧美在线免费 | 亚洲人成在线观看 | 亚洲第一成人影院 | 一区二区三区免费 | 成人3d动漫一区二区三区91 | 欧美色综合 | 成人国产精品久久久 | 国产一级在线观看 | 国产区第一页 | 99re在线视频免费观看 | 精品国产一区久久 | 国产日韩精品一区 | 国产欧美日韩在线一区 | 久久久91精品国产一区二区三区 | 伊人伊成久久人综合网站 | 国产精品日韩一区 | 国产精品久久久久久妇女 | a级黄色片在线观看 | 99精品久久| 欧美bondage紧缚视频 | 欧美精品久久 | 一区二区不卡视频 | 久久美国 | 国产偷录视频叫床高潮对白 | 欧美日韩a | 国产精品亚洲第一区在线暖暖韩国 | www久久爱| 亚洲在线 | 999视频在线播放 | 亚洲97 | 免费成年网站 | 成人在线精品 | 又黄又色| 久久99国产精品 | 亚洲91视频 | 干出白浆视频 | 国产在线观看一区二区三区 | 中文字幕 欧美 日韩 |