Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
IBM
GitHub Repository: IBM/watson-machine-learning-samples
Path: blob/master/cloud/notebooks/python_sdk/deployments/foundation_models/Use watsonx, and `granite-8b-code-instruct` to generate code based on instruction.ipynb
5169 views
Kernel: watsonx-ai-samples-py-311

image

Use watsonx, and ibm/granite-8b-code-instruct to generate code based on instruction

Disclaimers

  • Use only Projects and Spaces that are available in watsonx context.

Notebook content

This notebook contains the steps and code to demonstrate support for code generating in watsonx. It introduces commands for defining prompt and model testing.

Some familiarity with Python is helpful. This notebook uses Python 3.11.

Learning goal

The goal of this notebook is to demonstrate how to generate code using ibm/granite-8b-code-instruct watsonx model based on instruction provided by the user.

Contents

This notebook contains the following parts:

Set up the environment

Before you use the sample code in this notebook, you must perform the following setup tasks:

Install dependencies

%pip install -U ibm-watsonx-ai | tail -n 1
Successfully installed anyio-4.11.0 cachetools-6.2.1 certifi-2025.10.5 charset_normalizer-3.4.4 h11-0.16.0 httpcore-1.0.9 httpx-0.28.1 ibm-cos-sdk-2.14.3 ibm-cos-sdk-core-2.14.3 ibm-cos-sdk-s3transfer-2.14.3 ibm-watsonx-ai-1.4.2 idna-3.11 jmespath-1.0.1 lomond-0.3.3 numpy-2.3.4 pandas-2.2.3 pytz-2025.2 requests-2.32.5 sniffio-1.3.1 tabulate-0.9.0 tzdata-2025.2 urllib3-2.5.0

Defining the watsonx.ai credentials

This cell defines the watsonx.ai credentials required to work with watsonx Foundation Model inferencing.

Action: Provide the IBM Cloud user API key. For details, see documentation.

import getpass from ibm_watsonx_ai import Credentials credentials = Credentials( url="https://us-south.ml.cloud.ibm.com", api_key=getpass.getpass("Please enter your watsonx.ai api key (hit enter): "), )

Defining the project ID

The Foundation Model requires project ID that provides the context for the call. We will obtain the ID from the project in which this notebook runs. Otherwise, please provide the project ID.

import os try: project_id = os.environ["PROJECT_ID"] except KeyError: project_id = input("Please enter your project_id (hit enter): ")

API Client initialization

from ibm_watsonx_ai import APIClient client = APIClient(credentials, project_id=project_id)

Foundation Models on watsonx.ai

List available models

client.foundation_models.TextModels.show()
{'GRANITE_3_2_8B_INSTRUCT': 'ibm/granite-3-2-8b-instruct', 'GRANITE_3_2B_INSTRUCT': 'ibm/granite-3-2b-instruct', 'GRANITE_3_3_8B_INSTRUCT': 'ibm/granite-3-3-8b-instruct', 'GRANITE_3_8B_INSTRUCT': 'ibm/granite-3-8b-instruct', 'GRANITE_4_H_SMALL': 'ibm/granite-4-h-small', 'GRANITE_8B_CODE_INSTRUCT': 'ibm/granite-8b-code-instruct', 'GRANITE_GUARDIAN_3_8B': 'ibm/granite-guardian-3-8b', 'GRANITE_VISION_3_2_2B': 'ibm/granite-vision-3-2-2b', 'LLAMA_3_2_11B_VISION_INSTRUCT': 'meta-llama/llama-3-2-11b-vision-instruct', 'LLAMA_3_2_90B_VISION_INSTRUCT': 'meta-llama/llama-3-2-90b-vision-instruct', 'LLAMA_3_3_70B_INSTRUCT': 'meta-llama/llama-3-3-70b-instruct', 'LLAMA_3_405B_INSTRUCT': 'meta-llama/llama-3-405b-instruct', 'LLAMA_4_MAVERICK_17B_128E_INSTRUCT_FP8': 'meta-llama/llama-4-maverick-17b-128e-instruct-fp8', 'LLAMA_GUARD_3_11B_VISION': 'meta-llama/llama-guard-3-11b-vision', 'MISTRAL_MEDIUM_2505': 'mistralai/mistral-medium-2505', 'MISTRAL_SMALL_3_1_24B_INSTRUCT_2503': 'mistralai/mistral-small-3-1-24b-instruct-2503', 'GPT_OSS_120B': 'openai/gpt-oss-120b'}

