목 차
1. LLM이란 무엇인가?
2. LLM의 작동 원리
3. LLM의 파라미터와 모델 크기
4. LLM의 협력 시스템(멀티 에이전트)
5. LLM의 학습과 피드백
6. LLM을 활용한 서비스 구현
GPT-4o: OpenAI에서 개발한 최신 모델로, 다양한 언어와 작업을 지원합니다.
Claude 3: Anthropic에서 개발한 모델로, 안전성과 정확성을 강조합니다.
Grok3: xAI에서 개발한 모델로, 인간의 과학적 발견을 가속화하는 것을 목표로 합니다.
텍스트 생성: 주어진 프롬프트에 따라 문장을 생성합니다.
코딩: 코드 작성, 디버깅, 설명 등을 할 수 있습니다.
이미지 분석: 이미지에 대한 설명을 제공하거나, 이미지와 관련된 질문에 답변할 수 있습니다.
수식 풀이: 수학 문제를 이해하고 풀이 과정을 설명할 수 있습니다.
from openai import OpenAI
# OpenAI API 키 설정
client = OpenAI(api_key="YOUR_API_KEY")
# 모델과 프롬프트 설정
MODEL = "gpt-4o"
prompt = "Hello, how are you?"
# 문장 생성
completion = client.chat.completions.create(
model=MODEL,
messages=[{"role": "user", "content": prompt}],
)
print("Assistant: " + completion.choices[0].message.content)
LLM은 텍스트를 입력받아 이를 토큰화하고, 학습된 데이터를 기반으로 다음 토큰을 예측합니다.
API 호출: LLM은 직접 API를 호출하지 않으며, 실제 호출은 개발자가 코드로 구현해야 합니다.
LLM이 아무리 똑똑해도,
이미 학습한 데이터만 가지고 답을 생성하게 된다는 단점이 있습니다.
그럼 최신 뉴스나 사내 문서 같은 정보는 어떻게 불러오는걸까요?
그때 필요한 게 RAG입니다.
외부 데이터베이스에서 필요한 정보를 먼저 검색(Retrieval)하고,
그 정보를 기반으로 답변을 생성(Generation)하는 방식입니다.
이렇게 하면 LLM이 최신 정보도 반영하여 결과를 Return 할 수 있습니다.
즉, LLM이 대답하기 이전에 먼저 대답에 필요한 자료들을 넣어주고,
요약 또는 이를 기반으로 대답하는걸 모두 RAG라고 하는거죠
from openai import OpenAI
# OpenAI API 키 설정
client = OpenAI(api_key="YOUR_API_KEY")
# 모델과 프롬프트 설정
MODEL_1 = "gpt-4o" # 8B 파라미터
MODEL_2 = "gpt-4o-large" # 70B 파라미터
prompt = "What is the difference between AI and ML?"
# 문장 생성
completion_1 = client.chat.completions.create(
model=MODEL_1,
messages=[{"role": "user", "content": prompt}],
)
completion_2 = client.chat.completions.create(
model=MODEL_2,
messages=[{"role": "user", "content": prompt}],
)
print("Model 1 (8B): " + completion_1.choices[0].message.content)
print("Model 2 (70B): " + completion_2.choices[0].message.content)
LLM이 혼자서 모든 작업을 처리하는 것이 아니라, 여러 개의 작은 AI(에이전트)가 협력하는 방식입니다.
속도와 정확성: 이렇게 역할을 나누면 속도도 빠르고, 더 정확한 답변이 가능해집니다.
import { Agentica } from "@agentica/core";
import typia from "typia";
// Agentica 인스턴스 생성
const agent = new Agentica({
controllers: [
typia.llm.application<ShoppingCounselor>(),
typia.llm.application<ShoppingPolicy>(),
],
});
// 대화 시작
await agent.conversate("I want to buy a MacBook Pro.");
LLM이 항상 정답을 말하는 것은 아니므로, 틀린 답변을 줄 수도 있습니다.
이를 자동화하여 LLM이 스스로 학습하는 시스템을 만들 수 있습니다.
이는 LLM의 성능을 지속적으로 향상시키는 데 도움이 됩니다.
피드백 루프
: 사용자로부터 피드백을 받고 이를 모델에 반영하는 과정을 반복하여 LLM의 성능을 개선합니다.
from openai import OpenAI
# OpenAI API 키 설정
client = OpenAI(api_key="YOUR_API_KEY")
# 모델과 프롬프트 설정
MODEL = "gpt-4o"
prompt = "What is the capital of France?"
# 문장 생성
completion = client.chat.completions.create(
model=MODEL,
messages=[{"role": "user", "content": prompt}],
)
# 피드백 반영
if completion.choices[0].message.content != "Paris":
# 피드백을 통해 모델을 개선합니다.
print("Incorrect answer. Providing feedback...")
else:
print("Correct answer!")
import openai
# OpenAI API 키 설정
openai.api_key = "YOUR_API_KEY"
# 모델과 프롬프트 설정
MODEL = "gpt-4o"
tools = [
{
"type": "function",
"name": "get_weather",
"description": "Get current temperature for provided coordinates in celsius.",
"parameters": {
"type": "object",
"properties": {
"latitude": {"type": "number"},
"longitude": {"type": "number"},
},
"required": ["latitude", "longitude"],
"additionalProperties": False,
},
"strict": True,
},
]
input = [
{"role": "user", "content": "What's the weather like in Paris today?"},
]
# 함수 호출을 포함한 응답 생성
response = openai.responses.create(
model=MODEL,
input=input,
tools=tools,
)
# 함수 호출 결과 처리
for tool_call in response.output:
if tool_call.type != "function_call":
continue
name = tool_call.name
args = json.loads(tool_call.arguments)
result = get_weather(args["latitude"], args["longitude"])
# 결과를 모델에 반영
input.append(
{
"type": "function_call_output",
"call_id": tool_call.call_id,
"output": str(result),
}
)
# 최종 응답 생성
response2 = openai.responses.create(
model=MODEL,
input=input,
tools=tools,
)
print(response2.output_text)