# API KEY를 환경변수로 관리하기 위한 설정 파일
from dotenv import load_dotenv
# API KEY 정보로드
load_dotenv
from langchain_openai import ChatOpenAI
# ChatOpenAI()를 이용해 llm 객체 생성
llm = ChatOpenAI(
temperature=1.5, # 창의성 (0.0 ~ 2.0)
model_name="gpt-4o", # 모델명
max_tokens = 100
)
# 질의내용
question = "제습기의 강력한 성능을 홍보하는 문구를 작성해주세요"
# 질의
print(f"[답변]: {llm.invoke(question)}")

# 답변만 출력
response.content
# metadata만 출력
response.response_metadata
# token_usage 딕셔너리 안에 있는 total_tokens 키의 값을 출력
response.response_metadata["token_usage"]["total_tokens"]
stream 옵션을 사용해 응답을 한꺼번에 받는 게 아니라 토큰 단위로 순차적으로 받을 수 있다. 마치 실시간 응답하는 것처럼 보인다.
answer = llm.stream("대한민국의 아름다운 관광지 10곳과 주소를 알려주세요!")
# 스트리밍 방식으로 각 토큰을 출력합니다. (실시간 출력)
for token in answer:
print(token.content, end="", flush=True) #end = "" 줄바꿈 없이 이어서 출력 flush=True= 버퍼(Buffer)를 강제로 비워 즉시 콘솔에 출력
# 스트리밍 방식으로 각 토큰을 출력
final_answer = ""
for token in answer:
print(token.content, end="", flush=True)
final_answer += token.content #각 토큰을 하나의 문자열로 붙여 저장
print(final_answer)