[7기 랭체인] 랭체인으로 여러 프롬프트 묶어서 써보기

안녕하세요 파트너 곽은철입니다.

처음 목표로 여러 프롬프트를 설정하고 직렬로 연결된 프롬프트를 통해 입력 한번에 여러 작업을 거친 후 하나의 결과물로 만드는 작업을 실습해 봤습니다.

개인 일정이 너무 바빳던 탓에 코드가 다소 난잡한 점 죄송합니다 ㅠㅠ..

먼저 DLAI - Learning Platform Beta (deeplearning.ai)의 강의를 참고했습니다.

제가 참고한 부분은 처음 랭체인을 사용하는 사람들을 초점으로 맞춰 직렬로 연결된 여러 프롬프트를 하나의 결과물로 만드는 과정이었는데요. 영상에서는 csv로 저장된 상품명을 가져와서 하나씩 새로운 이름을 만들고 설명하게 했습니다.

저는 똑같이 따라하면 공부가 안되다보니 C언어 함수를 입력하면 함수의 설명, 함수가 내부적으로 동작할때 CS에 어떤 방식으로 동작하는지에 대한 설명, 종합적인 설명을 이해하기위한 예제코드, 지금까지 작성된 설명, 동작원리,예제코드를 한글로 번역, 마크다운으로 정리 하는 순서로 랭체인을 사용해봤습니다.

함수설명 → 동작원리 → 예제코드 → 한글로 번역 → 마크다운 편집

코드를 작성하면서 랭체인이 정말 탁월하게 설계되었다는 느낌을 많이 받았습니다. 원할때 원하는 언어 모델만 바꾸거나 프롬프트만 바꾸는 형식으로 사용할수있었고 input,output을 자유 자제로 여러 프롬프트에 추가할수 있었습니다. 이 과정을 하나하나 직접 컨트롤 했다면 엄청나게 힘든 작업이 었을겁니다. 특히나 저는 openai의 gpt-3.5, 3.5-16k 두가지 모델만 사용했는데 사용법이 다른 여러 모델을 같이 사용한다면 더 큰 효용을 가질수있다고 확신하는 시간이었습니다.


import os

from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv())

import warnings
warnings.filterwarnings("ignore")

llm_model = "gpt-3.5-turbo"

from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
from langchain.chains import LLMChain

from langchain.chains import SequentialChain

llm = ChatOpenAI(temperature=0.9, model=llm_model)

first_prompt = ChatPromptTemplate.from_template(
    """
    ```function
    {function}
    ```
    The function you entered is a C language function. Please describe the function.
    """
)

chain_one = LLMChain(llm=llm, prompt=first_prompt, output_key="description")

second_prompt = ChatPromptTemplate.from_template(
    """
    ```function
    {function}
    ```
    The function you entered is a C language function. Omit the description of the function and explain how it is used in computer science. For example, if it is printf, explain how it works internally when multiple printf functions are written to the standard output.
    """
)

chain_two = LLMChain(llm=llm, prompt=second_prompt, output_key="usage")

third_prompt = ChatPromptTemplate.from_template(
    """
    ```function
    {function}
    ```
    ```description
    {description}
    ```
    ```usage
    {usage}
    ```
    Please write an example code based on function,description,usage.
    """
)

chain_three = LLMChain(llm=llm, prompt=third_prompt, output_key="example")

fourth_prompt = ChatPromptTemplate.from_template(
    """
    ```function
    {function}
    ```
    ```description
    {description}
    ```
    ```usage
    {usage}
    ```
    ```example
    {example}
    ```
    Please translate to Korean. Please do not translate jargon.
    """
)

llm_model_16k = "gpt-3.5-turbo-16k-0613"
llm_16k = ChatOpenAI(temperature=0.5, model=llm_model_16k)

chain_four = LLMChain(llm=llm_16k, prompt=fourth_prompt, output_key="translate")

five_prompt = ChatPromptTemplate.from_template(
    """
    {translate}
    Organize it in markdown.
    """
)

chain_five = LLMChain(llm=llm, prompt=five_prompt, output_key="markdown")

overall_chain = SequentialChain(
    chains=[chain_one, chain_two, chain_three, chain_four, chain_five],
    input_variables=["function"],
    output_variables=["description", "usage", "example", "translate", "markdown"],
    verbose=True
)

function = "open"
data = {'function': function}
result = overall_chain(data)
print(result['markdown'])

def save_to_file(text, filename):
    with open(filename, 'w') as file:
        file.write(text)

save_to_file(result['markdown'], 'example_output.md')
6
1개의 답글

(채용) 콘텐츠 마케터, AI 엔지니어, 백엔드 개발자

지피터스의 수 천개 AI 활용 사례 데이터를 AI로 재가공 할 인재를 찾습니다

👉 이 게시글도 읽어보세요