[LangChain] Prompt Template 사용 방법 정리

2024. 1. 20. 12:57관심있는 주제/ChatGPT Prompt

728x90

 

 

langchain에서 사용하는 prompt에 대해서 정리해보고자 합니다.

 

이런 식으로 굉장히 다양한 promptTemplate가 있기 때문에 정리하고자 한다.

모든 것을 커버할 수는 없지만 최대한 자주 사용할 것 같은 것들을 기준으로 정리해보고자 한다.

 

버전

0.1.1 버전을 기준으로 정리해서, 추후에 이 template은 의미가 없어질 수 있지만 큰 개념으로 이해하면 좋을 것 같다.

프롬프트 함수 정리

아래에는 langchain에서 사용하는 prompt를 정리한 내역을 보면 다음과 같다.

 

전체

from langchain.prompts import (
    PromptTemplate,
    PipelinePromptTemplate,
    MessagesPlaceholder,
    ChatPromptTemplate,
    HumanMessagePromptTemplate,
    SystemMessagePromptTemplate,
    AIMessagePromptTemplate,
    FewShotChatMessagePromptTemplate,
    FewShotPromptWithTemplates
)

 

 

Prompt란?

언어 모델에 대한 프롬프트는 사용자가 제공하는 지침이나 입력의 집합으로, 모델의 응답을 안내하고 문맥을 이해하며 질문에 답하거나 문장을 완성하거나 대화를 나누는 등 관련성 있고 일관된 언어 기반 출력을 생성하는 데 도움을 주는 역할을 합니다.

 

하지만 일반적으로 사용자들이 일반적인 질문을 하게 되면 원하는 결과가 나오지 않는 경우가 많이 나온다.

그래서 prompt engineering이라는 것이 필요하게 된다.

 

Prompt Engineering이란?

프롬프트 엔지니어링의 주요 목표는 사용자의 의도와 원하는 결과를 전달하는 프롬프트를 만들어 모델의 성능, 정확성, 유용성을 극대화하는 것이다. 프롬프트 엔지니어링이 필요한 이유는 현재 LLM의 동작 방식의 한계와 인간과 컴퓨터의 상호 작용을 위해 자연어를 사용하고 있기 때문이다.

프롬프트는 일반적으로 여러 부분으로 구성된다.

 

모든 프롬프트가 이러한 구성 요소를 사용하는 것은 아니지만, 좋은 프롬프트는 일반적으로 두 개 이상의 구성 요소를 사용합니다. 이들을 더 정확하게 정의해 보겠습니다.

 

구성요소 설명
Instructions 모델에게 무엇을 해야 하는지, 제공된 경우 외부 정보를 어떻게 사용해야 하는지, 쿼리와 어떻게 처리해야 하는지, 출력물을 어떻게 구성해야 하는지 알려주는 부분입니다.
External information or context(s) 모델에 대한 추가 지식의 원천 역할을 합니다. 이 정보는 프롬프트에 수동으로 삽입될 수 있으며, 벡터 데이터베이스를 통해 검색된 정보일 수도 있고 다른 수단(API, 계산 등)을 통해 가져올 수도 있습니다.
User input or query 일반적으로 (항상 그렇지는 않지만) 인간 사용자(프롬프트 생성자)가 시스템에 입력한 쿼리입니다.
Output indicator 생성될 텍스트의 시작을 나타냅니다. 예를 들어 Python 코드를 생성하는 경우, 대부분의 Python 스크립트가 'import'로 시작하므로 모델에게 Python 코드 작성을 시작해야 한다는 것을 나타낼 수 있습니다.


이러한 구성 요소는 일반적으로 위에서 아래 순서대로 프롬프트에 배치됩니다. 즉, 지침, 외부 정보(해당하는 경우), 사용자 입력 및 마지막으로 출력 지시자인 형태로 보통 놔둡니다. 

