

# 생성하고자 하는 템플릿 예시
'''
모든 입력에 대한 반의어를 추천(추론)해 주세요 <- 접두사
<- 구분기호
입력:선 <- 답변예시
출력:악 <- 답변예시
<- 구분기호
입력:밝음 <- 답변예시
출력:어둠 <- 답변예시
<- 구분기호
입력:상승장 <- 접미사
출력:
'''
# 출력에 대한 추론은 llm 이 알아서 판단
# 동적 구성
samples = [
{
'input':'선',
'output':'악'
},
{
'input':'밝음',
'output':'어둠',
}
]
basic_prompt = PromptTemplate(
input_variables = ['input', 'output'], # 입력변수 2개
template = '입력: {input}\n출력: {output}', # 템플릿 설정 -> 복잡한 구성이 예측됨, jinja2 사용 필요등...
)
from langchain.prompts import FewShotPromptTemplate
# 답변예시용
fewshow_prompt = FewShotPromptTemplate(
input_variables=['keyword'], # 입력변수 1개
examples=samples, # 답변 예시
example_prompt=basic_prompt, # 답변예시 형태
prefix='모든 입력에 대한 반의어를 추천(추론)해 주세요', # 접두사
suffix='입력: {keyword}\n출력: ', # 접미사
example_separator='\n\n', # 구분기호
)
prompt = fewshow_prompt.format( keyword='상승장' )
print( prompt )


from langchain.prompts.example_selector import SemanticSimilarityExampleSelector
# 유사도 사용
from langchain.vectorstores import FAISS
from langchain_openai import OpenAIEmbeddings
samples = [
{
'input':'자동차',
'output':'운전자'
},
{
'input':'프로그램',
'output':'개발자'
},
{
'input':'동영상',
'output':'PD'
}
]
basic_prompt = PromptTemplate(
input_variables = ['input', 'output'], # 입력변수 2개
template = '입력: {input}\n출력: {output}', # 템플릿 설정 -> 복잡한 구성이 예측됨, jinja2 사용 필요등...
)
# 유사도를 고려하여 샘플 선택
example_selector = SemanticSimilarityExampleSelector.from_examples(
examples=samples, # 샘플
embeddings=OpenAIEmbeddings(), # 임베딩 처리용 토크나이저용도
vectorstore_cls=FAISS, # 백터 디비, 유사도 계산을 사용할 수 있는 제품
k = 2 # 답변 예시는 2개로 제한 (샘플이 3개이므로 유사도 기준 2개만 선정)
)
fewshow_prompt = FewShotPromptTemplate(
example_selector=example_selector, # 길이 제한 부여
example_prompt=basic_prompt, # 답변예시 형태
input_variables=['keyword'], # 입력변수 1개
prefix='모든 입력에 대한 연관어를 추천(추론)해 주세요', # 접두사
suffix='입력: {keyword}\n출력: ', # 접미사
example_separator='\n\n', # 구분기호
)
prompt = fewshow_prompt.format( keyword='이케아' )
print( prompt )
print( model.invoke( prompt ) )








































RAG (Retrieval-Augmented Generation) 는 "검색 기반 생성" 기법으로, LLM (대형 언어 모델)과 외부 데이터베이스(백터DB) 를 결합하여 더욱 정확하고 신뢰성 높은 응답을 생성하는 방식입니다.






- query.html
```
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js" integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4=" crossorigin="anonymous"></script>
</head>
<body>
<fieldset>
<label>무엇이 궁금하세요?</label>
<form id="query_input">
<textarea name="question">해리포터의 mbti는?</textarea>
<input type="submit" value='질문 하기'>
</form>
</fieldset>
<script>
$('#query_input').on('submit', e=>{
e.preventDefault()
console.log('질문 하기 클릭', $('[name=question]').val())
// 서버 전송
$.post({
url :'/query',
data:JSON.stringify({
'question':$('[name=question]').val()
}),
contentType: "application/json; charset=utf-8",
dataType:'json',
success:res=>{
console.log( '성공', res)
},
error:err=>{
console.log( '실패', err)
}
})
return false
})
</script>
</body>
</html>
```








