コード生成プロンプトを作成する

gemini-1.0-pro モデルと code-bison モデルでは、自然言語での説明を使用してコードを生成できます。このトピックでは、サポートされているモデルと連携してコードを生成するプロンプトの作成方法について説明します。

ユースケース

コード生成の一般的なユースケースは次のとおりです。

  • 単体テスト - 関数の単体テストをリクエストするプロンプトを設計します。

  • 関数を記述する - モデルに問題を渡して、問題を解く関数を取得します。

  • クラスを作成する - プロンプトを使用してクラスの目的を説明し、返されるクラスを定義するコードを用意します。

サポートされているモデル

次のモデルはコード生成タスクをサポートしています。

  • gemini-1.0-pro
  • code-bison

コード生成プロンプトの例

以下の例を使用して、コード生成プロンプトの設計方法を学ぶことができます。

Docker スクリプトを生成する

Docker スクリプトは、コード生成モデルを使用して生成できます。次のプロンプトは、特定のライブラリがインストールされた Linux マシンを作成するための Docker スクリプトを生成します。


Generate a Docker script to create a simple linux machine that has python 3.10 installed with following libraries: pandas, tensorflow, numpy
  

```
# Create a new Dockerfile
FROM ubuntu:20.04

# Update the package list
RUN apt-get update

# Install Python 3.10
RUN apt-get install -y python3.10

# Install Python libraries
RUN pip install pandas tensorflow numpy

# Create a new user
RUN useradd -m user

# Set the default user
USER user

# Start the Python shell
CMD ["python"]
```

To build the Docker image, run the following command:

```
docker build -t my-python-image .
```

To run the Docker image, run the following command:

```
docker run -it --rm my-python-image
```

This starts a new container based on the `my-python-image` image. You can then use the Python shell to interact with the container. For example, you can install additional Python libraries or run Python scripts.
  

関数を生成する

コード生成モデルを使用して、関数を生成できます。次のプロンプトにより、年を入力してうるう年かどうかを判断する関数が生成されます。


Write a function that checks if a year is a leap year.
  

```python
def is_leap_year(year):
"""
def is_leap_year(year):
  """
  Check if a year is a leap year.

  Args:
    year: The year to check.

  Returns:
    True if the year is a leap year, False otherwise.
  """

  if year % 4 != 0:
    return False
  elif year % 100 == 0 and year % 400 != 0:
    return False
  else:
    return True
```
  

単体テストを生成する

コード生成モデルを使用して、単体テストを生成できます。

次のプロンプトでは、年がうるう年かどうかを判断する関数の単体テストが生成されます。


Write a unit test for this function:
def is_leap_year(year):
  """
  Check if a year is a leap year.

  Args:
    year: The year to check.

  Returns:
    True if the year is a leap year, False otherwise.
  """

  if year % 4 != 0:
    return False
  elif year % 100 == 0 and year % 400 != 0:
    return False
  else:
    return True
  

```python
import unittest

class IsLeapYearTest(unittest.TestCase):

    def test_is_leap_year_true(self):
        self.assertTrue(is_leap_year(2000))
        self.assertTrue(is_leap_year(2004))
        self.assertTrue(is_leap_year(2012))

    def test_is_leap_year_false(self):
        self.assertFalse(is_leap_year(1900))
        self.assertFalse(is_leap_year(1999))
        self.assertFalse(is_leap_year(2100))

    def test_is_leap_year_invalid_input(self):
        with self.assertRaises(TypeError):
            is_leap_year("2000")

if __name__ == '__main__':
    unittest.main()
```
  

次のステップ