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

使用本地部署的Hermes 2 Pro 構(gòu)建開(kāi)放的LLM應(yīng)用程序 原創(chuàng)

發(fā)布于 2024-7-2 10:52
瀏覽
0收藏

譯者 | 布加迪

審校 | 重樓

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

我們將把Fightaware.com的API 與該LLM集成起來(lái),以便實(shí)時(shí)跟蹤航班狀態(tài)。

FlightAware的AeroAPI是開(kāi)發(fā)人員獲取全面航班信息的一種完美工具。它支持實(shí)時(shí)航班跟蹤、歷史和未來(lái)航班數(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é)助等。它的一項(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 GPU的Linux服務(wù)器,搭載24GB的VRAM。它運(yùn)行Docker和英偉達(dá)容器工具包,使容器能夠訪問(wèn)GPU。

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

下面的命令在端口8080上啟動(dòng)推理引擎,通過(guò)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ù)娜掌谶^(guò)濾器構(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í)間(來(lái)自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ì)信息的字典。

使用本地部署的Hermes 2 Pro 構(gòu)建開(kāi)放的LLM應(yīng)用程序-AI.x社區(qū)

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

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

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

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

pip install --upgrade huggingface_hub

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

from huggingface_hub import InferenceClient

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

接下來(lái),定義函數(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ù)填充列表。

使用本地部署的Hermes 2 Pro 構(gòu)建開(kāi)放的LLM應(yīng)用程序-AI.x社區(qū)

現(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è)好處。比如說(shuō),使用函數(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類(lèi)可高效地處理這種轉(zhuǎn)換,使開(kāi)發(fā)人員能夠在提示中使用系統(tǒng)、用戶、工具和助手角色的熟悉的OpenAI格式。

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

使用本地部署的Hermes 2 Pro 構(gòu)建開(kāi)放的LLM應(yīng)用程序-AI.x社區(qū)

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

使用本地部署的Hermes 2 Pro 構(gòu)建開(kāi)放的LLM應(yīng)用程序-AI.x社區(qū)

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

現(xiàn)在是時(shí)候調(diào)用聊天機(jī)器人并通過(guò)提示來(lái)測(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

?著作權(quán)歸作者所有,如需轉(zhuǎn)載,請(qǐng)注明出處,否則將追究法律責(zé)任
標(biāo)簽
已于2024-7-2 11:05:57修改
收藏
回復(fù)
舉報(bào)
回復(fù)
相關(guān)推薦
主站蜘蛛池模板: 在线一区二区三区 | 高清色| 两性午夜视频 | 91综合网 | 国产精品污www一区二区三区 | 日韩一区二区在线免费观看 | 国产精品激情在线 | 国产精品久久久久久久免费大片 | 国产精品久久久久久模特 | 精品福利在线 | 91人人看| 久久国产区 | 亚洲欧洲国产视频 | 国产在线一级片 | 99国产视频| 亚洲一区久久 | 亚洲视频在线一区 | 中文字幕精品一区二区三区精品 | 日本精品视频 | 日韩欧美三区 | 国产精品99久久久久久宅男 | 91在线精品一区二区 | 成人高清在线 | 国产一在线观看 | 亚洲一区视频 | 91精品久久久久久久久久入口 | 日韩久久综合 | 久久这里只有 | 在线不卡 | av网站免费 | 日韩欧美专区 | 日本不卡一区二区三区 | 欧美日一区二区 | a黄视频| 日韩午夜一区二区三区 | 久久伦理电影 | 欧美日韩免费一区二区三区 | 欧美一级在线免费观看 | 精品久久一区 | 国产99小视频 | 午夜合集|