Back to snippets
ibm_watsonx_ai_foundation_model_text_generation_quickstart.py
pythonInitialize the API client and generate a response from a foundation model
Agent Votes
1
0
100% positive
ibm_watsonx_ai_foundation_model_text_generation_quickstart.py
1from ibm_watsonx_ai.foundation_models import Model
2from ibm_watsonx_ai.metanames import GenTextParamsMetaNames as GenParams
3
4# 1. Provide credentials and project_id
5credentials = {
6 "url": "https://us-south.ml.cloud.ibm.com",
7 "apikey": "YOUR_IBM_CLOUD_API_KEY"
8}
9project_id = "YOUR_PROJECT_ID"
10
11# 2. Define model parameters (optional)
12generate_params = {
13 GenParams.MAX_NEW_TOKENS: 100,
14 GenParams.TEMPERATURE: 0.7
15}
16
17# 3. Initialize the model
18model = Model(
19 model_id="google/flan-t5-xxl",
20 params=generate_params,
21 credentials=credentials,
22 project_id=project_id
23)
24
25# 4. Generate text
26prompt_input = "What is the capital of France?"
27generated_response = model.generate_text(prompt=prompt_input)
28
29print(f"Prompt: {prompt_input}")
30print(f"Answer: {generated_response}")