安全的關(guān)鍵.png)
使用這些基本 REST API 最佳實(shí)踐構(gòu)建出色的 API
函數(shù)調(diào)用
自然語(yǔ)言接口(NLI):Natural Language Interface,自然語(yǔ)言連接一切。
自然語(yǔ)言接口(NLI)
大模型的兩大缺陷:大模型受限于計(jì)算資源和訓(xùn)練時(shí)間,導(dǎo)致信息滯后,并且其基于統(tǒng)計(jì)規(guī)律的回答缺乏真正的邏輯推理能力。
大模型的兩大缺陷
函數(shù)調(diào)用(Function Calling):函數(shù)調(diào)用使您能夠更可靠地從模型中獲取結(jié)構(gòu)化數(shù)據(jù)。
get_current_weather(location: string, unit: 'celsius' | 'fahrenheit')
def get current weather(location: str, unit: str = 'celsius', api key: str = None) -> dict:
""獲取當(dāng)前天氣"
if not api key:
raise ValueError(API key is required to fetch weather data.")endpoint = f"https://api.weatherprovider.com/current?q=(location)&units=(unit)&appid=(api key)'response = requests.get(endpoint)
if response.status code == 200:
return response.json()
else:
raise ValueError(fFailed to fetch weather data: (response.status codey"
# 使用示例(需要填入實(shí)際的API密鑰)api key ="YOUR WEATHER API KEYlocation : "London,Uk"weather data = get current weather(location, api key api key)print(weather data)
定義函數(shù):get_current_weather
get_customers(min_revenue: int, created_before: string, limit: int)
調(diào)用您的內(nèi)部 API。def parse question to api call(question: str) -> tuple:
""將問(wèn)題解析為API調(diào)用的參數(shù)”“
# 這里應(yīng)該有更復(fù)雜的NLP邏輯來(lái)解析問(wèn)題
if"主要客戶(hù)"in question:
return "get customers", [min revenue": 10000, "created before": "2023-01-01", "limit": 10)else:
raise ValueError("Unknown question format.")
def get customers(**kwargs):
""獲取客戶(hù)列表 (模擬API調(diào)用) “”
# 這里應(yīng)該是實(shí)際的API調(diào)用邏輯
print(f"Fetching customers with parameters: (kwargs)")
# 返回模擬數(shù)據(jù)
return [("name": "Customer1" "revenue": 12000), ("name": "Customer2", "revenue": 15000)
# 使用示例
question ="誰(shuí)是我的主要客戶(hù)?“
api name, api params = parse question to api call(question)if api name == "get customers":
customers = get customers(* api params)
print(customers)
調(diào)用內(nèi)部API函數(shù):get_customers
extract_data(name: string, birthday: string)
import re
def extract data(text: str) -> tuple:
"“從文本中提取姓名和生日"m”pattern = r"Name: (w+)s+Birthday: ( d(43-d(2)-d(2))match = re.search(pattern, text)if match:
name, birthday = match.groups()
return name, birthdayelse:
raise ValueError("Failed to extract data from text.")
# 使用示例
text = "Name: John Doe, Birthday: 1990-01-01"try:
extracted name, extracted birthday = extract data(text)print(f"Name: (extracted name Birthday: (extracted birthday,")except ValueError as e:
print(e)
提取數(shù)據(jù)函數(shù):extract_data
函數(shù)調(diào)用的機(jī)制:在大語(yǔ)言模型中,函數(shù)調(diào)用通常涉及將用戶(hù)的自然語(yǔ)言請(qǐng)求轉(zhuǎn)換為可執(zhí)行的函數(shù)調(diào)用,并生成符合預(yù)定義函數(shù)簽名的結(jié)構(gòu)化輸出,如JSON對(duì)象。
函數(shù)調(diào)用機(jī)制的主要步驟:
函數(shù)調(diào)用的想象空間
用戶(hù)對(duì)著微信說(shuō):給我每個(gè)女性好友發(fā)一條情真意切的拜年信息,還要帶點(diǎn)兒小幽默。
import itchat # itchat是一個(gè)開(kāi)源的微信個(gè)人號(hào)接口,但注意它并不總是可用,且可能違反微信的服務(wù)條款
def send new year greeting _to female friends():# 登錄微信,這通常需要手機(jī)掃描二維碼確認(rèn)登錄itchat.auto login()
# 獲取所有好友列表
friends = itchat.get friends(update=True)
# 歷好友列表,篩選出女性好友并發(fā)送消息for friend in friends:
if friend[Sex] == 2: # 假設(shè)在itchat中,性別用1表示男性,2表示女性message =f"親愛(ài)的ffriend[NickName》,新年到啦! 祝你越來(lái)越美麗,笑口常開(kāi),好運(yùn)連連! 別#發(fā)送消息給好友,這里使用send msg函數(shù)作為示例,實(shí)際中itchat可能有不同的函數(shù)來(lái)發(fā)送消息# 注意: itchat庫(kù)已經(jīng)停止維護(hù),并且微信網(wǎng)頁(yè)版接口經(jīng)常變動(dòng),所以下面的代碼可能無(wú)法工作。itchat.send msg(message, toUserName friendUserName'7)
# 登出微信
itchat.logout()
# 調(diào)用函數(shù)發(fā)送拜年信息(注意:實(shí)際執(zhí)行這段代碼可能會(huì)違反微信的服務(wù)條款,導(dǎo)致賬號(hào)被封禁)# send new year greeting to female friends()
微信給女性朋友拜年
用戶(hù)對(duì)著富途牛牛說(shuō):人工智能相關(guān)股票,市盈率最低的是哪幾個(gè)?最近交易量如何?都有哪些機(jī)構(gòu)持有?
import requests
def get lowest pe ai stocks(api endpoint, api key):
0
獲取人工智能相關(guān)股票中市盈率最低的幾個(gè)股票信息
param api endpoint: APIBendpoint URL
param api key: 用戶(hù)的API密銷(xiāo)
:return: 市盈率最低的股票列表及其相關(guān)信息00
# 構(gòu)造請(qǐng)求參數(shù),這里假設(shè)API支持按市盈率排序和按人工智能相關(guān)篩選股票params = [
category':"ai,# 假設(shè) ai代表人工智能相關(guān)的股票分類(lèi)sort':'pe ratio,# 按市盈率排序order':"asc,# 升序排列,獲取市盈率最低的股票"limit': 5 # 獲取前5個(gè)結(jié)果,這個(gè)數(shù)字可以根據(jù)需要調(diào)整
# 發(fā)送HTTP請(qǐng)求到API
response = requestsget(api endpoint, params=params, headers=(Authorization': api key)
# 檢查響應(yīng)狀態(tài)碼,如果不是200則拋出異常if response.status code != 200:
raise Exception(f"Failed to fetch data from APl: fresponse.status code!")
#解析響應(yīng)內(nèi)容,這里假設(shè)API返回的是JSON格式的數(shù)據(jù)data = response,json()
# 提取股票信息,并返回結(jié)果
return data 'stocks'
def get recent trading_volume(api endpoint, api key, stock code):
獲取指定股票的最近交易量信息,
:param api endpoint: API的endpoint URL,可能需要根據(jù)股票代碼構(gòu)造具體的URLparam api_key: 用戶(hù)的API密鑰
:param stock code: 股票代碼
:return: 最近交易量信息
80
# 發(fā)送HTTP請(qǐng)求到API,獲取指定股票的交易量信息response = requests.get(f"api endpoint;/stock code)/trading_volume", headers=('Authorization' i
#檢查響應(yīng)狀態(tài)碼,如果不是200則拋出異常if responsestatus code != 200:
raise Exception(f"Failed to fetch trading volume for stock stock code): fresponse.status code)")
# 解析響應(yīng)內(nèi)容,并返回交易量信息
return response,json()['trading volume'
def get institutional holders(api endpoint, api key, stock code):
000
獲取指定股票的機(jī)構(gòu)持有者信息。
:param api endpoint: API的endpoint URL,可能需要根據(jù)股票代碼構(gòu)造具體的URL:param api_key: 用戶(hù)的API密鑰
:param stock code: 股票代碼
:return: 機(jī)構(gòu)持有者列表及其持股份額等信息000
# 發(fā)送HTTP請(qǐng)求到API,獲取指定股票的機(jī)構(gòu)持有者信息response = requests.get(f fapi endpoint)/stock code)/holders/institutional", headers='Authorizatic
#檢查響應(yīng)狀態(tài)碼,如果不是200則拋出異常
if response.status code != 200:
raise Exception(f"Failed to fetch institutional holders for stock fstock codek: fresponse.status coc
# 解析響應(yīng)內(nèi)容,并返回機(jī)構(gòu)持有者信息
return response.json()[institutional holders”]
# 假設(shè)的API密鑰和endpoint URL,實(shí)際使用時(shí)需要督換為真實(shí)的值api key = "your api key"api endpoint = "https://api.example.com/stocks'
# 獲取市盈率最低的人工智能相關(guān)股票列表lowest pe stocks = get lowest pe ai stocks(api endpoint, api key)for stock in lowest pe stocks:
stock code = stock['code'l
pe ratio = stock['pe ratio']
print(f"Stock Code: (stock code], PE Ratio: {pe ratio]"
#獲取每個(gè)股票的最近交易量信息
try:
trading volume = get recent trading volume(api endpoint, api key, stock codeprint(f"Recent Trading Volume: (trading_volume)")except Exception as e:
print(f"Error fetching trading volume: (ej")
# 獲取每個(gè)股票的機(jī)構(gòu)持有者信息try:
institutional holders = get institutional holders(api endpoint, api key, stock code)print("Institutional Holders.")
for holder in institutional holders:
print(f holder['name: holder['share percentage])%"except Exception as e:
print(f"Error fetching institutional holders: (ey")
本文章轉(zhuǎn)載微信公眾號(hào)@架構(gòu)師帶你玩轉(zhuǎn)AI
對(duì)比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力
一鍵對(duì)比試用API 限時(shí)免費(fèi)