You need to specify model_id that will be used for inferencing:

model_id = client.foundation_models.TextModels.GRANITE_8B_CODE_INSTRUCT

Defining the model parameters

You might need to adjust model parameters for different models or tasks, to do so please refer to documentation.

from ibm_watsonx_ai.metanames import GenTextParamsMetaNames as GenParams parameters = { GenParams.TEMPERATURE: 0, GenParams.MAX_NEW_TOKENS: 100, GenParams.STOP_SEQUENCES: ["<end·of·code>"], }

Initialize the model

Initialize the ModelInference class with previous set params.

from ibm_watsonx_ai.foundation_models import ModelInference model = ModelInference( model_id=model_id, params=parameters, credentials=credentials, project_id=project_id )

Model's details

import json print(json.dumps(model.get_details(), indent=2))
{ "model_id": "ibm/granite-8b-code-instruct", "label": "granite-8b-code-instruct", "provider": "IBM", "source": "IBM", "indemnity": "IBM_COVERED", "functions": [ { "id": "text_generation" } ], "short_description": "The Granite model series is a family of IBM-trained, dense decoder-only models, which are particularly well-suited for generative tasks.", "long_description": "Granite models are designed to be used for a wide range of generative and non-generative tasks with appropriate prompt engineering. They employ a GPT-style decoder-only architecture, with additional innovations from IBM Research and the open community.", "terms_url": "https://www.ibm.com/support/customer/csol/terms/?id=i126-6883", "input_tier": "class_1", "output_tier": "class_1", "number_params": "8b", "min_shot_size": 1, "task_ids": [ "question_answering", "summarization", "classification", "generation", "code", "extraction", "code-generation", "code-explanation", "code-fixing" ], "tasks": [ { "id": "question_answering" }, { "id": "summarization" }, { "id": "classification" }, { "id": "generation" }, { "id": "code" }, { "id": "extraction" }, { "id": "code-generation", "benchmarks": [ { "type": "academic", "name": "Code", "description": "Evaluates a model's ability to generate code in Python, C++, Go, Java, JavaScript, and Rust by using 164 code problems from the 'HumanEval' dataset that were translated from Python by humans. Metric represents the pass@1 score.", "language": "C++", "dataset": { "name": "HumanEvalSynthesize" }, "metrics": [ { "name": "pass@1", "value": 0.482 } ], "tags": [ "Code generation" ] }, { "type": "academic", "name": "Code", "description": "Evaluates a model's ability to generate code in Python, C++, Go, Java, JavaScript, and Rust by using 164 code problems from the 'HumanEval' dataset that were translated from Python by humans. Metric represents the pass@1 score.", "language": "Go", "dataset": { "name": "HumanEvalSynthesize" }, "metrics": [ { "name": "pass@1", "value": 0.433 } ], "tags": [ "Code generation" ] }, { "type": "academic", "name": "Code", "description": "Evaluates a model's ability to generate code in Python, C++, Go, Java, JavaScript, and Rust by using 164 code problems from the 'HumanEval' dataset that were translated from Python by humans. Metric represents the pass@1 score.", "language": "Java", "dataset": { "name": "HumanEvalSynthesize" }, "metrics": [ { "name": "pass@1", "value": 0.585 } ], "tags": [ "Code generation" ] }, { "type": "academic", "name": "Code", "description": "Evaluates a model's ability to generate code in Python, C++, Go, Java, JavaScript, and Rust by using 164 code problems from the 'HumanEval' dataset that were translated from Python by humans. Metric represents the pass@1 score.", "language": "JavaScript", "dataset": { "name": "HumanEvalSynthesize" }, "metrics": [ { "name": "pass@1", "value": 0.524 } ], "tags": [ "Code generation" ] }, { "type": "academic", "name": "Code", "description": "Evaluates a model's ability to generate code in Python, C++, Go, Java, JavaScript, and Rust by using 164 code problems from the 'HumanEval' dataset that were translated from Python by humans. Metric represents the pass@1 score.", "language": "Python", "dataset": { "name": "HumanEvalSynthesize" }, "metrics": [ { "name": "pass@1", "value": 0.579 } ], "tags": [ "Code generation" ] }, { "type": "academic", "name": "Code", "description": "Evaluates a model's ability to generate code in Python, C++, Go, Java, JavaScript, and Rust by using 164 code problems from the 'HumanEval' dataset that were translated from Python by humans. Metric represents the pass@1 score.", "language": "Rust", "dataset": { "name": "HumanEvalSynthesize" }, "metrics": [ { "name": "pass@1", "value": 0.372 } ], "tags": [ "Code generation" ] }, { "type": "watsonx.ai", "name": "Code", "description": "Evaluates a model's ability to generate code in Python, C++, Go, Java, JavaScript, and Rust by using 164 code problems from the 'HumanEval' dataset that were translated from Python by humans. Metric represents the pass@1 score.", "language": "C++", "dataset": { "name": "HumanEvalSynthesize" }, "metrics": [ { "name": "pass@1", "value": 0.482 } ], "tags": [ "Code generation" ] }, { "type": "watsonx.ai", "name": "Code", "description": "Evaluates a model's ability to generate code in Python, C++, Go, Java, JavaScript, and Rust by using 164 code problems from the 'HumanEval' dataset that were translated from Python by humans. Metric represents the pass@1 score.", "language": "Go", "dataset": { "name": "HumanEvalSynthesize" }, "metrics": [ { "name": "pass@1", "value": 0.402 } ], "tags": [ "Code generation" ] }, { "type": "watsonx.ai", "name": "Code", "description": "Evaluates a model's ability to generate code in Python, C++, Go, Java, JavaScript, and Rust by using 164 code problems from the 'HumanEval' dataset that were translated from Python by humans. Metric represents the pass@1 score.", "language": "Java", "dataset": { "name": "HumanEvalSynthesize" }, "metrics": [ { "name": "pass@1", "value": 0.573 } ], "tags": [ "Code generation" ] }, { "type": "watsonx.ai", "name": "Code", "description": "Evaluates a model's ability to generate code in Python, C++, Go, Java, JavaScript, and Rust by using 164 code problems from the 'HumanEval' dataset that were translated from Python by humans. Metric represents the pass@1 score.", "language": "JavaScript", "dataset": { "name": "HumanEvalSynthesize" }, "metrics": [ { "name": "pass@1", "value": 0.549 } ], "tags": [ "Code generation" ] }, { "type": "watsonx.ai", "name": "Code", "description": "Evaluates a model's ability to generate code in Python, C++, Go, Java, JavaScript, and Rust by using 164 code problems from the 'HumanEval' dataset that were translated from Python by humans. Metric represents the pass@1 score.", "language": "Python", "dataset": { "name": "HumanEvalSynthesize" }, "metrics": [ { "name": "pass@1", "value": 0.585 } ], "tags": [ "Code generation" ] }, { "type": "watsonx.ai", "name": "Code", "description": "Evaluates a model's ability to generate code in Python, C++, Go, Java, JavaScript, and Rust by using 164 code problems from the 'HumanEval' dataset that were translated from Python by humans. Metric represents the pass@1 score.", "language": "Rust", "dataset": { "name": "HumanEvalSynthesize" }, "metrics": [ { "name": "pass@1", "value": 0.348 } ], "tags": [ "Code generation" ] }, { "type": "watsonx.ai", "name": "Code", "description": "", "language": "Python", "dataset": { "name": "livecodebench_codeexecution" }, "metrics": [ { "name": "pass@1", "value": 0.236 } ], "tags": [ "Code generation" ] }, { "type": "watsonx.ai", "name": "Code", "description": "", "language": "Python", "dataset": { "name": "livecodebench_codegeneration" }, "metrics": [ { "name": "pass@1", "value": 0.127 } ], "tags": [ "Code generation" ] }, { "type": "watsonx.ai", "name": "Code", "description": "", "language": "Python", "dataset": { "name": "livecodebench_testoutputprediction" }, "metrics": [ { "name": "pass@1", "value": 0.208 } ], "tags": [ "Code generation" ] }, { "type": "watsonx.ai", "name": "Code", "description": "Evaluates a model's ability to solve entry-level Python problems using a dataset with 974 crowd-sourced problems and solutions. Metric represents the pass@1 score.", "language": "Python", "dataset": { "name": "MBPP" }, "metrics": [ { "name": "pass@1", "value": 0.502 } ], "tags": [ "Code generation" ] }, { "type": "watsonx.ai", "name": "Code", "description": "Expands on the MBPP dataset with more Python programming problems and more comprehensive test cases. Metric represents the pass@1 score.", "language": "Python", "dataset": { "name": "MBPP+" }, "metrics": [ { "name": "pass@1", "value": 0.571 } ], "tags": [ "Code generation" ] } ] }, { "id": "code-explanation", "benchmarks": [ { "type": "academic", "name": "Code", "description": "Evaluates a model's ability to explain C++, Go, Java, JavaScript, Python and Rust code by using the 'HumanEval' dataset to first ask the model to explain the solution to a programming problem and then solve the problem given only the previously generated explanation. Metric represents the pass@1 score.", "language": "C++", "dataset": { "name": "HumanEvalExplain" }, "metrics": [ { "name": "pass@1", "value": 0.439 } ], "tags": [ "Code explanation" ] }, { "type": "academic", "name": "Code", "description": "Evaluates a model's ability to explain C++, Go, Java, JavaScript, Python and Rust code by using the 'HumanEval' dataset to first ask the model to explain the solution to a programming problem and then solve the problem given only the previously generated explanation. Metric represents the pass@1 score.", "language": "Go", "dataset": { "name": "HumanEvalExplain" }, "metrics": [ { "name": "pass@1", "value": 0.366 } ], "tags": [ "Code explanation" ] }, { "type": "academic", "name": "Code", "description": "Evaluates a model's ability to explain C++, Go, Java, JavaScript, Python and Rust code by using the 'HumanEval' dataset to first ask the model to explain the solution to a programming problem and then solve the problem given only the previously generated explanation. Metric represents the pass@1 score.", "language": "Java", "dataset": { "name": "HumanEvalExplain" }, "metrics": [ { "name": "pass@1", "value": 0.524 } ], "tags": [ "Code explanation" ] }, { "type": "academic", "name": "Code", "description": "Evaluates a model's ability to explain C++, Go, Java, JavaScript, Python and Rust code by using the 'HumanEval' dataset to first ask the model to explain the solution to a programming problem and then solve the problem given only the previously generated explanation. Metric represents the pass@1 score.", "language": "JavaScript", "dataset": { "name": "HumanEvalExplain" }, "metrics": [ { "name": "pass@1", "value": 0.427 } ], "tags": [ "Code explanation" ] }, { "type": "academic", "name": "Code", "description": "Evaluates a model's ability to explain C++, Go, Java, JavaScript, Python and Rust code by using the 'HumanEval' dataset to first ask the model to explain the solution to a programming problem and then solve the problem given only the previously generated explanation. Metric represents the pass@1 score.", "language": "Python", "dataset": { "name": "HumanEvalExplain" }, "metrics": [ { "name": "pass@1", "value": 0.53 } ], "tags": [ "Code explanation" ] }, { "type": "academic", "name": "Code", "description": "Evaluates a model's ability to explain C++, Go, Java, JavaScript, Python and Rust code by using the 'HumanEval' dataset to first ask the model to explain the solution to a programming problem and then solve the problem given only the previously generated explanation. Metric represents the pass@1 score.", "language": "Rust", "dataset": { "name": "HumanEvalExplain" }, "metrics": [ { "name": "pass@1", "value": 0.165 } ], "tags": [ "Code explanation" ] }, { "type": "watsonx.ai", "name": "Code", "description": "Evaluates a model's ability to explain C++, Go, Java, JavaScript, Python and Rust code by using the 'HumanEval' dataset to first ask the model to explain the solution to a programming problem and then solve the problem given only the previously generated explanation. Metric represents the pass@1 score.", "language": "C++", "dataset": { "name": "HumanEvalExplain" }, "metrics": [ { "name": "pass@1", "value": 0.396 } ], "tags": [ "Code explanation" ] }, { "type": "watsonx.ai", "name": "Code", "description": "Evaluates a model's ability to explain C++, Go, Java, JavaScript, Python and Rust code by using the 'HumanEval' dataset to first ask the model to explain the solution to a programming problem and then solve the problem given only the previously generated explanation. Metric represents the pass@1 score.", "language": "Go", "dataset": { "name": "HumanEvalExplain" }, "metrics": [ { "name": "pass@1", "value": 0.396 } ], "tags": [ "Code explanation" ] }, { "type": "watsonx.ai", "name": "Code", "description": "Evaluates a model's ability to explain C++, Go, Java, JavaScript, Python and Rust code by using the 'HumanEval' dataset to first ask the model to explain the solution to a programming problem and then solve the problem given only the previously generated explanation. Metric represents the pass@1 score.", "language": "Java", "dataset": { "name": "HumanEvalExplain" }, "metrics": [ { "name": "pass@1", "value": 0.476 } ], "tags": [ "Code explanation" ] }, { "type": "watsonx.ai", "name": "Code", "description": "Evaluates a model's ability to explain C++, Go, Java, JavaScript, Python and Rust code by using the 'HumanEval' dataset to first ask the model to explain the solution to a programming problem and then solve the problem given only the previously generated explanation. Metric represents the pass@1 score.", "language": "JavaScript", "dataset": { "name": "HumanEvalExplain" }, "metrics": [ { "name": "pass@1", "value": 0.39 } ], "tags": [ "Code explanation" ] }, { "type": "watsonx.ai", "name": "Code", "description": "Evaluates a model's ability to explain C++, Go, Java, JavaScript, Python and Rust code by using the 'HumanEval' dataset to first ask the model to explain the solution to a programming problem and then solve the problem given only the previously generated explanation. Metric represents the pass@1 score.", "language": "Python", "dataset": { "name": "HumanEvalExplain" }, "metrics": [ { "name": "pass@1", "value": 0.506 } ], "tags": [ "Code explanation" ] }, { "type": "watsonx.ai", "name": "Code", "description": "Evaluates a model's ability to explain C++, Go, Java, JavaScript, Python and Rust code by using the 'HumanEval' dataset to first ask the model to explain the solution to a programming problem and then solve the problem given only the previously generated explanation. Metric represents the pass@1 score.", "language": "Rust", "dataset": { "name": "HumanEvalExplain" }, "metrics": [ { "name": "pass@1", "value": 0.22 } ], "tags": [ "Code explanation" ] } ] }, { "id": "code-fixing", "benchmarks": [ { "type": "academic", "name": "Code", "description": "Evaluates a model's ability to fix coding errors in the C++, Go, Java, JavaScript, Python and Rust using 'HumanEval' dataset with introduced errors and unit tests to help identify problems. Metric represents the pass@1 score.", "language": "C++", "dataset": { "name": "HumanEvalFix" }, "metrics": [ { "name": "pass@1", "value": 0.39 } ], "tags": [ "Code fixing" ] }, { "type": "academic", "name": "Code", "description": "Evaluates a model's ability to fix coding errors in the C++, Go, Java, JavaScript, Python and Rust using 'HumanEval' dataset with introduced errors and unit tests to help identify problems. Metric represents the pass@1 score.", "language": "Go", "dataset": { "name": "HumanEvalFix" }, "metrics": [ { "name": "pass@1", "value": 0.415 } ], "tags": [ "Code fixing" ] }, { "type": "academic", "name": "Code", "description": "Evaluates a model's ability to fix coding errors in the C++, Go, Java, JavaScript, Python and Rust using 'HumanEval' dataset with introduced errors and unit tests to help identify problems. Metric represents the pass@1 score.", "language": "Java", "dataset": { "name": "HumanEvalFix" }, "metrics": [ { "name": "pass@1", "value": 0.482 } ], "tags": [ "Code fixing" ] }, { "type": "academic", "name": "Code", "description": "Evaluates a model's ability to fix coding errors in the C++, Go, Java, JavaScript, Python and Rust using 'HumanEval' dataset with introduced errors and unit tests to help identify problems. Metric represents the pass@1 score.", "language": "JavaScript", "dataset": { "name": "HumanEvalFix" }, "metrics": [ { "name": "pass@1", "value": 0.409 } ], "tags": [ "Code fixing" ] }, { "type": "academic", "name": "Code", "description": "Evaluates a model's ability to fix coding errors in the C++, Go, Java, JavaScript, Python and Rust using 'HumanEval' dataset with introduced errors and unit tests to help identify problems. Metric represents the pass@1 score.", "language": "Python", "dataset": { "name": "HumanEvalFix" }, "metrics": [ { "name": "pass@1", "value": 0.396 } ], "tags": [ "Code fixing" ] }, { "type": "academic", "name": "Code", "description": "Evaluates a model's ability to fix coding errors in the C++, Go, Java, JavaScript, Python and Rust using 'HumanEval' dataset with introduced errors and unit tests to help identify problems. Metric represents the pass@1 score.", "language": "Rust", "dataset": { "name": "HumanEvalFix" }, "metrics": [ { "name": "pass@1", "value": 0.329 } ], "tags": [ "Code fixing" ] }, { "type": "watsonx.ai", "name": "Code", "description": "Evaluates a model's ability to fix coding errors in the C++, Go, Java, JavaScript, Python and Rust using 'HumanEval' dataset with introduced errors and unit tests to help identify problems. Metric represents the pass@1 score.", "language": "C++", "dataset": { "name": "HumanEvalFix" }, "metrics": [ { "name": "pass@1", "value": 0.39 } ], "tags": [ "Code fixing" ] }, { "type": "watsonx.ai", "name": "Code", "description": "Evaluates a model's ability to fix coding errors in the C++, Go, Java, JavaScript, Python and Rust using 'HumanEval' dataset with introduced errors and unit tests to help identify problems. Metric represents the pass@1 score.", "language": "Go", "dataset": { "name": "HumanEvalFix" }, "metrics": [ { "name": "pass@1", "value": 0.421 } ], "tags": [ "Code fixing" ] }, { "type": "watsonx.ai", "name": "Code", "description": "Evaluates a model's ability to fix coding errors in the C++, Go, Java, JavaScript, Python and Rust using 'HumanEval' dataset with introduced errors and unit tests to help identify problems. Metric represents the pass@1 score.", "language": "Java", "dataset": { "name": "HumanEvalFix" }, "metrics": [ { "name": "pass@1", "value": 0.482 } ], "tags": [ "Code fixing" ] }, { "type": "watsonx.ai", "name": "Code", "description": "Evaluates a model's ability to fix coding errors in the C++, Go, Java, JavaScript, Python and Rust using 'HumanEval' dataset with introduced errors and unit tests to help identify problems. Metric represents the pass@1 score.", "language": "JavaScript", "dataset": { "name": "HumanEvalFix" }, "metrics": [ { "name": "pass@1", "value": 0.427 } ], "tags": [ "Code fixing" ] }, { "type": "watsonx.ai", "name": "Code", "description": "Evaluates a model's ability to fix coding errors in the C++, Go, Java, JavaScript, Python and Rust using 'HumanEval' dataset with introduced errors and unit tests to help identify problems. Metric represents the pass@1 score.", "language": "Python", "dataset": { "name": "HumanEvalFix" }, "metrics": [ { "name": "pass@1", "value": 0.402 } ], "tags": [ "Code fixing" ] }, { "type": "watsonx.ai", "name": "Code", "description": "Evaluates a model's ability to fix coding errors in the C++, Go, Java, JavaScript, Python and Rust using 'HumanEval' dataset with introduced errors and unit tests to help identify problems. Metric represents the pass@1 score.", "language": "Rust", "dataset": { "name": "HumanEvalFix" }, "metrics": [ { "name": "pass@1", "value": 0.28 } ], "tags": [ "Code fixing" ] }, { "type": "watsonx.ai", "name": "Code", "description": "", "language": "Python", "dataset": { "name": "livecodebench_selfrepair" }, "metrics": [ { "name": "pass@1", "value": 0.127 } ], "tags": [ "Code fixing" ] } ] } ], "model_limits": { "max_sequence_length": 128000, "max_output_tokens": 16384 }, "limits": { "3f6acf43-ede8-413a-ac69-f8af3bb0cbfe": { "call_time": "5m0s", "max_output_tokens": 16384 }, "a3d2f92f-06f9-48d0-b2e6-a7ba2b4e0577": { "call_time": "10m0s", "max_output_tokens": 16384 }, "d18d88b9-be7a-46ec-be1e-aff14904f1e9": { "call_time": "10m0s", "max_output_tokens": 16384 } }, "lifecycle": [ { "id": "available", "start_date": "2024-05-09" } ], "versions": [ { "version": "1.1.1", "available_date": "2024-10-28" }, { "version": "1.1.0", "available_date": "2024-09-03" }, { "version": "1.0.0", "available_date": "2024-05-09" } ] }

