函數調用

一、函數調用的本質

自然語言接口(NLI):Natural Language Interface,自然語言連接一切。

自然語言接口(NLI)

大模型的兩大缺陷:大模型受限于計算資源和訓練時間,導致信息滯后,并且其基于統計規律的回答缺乏真正的邏輯推理能力。

大模型的兩大缺陷

二、函數調用的原理

函數調用(Function Calling):函數調用使您能夠更可靠地從模型中獲取結構化數據。

函數調用(Function Calling)

def get current weather(location: str, unit: str = 'celsius', api key: str = None) -> dict:
""獲取當前天氣"
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"
# 使用示例(需要填入實際的API密鑰)api key ="YOUR WEATHER API KEYlocation : "London,Uk"weather data = get current weather(location, api key api key)print(weather data)

定義函數:get_current_weather

def parse question to api call(question: str) -> tuple:
""將問題解析為API調用的參數”“
# 這里應該有更復雜的NLP邏輯來解析問題
if"主要客戶"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):
""獲取客戶列表 (模擬API調用) “”
# 這里應該是實際的API調用邏輯
print(f"Fetching customers with parameters: (kwargs)")
# 返回模擬數據
return [("name": "Customer1" "revenue": 12000), ("name": "Customer2", "revenue": 15000)
# 使用示例
question ="誰是我的主要客戶?“
api name, api params = parse question to api call(question)if api name == "get customers":
customers = get customers(* api params)
print(customers)

調用內部API函數:get_customers

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)

提取數據函數:extract_data

函數調用的機制:在大語言模型中,函數調用通常涉及將用戶的自然語言請求轉換為可執行的函數調用,并生成符合預定義函數簽名的結構化輸出,如JSON對象。

函數調用的機制

函數調用機制的主要步驟:

三、函數調用的想象空間

函數調用的想象空間

用戶對著微信說:給我每個女性好友發一條情真意切的拜年信息,還要帶點兒小幽默。

import itchat # itchat是一個開源的微信個人號接口,但注意它并不總是可用,且可能違反微信的服務條款
def send new year greeting _to female friends():# 登錄微信,這通常需要手機掃描二維碼確認登錄itchat.auto login()
# 獲取所有好友列表
friends = itchat.get friends(update=True)
# 歷好友列表,篩選出女性好友并發送消息for friend in friends:
if friend[Sex] == 2: # 假設在itchat中,性別用1表示男性,2表示女性message =f"親愛的ffriend[NickName》,新年到啦! 祝你越來越美麗,笑口常開,好運連連! 別#發送消息給好友,這里使用send msg函數作為示例,實際中itchat可能有不同的函數來發送消息# 注意: itchat庫已經停止維護,并且微信網頁版接口經常變動,所以下面的代碼可能無法工作。itchat.send msg(message, toUserName friendUserName'7)
# 登出微信
itchat.logout()
# 調用函數發送拜年信息(注意:實際執行這段代碼可能會違反微信的服務條款,導致賬號被封禁)# send new year greeting to female friends()

微信給女性朋友拜年

用戶對著富途牛牛說人工智能相關股票,市盈率最低的是哪幾個?最近交易量如何?都有哪些機構持有?

import requests
def get lowest pe ai stocks(api endpoint, api key):
0
獲取人工智能相關股票中市盈率最低的幾個股票信息
param api endpoint: APIBendpoint URL
param api key: 用戶的API密銷
:return: 市盈率最低的股票列表及其相關信息00
# 構造請求參數,這里假設API支持按市盈率排序和按人工智能相關篩選股票params = [
category':"ai,# 假設 ai代表人工智能相關的股票分類sort':'pe ratio,# 按市盈率排序order':"asc,# 升序排列,獲取市盈率最低的股票"limit': 5 # 獲取前5個結果,這個數字可以根據需要調整
# 發送HTTP請求到API
response = requestsget(api endpoint, params=params, headers=(Authorization': api key)
# 檢查響應狀態碼,如果不是200則拋出異常if response.status code != 200:
raise Exception(f"Failed to fetch data from APl: fresponse.status code!")
#解析響應內容,這里假設API返回的是JSON格式的數據data = response,json()
# 提取股票信息,并返回結果
return data 'stocks'
def get recent trading_volume(api endpoint, api key, stock code):
獲取指定股票的最近交易量信息,
:param api endpoint: API的endpoint URL,可能需要根據股票代碼構造具體的URLparam api_key: 用戶的API密鑰
:param stock code: 股票代碼
:return: 最近交易量信息
80
# 發送HTTP請求到API,獲取指定股票的交易量信息response = requests.get(f"api endpoint;/stock code)/trading_volume", headers=('Authorization' i
#檢查響應狀態碼,如果不是200則拋出異常if responsestatus code != 200:
raise Exception(f"Failed to fetch trading volume for stock stock code): fresponse.status code)")
# 解析響應內容,并返回交易量信息
return response,json()['trading volume'
def get institutional holders(api endpoint, api key, stock code):
000
獲取指定股票的機構持有者信息。
:param api endpoint: API的endpoint URL,可能需要根據股票代碼構造具體的URL:param api_key: 用戶的API密鑰
:param stock code: 股票代碼
:return: 機構持有者列表及其持股份額等信息000
# 發送HTTP請求到API,獲取指定股票的機構持有者信息response = requests.get(f fapi endpoint)/stock code)/holders/institutional", headers='Authorizatic
#檢查響應狀態碼,如果不是200則拋出異常
if response.status code != 200:
raise Exception(f"Failed to fetch institutional holders for stock fstock codek: fresponse.status coc
# 解析響應內容,并返回機構持有者信息
return response.json()[institutional holders”]
# 假設的API密鑰和endpoint URL,實際使用時需要督換為真實的值api key = "your api key"api endpoint = "https://api.example.com/stocks'
# 獲取市盈率最低的人工智能相關股票列表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]"
#獲取每個股票的最近交易量信息
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")
# 獲取每個股票的機構持有者信息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")

本文章轉載微信公眾號@架構師帶你玩轉AI

上一篇:

大模型開發 - 一文搞懂 LangChain(五):Chains

下一篇:

大模型開發 - 一文搞懂 Prompt Engineering(提示工程)
#你可能也喜歡這些API文章!

我們有何不同?

API服務商零注冊

多API并行試用

數據驅動選型,提升決策效率

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

對比大模型API的內容創意新穎性、情感共鳴力、商業轉化潛力

25個渠道
一鍵對比試用API 限時免費

#AI深度推理大模型API

對比大模型API的邏輯推理準確性、分析深度、可視化建議合理性

10個渠道
一鍵對比試用API 限時免費