왜냐하면 llm 은 결국 transformer 구조를 가지고 있고, attention이 있기는 하지만, auto regressive 기반으로 보통 만들어지니까, 가장 마지막에 위치한 인풋이 가장 영향을 많이 준다.

 

그래서 이 방법은 openai에 대한 api를 이용할 때뿐만 아니라 web에서 이러한 형태를 잘 기억해서 물어보는 것은 좀 더 원하는 답을 찾는 데 도움을 줄 것이다.

 

이외에도 여러가지 방식은 있지만, 그것도 생각보다 테크닉도 많고 복잡한 영역인 것 같아 다음에 시간이 되면 정리해보고자 한다.

 

 

Prompt Template이란?

LangChain 프롬프트 템플릿은 무엇입니까? LangChain의 공식 문서에는 다음과 같이 적혀 있습니다.

"프롬프트 템플릿은 프롬프트를 생성하는 재현 가능한 방법을 나타냅니다." 

프롬프트 템플릿에는 다음이 포함될 수 있습니다: 
 
 - 언어 모델에 대한 지침
 - 언어 모델을 돕기 위한 몇 가지 샷 예제 세트 더 나은 응답
 

즉 prompt template는 위에서 말한 ai가 잘 이해할 수 있는 형태로 만들어주는 prompt engineering을 쉽게 하기 위한 예시 형태들이라고 보면 될 것 같다.

 

이번 글에서는 위에서 나온 template의 대한 예시들을 통해 차이점을 확인해 보고 정리해보고자 한다.

 

LangChain Prompt Template 실습

여기서는 openai와 같은 llm을 붙이는 것을 이야기 하지 않고, prompt template에 최대한 초점을 맞춰서 말하고자 한다.

 

llm 적용 예시

예시는 다음과 같은 것들이 있다.

- predict

- llmchain

- lcel

# instantiate the OpenAI intance
llm = OpenAI()

# make a prediction
prediction = llm.predict(prompt_formatted_str)

# print the prediction
print(prediction)

chat_model: ChatOpenAI = ChatOpenAI()

chain: LLMChain = LLMChain(llm=chat_model, prompt=chat_prompt)

# make a call to the models
prediction_msg: dict = chain.run(
    original_sentence="I love Pizza!", desired_language="French")


chain = chat_prompt | chat_model
chain.invoke(dict(original_sentence="I love Pizza!", desired_language="French"))

 

 

Prompt

from langchain.prompts.prompt import PromptTemplate

 

아래 예시를 보면 prompt_template이라는 전반적인 틀을 만들고, 그 안에 {question}이라는 것에 변수를 받을 부분을 남겨 놓는 식으로 기본 template에 사용할 전반적인 구조를 구성한 것이다.

 

이러한 형태는 question이라는 것은 매번 바뀔 수 있지만, 나머지 앞 뒤에 있는 내용(instruction 등등)은 고정이 되기 때문에 이러한 모양으로 구성을 한 것이고 사용자는 question을 물어보게 해서 기존에 있던 template을 여러 번 반복해서 사용할 수 있게 된다.

# create the prompt
prompt_template: str = """/
You are a vehicle mechanic, give responses to the following/ 
question: {question}. Do not use technical words, give easy/
to understand responses.
"""

prompt = PromptTemplate.from_template(template=prompt_template)

# format the prompt to add variable values
prompt_formatted_str: str = prompt.format(
    question="Why won't a vehicle start on ignition?")
print(prompt_formatted_str)

 

아래 답을 보면 {question} 부분에 사용자가 입력한 데이터가 들어간 것을 알 수 있다.

You are a vehicle mechanic, give responses to the following/ 
question: Why won't a vehicle start on ignition?. Do not use technical words, give easy/
to understand responses.

 

이런 식으로 question만 바꿔가면서 동일한 질문에 대한 처리를 할 수 있어서 복잡도를 많이 낮출 수 있게 된다.

# format the prompt to add variable values
prompt_formatted_str: str = prompt.format(
    question="Test 1234")