Generate code based on instruction

Define instructions for the model with at-least one example.

instruction = """Using the directions below, generate Python code for the given task. Input: # Write a Python function that prints 'Hello World!' string 'n' times. Output: def print_n_times(n): for i in range(n): print("Hello World!") <end of code> """

Prepare question for the model.

question = """Input: # Write a Python function, which generates sequence of prime numbers. # The function 'primes' will take the argument 'n', an int. It will return a list which contains all primes less than 'n'."""

Generate the code using ibm/granite-8b-code-instruct model

Inter the model to generate the code, according to provided instruction.

result = model.generate_text(" ".join([instruction, question]))

Formatting the text to get the function itself

code_as_text = result.split("Output:")[1].split("<end of code>")[0]

Generated code testing

The resulting code looks as below.

print(code_as_text)
def primes(n): primes = [] for num in range(2, n): is_prime = True for i in range(2, num): if num % i == 0: is_prime = False break if is_prime: primes.append(num) return primes

Use generated code to make it as function.

Note: Before executing this line, make sure the model's output visible above doesn't contain any malicious instructions.

exec(code_as_text)

Define the number 'n' for which the primes() function should process prime numbers.

n = 25

Test and run the generated function.

primes(n)
[2, 3, 5, 7, 11, 13, 17, 19, 23]

Summary and next steps

You successfully completed this notebook!

You learned how to generate code based on instuction with codellama-34b-instruct-hf on watsonx.

Check out our Online Documentation for more samples, tutorials, documentation, how-tos, and blog posts.

Authors:

Mateusz Szewczyk, Software Engineer at watsonx.ai.

Copyright © 2024-2026 IBM. This notebook and its source code are released under the terms of the MIT License.