基礎模型 Python 程式庫
您可以使用 Python 程式庫,以程式化方式在 IBM watsonx.ai 中提示基礎模型。
Python 程式庫參照
必要條件
若要執行本主題中的部分範例,您需要 API 金鑰及專案 ID:
API 的基礎模型 ID
您必須指定要在要求中使用的模型。 下列清單顯示從 API 參照基礎模型時要在 {model_id} 參數中使用的值。
flan-t5-xxl-11b
google/flan-t5-xxlflan-ul2-20b
google/flan-ul2gpt-neox-20b
eleutherai/gpt-neox-20bgranite-13b-chat-v1
ibm/granite-13b-chat-v1granite-13b-instruct-v1
ibm/granite-13b-instruct-v1llama-2-13b-chat
meta-llama/llama-2-13b-chatllama-2-70b-chat
meta-llama/llama-2-70b-chatmpt-7b-instruct2
ibm/mpt-7b-instruct2mt0-xxl-13b
bigscience/mt0-xxlstarcoder-15.5b
bigcode/starcoder
範例
範例 1: 列出可用的模型
您可以檢視 ModelTypes 以查看可用的模型。
Python 程式碼
from ibm_watson_machine_learning.foundation_models.utils.enums import ModelTypes
import json
print( json.dumps( ModelTypes._member_names_, indent=2 ) )
範例輸出
[
"FLAN_T5_XXL",
"FLAN_UL2",
"MT0_XXL",
...
]
範例 2: 檢視模型的詳細資料
您可以使用 get_details()來檢視詳細資料,例如簡要說明和模型限制。
Python 程式碼
from ibm_watson_machine_learning.foundation_models.utils.enums import ModelTypes
from ibm_watson_machine_learning.foundation_models import Model
import json
my_credentials = {
"url" : "https://us-south.ml.cloud.ibm.com",
"apikey" : <my-IBM-Cloud-API-key>
}
model_id = ModelTypes.MPT_7B_INSTRUCT2
gen_parms = None
project_id = <my-watsonx.ai-project-ID>
space_id = None
verify = False
model = Model( model_id, my_credentials, gen_parms, project_id, space_id, verify )
model_details = model.get_details()
print( json.dumps( model_details, indent=2 ) )
附註:
將 <my-IBM-Cloud-API-key> 和 <my-project-ID> 取代為您的 API 金鑰和專案 ID。
範例輸出
{
"model_id": "ibm/mpt-7b-instruct2",
"label": "mpt-7b-instruct2",
"provider": "IBM",
"source": "Hugging Face",
"short_description": "MPT-7B is a decoder-style transformer pretrained from
scratch on 1T tokens of English text and code. This model was trained by IBM.",
...
}
範例 3: 使用預設參數提示模型
使用 generate()提示模型產生回應。
Python 程式碼
from ibm_watson_machine_learning.foundation_models.utils.enums import ModelTypes
from ibm_watson_machine_learning.foundation_models import Model
import json
my_credentials = {
"url" : "https://us-south.ml.cloud.ibm.com",
"apikey" : <my-IBM-Cloud-API-key>
}
model_id = ModelTypes.FLAN_T5_XXL
gen_parms = None
project_id = <my-project-ID>
space_id = None
verify = False
model = Model( model_id, my_credentials, gen_parms, project_id, space_id, verify )
prompt_txt = "In today's sales meeting, we "
gen_parms_override = None
generated_response = model.generate( prompt_txt, gen_parms_override )
print( json.dumps( generated_response, indent=2 ) )
附註:
將 <my-IBM-Cloud-API-key> 和 <my-project-ID> 取代為您的 API 金鑰和專案 ID。
範例輸出
{
"model_id": "google/flan-t5-xxl",
"created_at": "2023-07-27T03:40:17.575Z",
"results": [
{
"generated_text": "will discuss the new product line.",
"generated_token_count": 8,
"input_token_count": 10,
"stop_reason": "EOS_TOKEN"
}
],
...
}
進一步瞭解
上層主題: 基礎模型