print(prompt_formatted_str)

 

/
You are a vehicle mechanic, give responses to the following/ 
question: Test 1234. Do not use technical words, give easy/
to understand responses.

 

 

Partial with strings

promptTemplate을 사용하다보면 반드시 항상 동일한 시점에 variable이 나오는 경우가 없다

그래서 부분적으로 미리 넣을 수 있는 방식이 있어서 공유한다.

 

prompt = PromptTemplate(
    template="{foo}{bar}", input_variables=["bar"], partial_variables={"foo": "foo"}
)
print(prompt.format(bar="baz"))

 

Partial with functions

아래는 단순히 값이 아닌 함수를 넣어서 매번 업데이트되는 문자형태의 결과를 얻을 수 있게 하는 것이고

여기서는 시간을 매번 바꿔서 넣을 수 있게 했다.

from datetime import datetime


def _get_datetime():
    now = datetime.now()
    return now.strftime("%m/%d/%Y, %H:%M:%S")


prompt = PromptTemplate(
    template="Tell me a {adjective} joke about the day {date}",
    input_variables=["adjective", "date"],
)
partial_prompt = prompt.partial(date=_get_datetime)
print(partial_prompt.format(adjective="funny"))

 

 

 

Chat

위에서는 단순히 명령을 하는 방식의 prompt template였다면, 아래는 chat을 이용한 prompt template에 대한 것이다.

이러한 작업 같은 경우 결국 봇과의 대화의 구분이나 이 대화의 전반적인 구조에 대한 설명을 필요로 하기 때문에

System, Human,  AI 와 같이 각각의 역할에 따른 Template이 나눠져 있다고 보면 된다.

from langchain.prompts.chat import (
    ChatPromptTemplate,
    SystemMessagePromptTemplate,
    HumanMessagePromptTemplate,
    AIMessagePromptTemplate,
    MessagesPlaceholder
)

 

방법 1

아래는 봇에게 번역을 하라는 예시의 template이다.

우선 전반적은 봇에 대한 system을 적용하고 위해 sys_prompt를 먼저 구성을 한다.

그다음에 사용자 질의에 다가 번역을 해야 하는 의미를 추가해야 하니

"Translate {original_sentence} to {desired_language}"

와 같이 앞 뒤로 명령할 부분들을 추가해주는 것을 확인할 수 있다.

그래서 실제로 사용하는 I love Pizza! 와 바꾸고자 하는 다른 언어를 선택하면 프롬프트 엔지니어링을 통해 변경해 준다.

# Create the first prompt template
sys_prompt: PromptTemplate = PromptTemplate(
    input_variables=["original_sentence", "desired_language"],
    template="""You are a language translater, an English speaker wants to translate/
    {original_sentence} to {desired_language}. Tell him the corrent answer."""
)

system_message_prompt = SystemMessagePromptTemplate(prompt=sys_prompt)

student_prompt: PromptTemplate = PromptTemplate(
    input_variables=["original_sentence", "desired_language"],
    template="Translate {original_sentence} to {desired_language}"
)
student_message_prompt = HumanMessagePromptTemplate(prompt=student_prompt)

chat_prompt = ChatPromptTemplate.from_messages(
    [system_message_prompt, student_message_prompt])
    
print(chat_prompt)
print("="*100)
print(chat_prompt.format(original_sentence="I love Pizza!", desired_language="French"))

 

그러면 아래와 같이 사용자는 아래의 2개를 입력하면, 뒤에서는 아래와 같이 system을 구분해 주는 것과 humain이 질문했다는 것을 나눠주는 것을 알 수 있다.

original_sentence="I love Pizza!"

desired_language="French"

