본문 바로가기
AI 공부/LLM

[LLM] LLM을 이용한 페어 프로그래밍: GEMINI API 활용 방법

by 데이터 벌집 2024. 9. 3.
반응형

프로그래밍을 할 때, 특히 복잡한 문제를 해결할 때 페어 프로그래밍은 매우 유용합니다. 페어 프로그래밍은 두 명의 개발자가 함께 코드를 작성하는 방식으로, 한 명이 코드를 작성하고 다른 한 명이 이를 검토합니다. 최근에는 LLM(대규모 언어 모델)을 이용하여 가상 페어 프로그래밍 파트너를 만드는 것이 가능해졌습니다. 이 글에서는 GEMINI API를 사용하여 LLM을 페어 프로그래밍 파트너로 활용하는 방법을 설명합니다.

 

[LLM] LLM을 이용한 페어 프로그래밍: GEMINI API 활용 방법

 

1. GEMINI API 설정

먼저, GEMINI API를 설정해야 합니다. 이 API를 통해 LLM과 상호작용하여 코드 개선을 요청할 수 있습니다. 아래는 API 설정 코드입니다:

import os
import google.generativeai as genai
from dotenv import load_dotenv
load_dotenv()

GOOGLE_API_KEY = os.environ['GOOGLE_API_KEY']
genai.configure(api_key = os.environ['GOOGLE_API_KEY'])


# Create the model
generation_config = {
  "temperature": 1,
  "top_p": 0.95,
  "top_k": 64,
  "max_output_tokens": 8192,
  "response_mime_type": "text/plain",
}

model = genai.GenerativeModel(
  model_name="gemini-1.5-pro",
  generation_config=generation_config,
  # safety_settings = Adjust safety settings
  # See https://ai.google.dev/gemini-api/docs/safety-settings
)

chat_session = model.start_chat(
  history=[
  ]
)

 

이 코드를 통해 GEMINI API와 연동하여, LLM을 사용한 코드 개선 요청을 수행할 수 있습니다.

2. LLM에게 코드 개선 요청하기

GEMINI API를 설정한 후, 이제 LLM을 활용해 다양한 코드 개선 요청을 할 수 있습니다. 아래는 몇 가지 예시 프롬프트입니다.

  • 기본 코드 개선: "이 코드를 간단하고 효율적으로 개선해 주세요."
  • 가독성 향상: "이 코드의 가독성을 높일 수 있는 방법을 알려주세요."
  • 중복 코드 제거: "중복된 로직을 함수화하여 코드의 길이를 줄여주세요."
  • 모듈화 및 재사용성: "이 코드를 모듈화하여 재사용할 수 있게 바꿔주세요."
  • 에러 처리 추가: "예외 상황에 대한 처리가 포함된 코드로 개선해 주세요."

예를 들어, 간단한 코드의 가독성을 높이기 위해 LLM에 아래와 같이 요청할 수 있습니다:

```python
def process_data(data_list):
  """
  Processes a list of numbers according to the following rules:

  - Even numbers are multiplied by 2.
  - Odd numbers less than 10 are incremented by 10.
  - Other odd numbers remain unchanged.
  - Finally, every other element in the resulting list is multiplied by 2.

  Args:
    data_list: A list of integers.

  Returns:
    A new list with the processed data.
  """
  result = []
  for i, num in enumerate(data_list):
    if num % 2 == 0:
      result.append(num * 2)
    elif num < 10:
      result.append(num + 10)
    else:
      result.append(num)

  for i in range(0, len(result), 2):
    result[i] *= 2

  return result

data = [5, 8, 12, 3, 7, 10]
print(process_data(data))
```

**Improvements:**

- **Added docstrings:** Docstrings (triple quotes) provide a clear explanation of what the function does and how it works.
- **Used `enumerate`:**  Instead of iterating through indices with `range(len(...))`, using `enumerate` provides both the index and value directly, making the code cleaner.
- **Simplified conditional logic:** The nested `if/else` block was flattened for better readability.
- **Used augmented assignment:**  `result[i] *= 2` is more concise than `result[i] = result[i] * 2`.
- **Modified loop for even index multiplication:** Iterating over the list with a step of 2 efficiently multiplies every other element.

**These changes make the code more Pythonic, readable, and potentially slightly more efficient due to the optimized loop for even index multiplication.**

 

3. 코드 개선 결과 확인

위의 프롬프트를 통해 LLM이 제안한 개선된 코드를 받을 수 있습니다. LLM은 더 효율적인 코드 구조를 제안하거나, 가독성을 높이는 방법을 제시할 수 있습니다. 이를 통해 개발자는 더욱 깔끔하고 유지보수가 용이한 코드를 작성할 수 있게 됩니다.

 

```python
def process_data(data_list):
  """
  Processes a list of numbers according to the following rules:

  - Even numbers are multiplied by 2.
  - Odd numbers less than 10 are incremented by 10.
  - Other odd numbers remain unchanged.
  - Finally, every other element in the resulting list is multiplied by 2.

  Args:
    data_list: A list of integers.

  Returns:
    A new list with the processed data.
  """
  result = []
  for i, num in enumerate(data_list):
    if num % 2 == 0:
      result.append(num * 2)
    elif num < 10:
      result.append(num + 10)
    else:
      result.append(num)

  for i in range(0, len(result), 2):
    result[i] *= 2

  return result

data = [5, 8, 12, 3, 7, 10]
print(process_data(data))
```

**Improvements:**

- **Added docstrings:** Docstrings (triple quotes) provide a clear explanation of what the function does and how it works.
- **Used `enumerate`:**  Instead of iterating through indices with `range(len(...))`, using `enumerate` provides both the index and value directly, making the code cleaner.
- **Simplified conditional logic:** The nested `if/else` block was flattened for better readability.
- **Used augmented assignment:**  `result[i] *= 2` is more concise than `result[i] = result[i] * 2`.
- **Modified loop for even index multiplication:** Iterating over the list with a step of 2 efficiently multiplies every other element.

**These changes make the code more Pythonic, readable, and potentially slightly more efficient due to the optimized loop for even index multiplication.**

4. 결론

LLM을 활용한 코드 개선은 개발자가 직면하는 다양한 문제를 해결하는 데 큰 도움이 됩니다. GEMINI API를 사용하면 이러한 작업을 더욱 간편하게 수행할 수 있으며, 다양한 프롬프트를 통해 원하는 방식으로 코드를 발전시킬 수 있습니다. 이 방법을 사용해 여러분의 코드를 한 단계 업그레이드해 보세요!

반응형