고수준 API로 텍스트 생성하기

고수준 API로 텍스트 생성하기

llama-cpp-python은 두 가지 레벨의 API를 제공해요. 그중 고수준 API는 Llama 클래스 하나로 모델을 로드하고 텍스트 생성을 끝내는, 관리형 인터페이스예요.

출처: https://github.com/abetlen/llama-cpp-python

Llama 클래스는 GGUF 모델 경로를 받아 인스턴스로 만들고, 그 인스턴스를 함수처럼 호출해 생성 결과를 얻어요. 기본적으로 OpenAI 호환 형식으로 결과를 돌려줍니다. 간단한 예제를 볼게요.

from llama_cpp import Llama

llm = Llama(
      model_path="./models/7B/llama-model.gguf",
      # n_gpu_layers=-1, # Uncomment to use GPU acceleration
      # seed=1337, # Uncomment to set a specific seed
      # n_ctx=2048, # Uncomment to increase the context window
)
output = llm(
      "Q: Name the planets in the solar system? A: ", # Prompt
      max_tokens=32, # Generate up to 32 tokens, set to None to generate up to the end of the context window
      stop=["Q:", "\n"], # Stop generating just before the model would generate a new question
      echo=True # Echo the prompt back in the output
) # Generate a completion, can also call create_completion
print(output)

max_tokens는 생성할 최대 토큰 수, stop은 거기서 멈추는 시그널 문자열들, echo는 프롬프트를 출력에 되돌려 포함할지예요. 주석에 적어 둔 대로 GPU 가속은 n_gpu_layers=-1, 시드는 seed, 컨텍스트 창은 n_ctx로 조절할 수 있어요.

응답은 OpenAI 호환 형식으로 돌아와요. id, object, created 같은 필드를 포함하는 표준 구조를 갖추고 있어서 기존 OpenAI API 기반 코드를 거의 그대로 옮겨 쓸 수 있어요. 랭체인, LlamaIndex 통합도 지원해요.

더 낮은 통제가 필요하면 C API를 직접 다루는 저수준 API도 있는데, 고수준 API가 대부분의 경우로는 충분해요.

더 알아보기