input_variables=['desired_language', 'original_sentence'] messages=[SystemMessagePromptTemplate(prompt=PromptTemplate(input_variables=['desired_language', 'original_sentence'], template='You are a language translater, an English speaker wants to translate/\n    {original_sentence} to {desired_language}. Tell him the corrent answer.')), HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['desired_language', 'original_sentence'], template='Translate {original_sentence} to {desired_language}'))]
====================================================================================================
System: You are a language translater, an English speaker wants to translate/
    I love Pizza! to French. Tell him the corrent answer.
Human: Translate I love Pizza! to French

 

 

방법 2

위에서는 class를 사용한 예시지만, 아래에서는 굳이 그렇게 사용하지 않고, tuple로 "system" "human"을 입력해 주면 인식한다는 것을 알려주는 코드이다.

 

크게 가능한 것은 다음과 같다.

  1. user
  2. ai
  3. assistant
  4. system

현재는 이 4개만 가능하다고 한다.

chat_template = ChatPromptTemplate.from_messages(
    [
        ("system", "You are a language translater, an English speaker wants to translate/{original_sentence} to {desired_language}. Tell him the corrent answer."),
        ("human", "Translate {original_sentence} to {desired_language}"),
    ]
)

messages = chat_template.format_messages(original_sentence="I love Pizza!", desired_language="French")
messages

 

아래와 같이 정해진 규칙에 따라서 자동으로 맵핑되는 것을 알 수 있다.

[SystemMessage(content='You are a language translater, an English speaker wants to translate/I love Pizza! to French. Tell him the corrent answer.'),
 HumanMessage(content='Translate I love Pizza! to French')]

 

MessagePlaceholder - 1

아래는 메시지 공간을 놔두고 거기 안에 많은  message를 넣은 예시이다.

 

human_prompt = "Summarize our conversation so far in {word_count} words."
human_message_template = HumanMessagePromptTemplate.from_template(human_prompt)

chat_prompt = ChatPromptTemplate.from_messages(
    [MessagesPlaceholder(variable_name="conversation"), human_message_template]
)



human_message = HumanMessage(content="What is the best way to learn programming?")
ai_message = AIMessage(
    content="""\
1. Choose a programming language: Decide on a programming language that you want to learn.

2. Start with the basics: Familiarize yourself with the basic programming concepts such as variables, data types and control structures.

3. Practice, practice, practice: The best way to learn programming is through hands-on experience\
"""
)

chat_prompt.format_prompt(
    conversation=[human_message, ai_message], word_count="10"
).to_messages()

 

[HumanMessage(content='What is the best way to learn programming?'),
 AIMessage(content='1. Choose a programming language: Decide on a programming language that you want to learn.\n\n2. Start with the basics: Familiarize yourself with the basic programming concepts such as variables, data types and control structures.\n\n3. Practice, practice, practice: The best way to learn programming is through hands-on experience'),
 HumanMessage(content='Summarize our conversation so far in 10 words.')]

 

print(chat_prompt.format(
    conversation=[human_message, ai_message], word_count="10"
)   )
Human: What is the best way to learn programming?
AI: 1. Choose a programming language: Decide on a programming language that you want to learn.

2. Start with the basics: Familiarize yourself with the basic programming concepts such as variables, data types and control structures.

3. Practice, practice, practice: The best way to learn programming is through hands-on experience
Human: Summarize our conversation so far in 10 words.

 

 

MessagePlaceholder  - 2

조금 복잡하지만 밑에는 buffer에 채팅 기록을 담는 코드이다.

위에서는 먼가 객체로 가지고 있어야 하지만, 아래는 따로 buffermemory라는 것을 이용해서 메시지를 계속 저장하는 방식이다. 

from langchain.chat_models import ChatOpenAI
from langchain.memory import ConversationSummaryBufferMemory


llm = ChatOpenAI(temperature=0.1)

memory = ConversationSummaryBufferMemory(
    llm=llm,
    max_token_limit=80,
    memory_key="chat_history",
    return_messages=True,
)

def load_memory(input):
    print(input)
    return memory.load_memory_variables({})["chat_history"]
    
prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful AI talking to human"),
    MessagesPlaceholder(variable_name="chat_history"),
    ("human", "{question}"),
])
chain = RunnablePassthrough.assign(chat_history=load_memory) | prompt | llm
def invoke_chain(question):
    result = chain.invoke({"question": question})
    memory.save_context(
        {"input": question},
        {"output": result.content},
    )
    print(result)

invoke_chain("My name is nam.")

 

 

FewShot

from langchain.prompts.few_shot import (
    FewShotChatMessagePromptTemplate,
    FewShotPromptTemplate,
    )

 

방법 1

 

llm에게 내가 하고자 할 때 가장 많이 사용하는 방식은 보통 내가 원하고자 하는 질문에 대한 답을 제공해서, 비슷한 질문을 하였을 때 답을 맞히는 것입니다.

그래서 이상한 답변을 하지 않고, 내가 원하는 답을 나오게 조작할 수 있게 됩니다.

 

아래와 같이 llm에게 숫자에 대한 답을 맞히게 하는 것을 하고자 할 때 이런 식으로 사용할 수 있다.

examples = [
    {"input": "2+2", "output": "4"},
    {"input": "2+3", "output": "5"},
]

example_prompt = ChatPromptTemplate.from_messages(
    [
        ("human", "{input}"),
        ("ai", "{output}"),
    ]
)
few_shot_prompt = FewShotChatMessagePromptTemplate(
    example_prompt=example_prompt,
    examples=examples,
)

print(few_shot_prompt.format())

 

Human: 2+2
AI: 4
Human: 2+3
AI: 5

 

저러한 few shot에 system과 사용자 질의를 추가하면 이런 형태로 만들 수 있게 된다.

final_prompt = ChatPromptTemplate.from_messages(
    [
        ("system", "You are a wondrous wizard of math."),
        few_shot_prompt,
        ("human", "{input}"),
    ]
)

print(final_prompt.format(input="10+5"))

 

 

System: You are a wondrous wizard of math.
Human: 2+2
AI: 4
Human: 2+3
AI: 5
Human: 10+5

 

방법 2

채팅 형식에 맞춰서 할 수도 있지만 방법 2처럼도 할 수 있다.

examples = [
    {
        "question": "Who was the maternal grandfather of George Washington?",
        "answer": """
Are follow up questions needed here: Yes.
Follow up: Who was the mother of George Washington?
Intermediate answer: The mother of George Washington was Mary Ball Washington.
Follow up: Who was the father of Mary Ball Washington?
Intermediate answer: The father of Mary Ball Washington was Joseph Ball.
So the final answer is: Joseph Ball
""",
    },
    {
        "question": "Are both the directors of Jaws and Casino Royale from the same country?",
        "answer": """
Are follow up questions needed here: Yes.
Follow up: Who is the director of Jaws?
Intermediate Answer: The director of Jaws is Steven Spielberg.
Follow up: Where is Steven Spielberg from?
Intermediate Answer: The United States.
Follow up: Who is the director of Casino Royale?
Intermediate Answer: The director of Casino Royale is Martin Campbell.
Follow up: Where is Martin Campbell from?
Intermediate Answer: New Zealand.
So the final answer is: No
""",
    },
]

example_prompt = PromptTemplate(
    input_variables=["question", "answer"], template="Question: {question}\n{answer}"
)

print(example_prompt.format(**examples[0]))

prompt = FewShotPromptTemplate(
    examples=examples,
    example_prompt=example_prompt,
    suffix="Question: {input}",
    input_variables=["input"],
)

print(prompt.format(input="Who was the father of Mary Ball Washington?"))

 

이런 식으로 사용할 수도 있다. 

Question: Who was the maternal grandfather of George Washington?

Are follow up questions needed here: Yes.
Follow up: Who was the mother of George Washington?
Intermediate answer: The mother of George Washington was Mary Ball Washington.
Follow up: Who was the father of Mary Ball Washington?
Intermediate answer: The father of Mary Ball Washington was Joseph Ball.
So the final answer is: Joseph Ball

