LLM Day 2

Soyee Sung·2025년 1월 27일
0

LLM

목록 보기
3/34

LLM 생성 원리

OpenAI Chat Completion API 활용

  • poetry 프로젝트 설정
    - poetry --version
echo 'export PATH="/opt/homebrew/bin/python3:$PATH"' >> ~/.zshrc
source ~/.zshrc```

    - 프로젝트 추가 : `poetry new [프로젝트명]`
    - 가상환경 생성 : `poetry install`
    - poetry env use $(which python3)
    - 가상환경 확인 : `poetry env info`
    - 패키지 설치 : `poetry add langchain langchain_openai python-dotenv`
      poetry add jupyter ipykernel
      poetry run python -m ipykernel install --user --name=llm30-etf --display-name "Python (llm30-etf)"

    - .env 파일 만들고 API 키 등록: `touch .env`
      [open AI key 발급하고 사용하기](https://velog.io/@ji1kang/OpenAI%EC%9D%98-API-Key-%EB%B0%9C%EA%B8%89-%EB%B0%9B%EA%B3%A0-%ED%85%8C%EC%8A%A4%ED%8A%B8-%ED%95%98%EA%B8%B0)
    
🛠 추가 문제 해결
1️⃣ Poetry가 Python을 찾지 못하는 경우

brew link --overwrite python@3.13

이후 다시 poetry env use /opt/homebrew/opt/python@3.13/bin/python3 실행

2️⃣ Homebrew로 설치한 Python을 기본 Python으로 설정하고 싶다면

echo 'export PATH="/opt/homebrew/opt/python@3.13/bin:$PATH"' >> ~/.zshrc
source ~/.zshrc

    
- python script 
 

from openai import OpenAI
from dotenv import load_dotenv
import os

client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

.env 파일에서 API 키를 가져옵니다.

load_dotenv()

def generate_response(prompt, model="gpt-4", max_tokens=150, temperature=0.7):
"""
최신 OpenAI Python 라이브러리 형식에 맞는 API 호출.
"""
try:

    # .env 파일에서 API 키를 가져옵니다.
    if not openai.api_key:
        raise ValueError("API key is missing. Please set it in the .env file.")

    # OpenAI API 호출 (최신 방식)
    response = client.chat.completions.create(model=model,
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": prompt}
    ],
    max_tokens=max_tokens,
    temperature=temperature)

    # API 호출 결과에서 메시지 내용 추출
    return response.choices[0].message.content

except Exception as e:
    return f"An error occurred: {e}"

if name == "main":

# 사용자 입력 예시
user_prompt = "Explain the concept of machine learning in simple terms."

# 응답 생성 및 출력
result = generate_response(user_prompt)
print(result)

0개의 댓글