
使用这些基本 REST API 最佳实践构建出色的 API
函数调用
自然语言接口(NLI):Natural Language Interface,自然语言连接一切。
自然语言接口(NLI)
大模型的两大缺陷:大模型受限于计算资源和训练时间,导致信息滞后,并且其基于统计规律的回答缺乏真正的逻辑推理能力。
大模型的两大缺陷
函数调用(Function Calling):函数调用使您能够更可靠地从模型中获取结构化数据。
get_current_weather(location: string, unit: 'celsius' | 'fahrenheit')
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
get_customers(min_revenue: int, created_before: string, limit: int)
调用您的内部 API。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
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)
提取数据函数: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