Question: Who was the maternal grandfather of George Washington?

Are follow up questions needed here: Yes.
Follow up: Who was the mother of George Washington?
Intermediate answer: The mother of George Washington was Mary Ball Washington.
Follow up: Who was the father of Mary Ball Washington?
Intermediate answer: The father of Mary Ball Washington was Joseph Ball.
So the final answer is: Joseph Ball


Question: Are both the directors of Jaws and Casino Royale from the same country?

Are follow up questions needed here: Yes.
Follow up: Who is the director of Jaws?
Intermediate Answer: The director of Jaws is Steven Spielberg.
Follow up: Where is Steven Spielberg from?
Intermediate Answer: The United States.
Follow up: Who is the director of Casino Royale?
Intermediate Answer: The director of Casino Royale is Martin Campbell.
Follow up: Where is Martin Campbell from?
Intermediate Answer: New Zealand.
So the final answer is: No


Question: Who was the father of Mary Ball Washington?

 

 

방법 3 - dynamic few-shot promting

from langchain.prompts import SemanticSimilarityExampleSelector
from langchain_community.vectorstores import Chroma
from langchain.embeddings import OpenAIEmbeddings

 

아래 같은 경우 여러 개의 예시 중에서 embedding을 사용해서 사용자 질의에 대한 적합한 데이터를 찾고, 그것을 기반으로 원하는 example만 쓰는 예시이다.

examples = [
    {"input": "2+2", "output": "4"},
    {"input": "2+3", "output": "5"},
    {"input": "2+4", "output": "6"},
    {"input": "What did the cow say to the moon?", "output": "nothing at all"},
    {
        "input": "Write me a poem about the moon",
        "output": "One for the moon, and one for me, who are we to talk about the moon?",
    },
]

to_vectorize = [" ".join(example.values()) for example in examples]
embeddings = OpenAIEmbeddings()
vectorstore = Chroma.from_texts(to_vectorize, embeddings, metadatas=examples)

example_selector = SemanticSimilarityExampleSelector(
    vectorstore=vectorstore,
    k=2,
)

# The prompt template will load examples by passing the input do the `select_examples` method
example_selector.select_examples({"input": "horse"})

from langchain.prompts import (
    ChatPromptTemplate,
    FewShotChatMessagePromptTemplate,
)

# Define the few-shot prompt.
few_shot_prompt = FewShotChatMessagePromptTemplate(
    # The input variables select the values to pass to the example_selector
    input_variables=["input"],
    example_selector=example_selector,
    # Define how each example will be formatted.
    # In this case, each example will become 2 messages:
    # 1 human, and 1 AI
    example_prompt=ChatPromptTemplate.from_messages(
        [("human", "{input}"), ("ai", "{output}")]
    ),
)
print(few_shot_prompt.format(input="What's 3+3?"))

실제로 숫자에 대한 질문을 했을 때 가장 유사한 예시 2개만 뽑아서 한 결과는 다음과 같다.

Human: 2+3
AI: 5
Human: 2+3
AI: 5

 

final_prompt = ChatPromptTemplate.from_messages(
    [
        ("system", "You are a wondrous wizard of math."),
        few_shot_prompt,
        ("human", "{input}"),
    ]
)
print(final_prompt.format(input="What's 3+3?"))
System: You are a wondrous wizard of math.
Human: 2+2
AI: 4
Human: 2+3
AI: 5
Human: What's 3+3?

 

Pipeline

from langchain.prompts.pipeline import PipelinePromptTemplate


이 노트북은 여러 프롬프트를 함께 구성하는 방법을 다룹니다. 

프롬프트 일부를 재사용하고 싶을 때 유용할 수 있습니다. 

이것은 PipelinePrompt로 수행할 수 있습니다. 

PipelinePrompt는 두 가지 주요 부분으로 구성됩니다:

  • 최종 프롬프트: 반환되는 최종 프롬프트입니다.
  • 파이프라인 프롬프트: 문자열 이름과 프롬프트 템플릿으로 구성된 튜플 목록입니다. 각 프롬프트 템플릿은 형식화되고 나중에 동일한 이름을 가진 변수로 미래의 프롬프트 템플릿에 전달됩니다.

 

아래는 맨 처음에 이야기한 것처럼 instruction과 context와 질의를 넣는 형태의 전체 구조를 짜고 넣는 방식에 대한 간략한 예시이다.

 

아래는 각각에 대해서 template을 구분하고 pipeline을 통해 합쳐주는 방식이다.

full_template = """{introduction}

{example}

{start}"""
full_prompt = PromptTemplate.from_template(full_template)

introduction_template = """You are impersonating {person}."""
introduction_prompt = PromptTemplate.from_template(introduction_template)

example_template = """Here's an example of an interaction:

Q: {example_q}
A: {example_a}"""
example_prompt = PromptTemplate.from_template(example_template)

start_template = """Now, do this for real!

Q: {input}
A:"""
start_prompt = PromptTemplate.from_template(start_template)

input_prompts = [
    ("introduction", introduction_prompt),
    ("example", example_prompt),
    ("start", start_prompt),
]
pipeline_prompt = PipelinePromptTemplate(
    final_prompt=full_prompt, pipeline_prompts=input_prompts
)

pipeline_prompt.input_variables

 

 

아래는 마지막 prompt를 채우기 위해 필요한 인풋들에 대한 정보를 제공한다.

['person', 'input', 'example_q', 'example_a']

 

 

print(
    pipeline_prompt.format(
        person="Elon Musk",
        example_q="What's your favorite car?",
        example_a="Tesla",
        input="What's your favorite social media site?",
    )
)

 

You are impersonating Elon Musk.

Here's an example of an interaction:

Q: What's your favorite car?
A: Tesla

Now, do this for real!

Q: What's your favorite social media site?
A:

 

마무리

간략하게 prompt와 prompt engineering이 중요한 이유에 대해서 알아보고 langchain을 통해서 prompt를 만드는 방법에 대해서 알아봤다.

제일 기본적인 내용에 대해서 알아본 것 같고, 여기에 더 복잡하게 하는 방법들이 있지만 나중에 추후에 좀 더 정리해보려고 한다.

꼭 이 라이브러리를 써야 하는 것은 아니겠지만, llm을 다루는데 있어서 더 쉽게 사용할 수 있을 것 같아서 langchain을 사용해봤다.

 

 

참고

https://velog.io/@ryeon0219/langChain

 

https://tonylixu.medium.com/langchain-prompt-template-0359d96090c5

 

https://www.datacamp.com/blog/what-is-prompt-engineering-the-future-of-ai-communication?utm_source=google&utm_medium=paid_search&utm_campaignid=19589720821&utm_adgroupid=152984010854&utm_device=c&utm_keyword=&utm_matchtype=&utm_network=g&utm_adpostion=&utm_creative=684753664555&utm_targetid=dsa-2222697810678&utm_loc_interest_ms=&utm_loc_physical_ms=1009846&utm_content=DSA~blog~Artificial-Intelligence&utm_campaign=230119_1-sea~dsa~tofu_2-b2c_3-row-p1_4-prc_5-na_6-na_7-le_8-pdsh-go_9-na_10-na_11-na-jan24&gad_source=1&gclid=Cj0KCQiAtaOtBhCwARIsAN_x-3IjAL1YIqGuxJnzcbh6-mHBfTNLRbDI1pYcaxA1fR7OxIrpENGa04EaAuYREALw_wcB

 

https://moon-walker.medium.com/the-art-of-prompt-engneering-1-prompt-engineering%EC%9D%B4%EB%9E%80-%EB%AC%B4%EC%97%87%EC%9D%B8%EA%B0%80-4a7a88ce67c

 

 

 

728x90