반응형
블로그 이미지
개발자로서 현장에서 일하면서 새로 접하는 기술들이나 알게된 정보 등을 정리하기 위한 블로그입니다. 운 좋게 미국에서 큰 회사들의 프로젝트에서 컬설턴트로 일하고 있어서 새로운 기술들을 접할 기회가 많이 있습니다. 미국의 IT 프로젝트에서 사용되는 툴들에 대해 많은 분들과 정보를 공유하고 싶습니다.
솔웅

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함

카테고리


반응형

https://python.langchain.com/docs/expression_language/cookbook/multiple_chains

 

Multiple chains | 🦜️🔗 Langchain

Runnables can easily be used to string together multiple Chains

python.langchain.com

 

Multiple chains

 

Runnables can easily be used to string together multiple Chains

 

Runnable은 여러 체인을 함께 묶는 데 쉽게 사용할 수 있습니다.

 

from operator import itemgetter

from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
from langchain.schema import StrOutputParser

prompt1 = ChatPromptTemplate.from_template("what is the city {person} is from?")
prompt2 = ChatPromptTemplate.from_template(
    "what country is the city {city} in? respond in {language}"
)

model = ChatOpenAI()

chain1 = prompt1 | model | StrOutputParser()

chain2 = (
    {"city": chain1, "language": itemgetter("language")}
    | prompt2
    | model
    | StrOutputParser()
)

chain2.invoke({"person": "obama", "language": "spanish"})

 

    'El país donde se encuentra la ciudad de Honolulu, donde nació Barack Obama, el 44º Presidente de los Estados Unidos, es Estados Unidos. Honolulu se encuentra en la isla de Oahu, en el estado de Hawái.'

 

이 코드는 LangChain에서 두 개의 프롬프트를 사용하여 정보를 검색하고, 이를 조합하여 원하는 질문에 대한 답변을 생성하는 방법을 보여줍니다.

  1. prompt1 및 chain1:
    • "what is the city {person} is from?"이라는 템플릿을 사용하여 prompt1을 생성합니다.
    • chain1은 prompt1을 사용하여 입력 데이터를 처리하고 모델을 사용하여 결과를 생성합니다.
  2. prompt2 및 chain2:
    • "what country is the city {city} in? respond in {language}"이라는 템플릿을 사용하여 prompt2를 생성합니다.
    • chain2는 prompt2와 chain1에서 생성된 chain1의 결과 (city)를 조합합니다.
    • chain2의 입력에는 "person"과 "language"가 있으며, "person"에 "obama" 및 "language"에 "Spanish" 값을 설정합니다.
    • 이렇게 조합된 입력을 사용하여 chain2는 모델을 통해 결과를 생성합니다.
  3. 결과:
    • chain2를 통해 생성된 결과에는 원하는 질문에 대한 답변이 포함되어 있습니다. "obama"라는 사람이 어떤 도시에서 왔는지에 대한 답변이 Spanish로 생성되었습니다.

이 코드는 여러 개의 프롬프트 및 연결된 체인을 사용하여 여러 단계를 거쳐 복잡한 질문에 대한 답변을 생성하는 방법을 보여줍니다.

 

 

language korean으로 했는데 제대로 잘 대답을 하네요.

 

from langchain.schema.runnable import RunnableMap, RunnablePassthrough

prompt1 = ChatPromptTemplate.from_template(
    "generate a {attribute} color. Return the name of the color and nothing else:"
)
prompt2 = ChatPromptTemplate.from_template(
    "what is a fruit of color: {color}. Return the name of the fruit and nothing else:"
)
prompt3 = ChatPromptTemplate.from_template(
    "what is a country with a flag that has the color: {color}. Return the name of the country and nothing else:"
)
prompt4 = ChatPromptTemplate.from_template(
    "What is the color of {fruit} and the flag of {country}?"
)

model_parser = model | StrOutputParser()

color_generator = (
    {"attribute": RunnablePassthrough()} | prompt1 | {"color": model_parser}
)
color_to_fruit = prompt2 | model_parser
color_to_country = prompt3 | model_parser
question_generator = (
    color_generator | {"fruit": color_to_fruit, "country": color_to_country} | prompt4
)

 

이 코드는 LangChain을 사용하여 색상, 과일, 나라 및 질문을 생성하는 방법을 보여줍니다.

  1. prompt1, prompt2, prompt3 및 prompt4:
    • 각각의 ChatPromptTemplate은 다양한 유형의 정보를 생성하기 위한 프롬프트를 정의합니다.
    • prompt1은 주어진 attribute에 해당하는 색상을 생성하도록 요청하며, 그 결과에서 색상의 이름을 반환합니다.
    • prompt2는 주어진 color에 해당하는 과일을 찾아서 과일의 이름을 반환합니다.
    • prompt3는 주어진 color와 일치하는 국기 색상을 가진 국가를 찾아 국가의 이름을 반환합니다.
    • prompt4는 주어진 과일 및 국가에 해당하는 색상 및 국기를 찾아 반환합니다.
  2. color_generator, color_to_fruit, color_to_country 및 question_generator:
    • color_generator은 "attribute" 값을 사용하여 prompt1을 호출하여 색상을 생성하고 결과를 "color"로 저장합니다.
    • color_to_fruit은 "color" 값을 사용하여 prompt2를 호출하여 해당 색상과 일치하는 과일을 찾아 반환합니다.
    • color_to_country은 "color" 값을 사용하여 prompt3를 호출하여 해당 색상과 일치하는 국가를 찾아 반환합니다.
    • question_generator는 color_generator, color_to_fruit, color_to_country의 결과를 사용하여 prompt4를 호출하여 원하는 질문을 생성합니다.

이 코드를 통해 서로 다른 프롬프트 및 정보를 조합하여 복잡한 정보를 생성하고, 그 결과를 단일 체인에서 관리할 수 있습니다.

 

question_generator.invoke("warm")

 

    ChatPromptValue(messages=[HumanMessage(content='What is the color of strawberry and the flag of China?', additional_kwargs={}, example=False)])

 

prompt = question_generator.invoke("warm")
model.invoke(prompt)

 

    AIMessage(content='The color of an apple is typically red or green. The flag of China is predominantly red with a large yellow star in the upper left corner and four smaller yellow stars surrounding it.', additional_kwargs={}, example=False)

 

이 코드는 question_generator를 사용하여 특정 정보에 대한 질문을 생성하고, 그 결과를 두 번 호출하는 예시입니다.

  1. question_generator.invoke("warm"):
    • question_generator를 사용하여 "warm"이라는 attribute를 사용한 색상에 대한 질문을 생성합니다.
    • 이 질문의 결과는 "prompt" 변수에 저장되지만 출력은 주어지지 않습니다.
  2. model.invoke(prompt):
    • model을 사용하여 "prompt"에 저장된 질문을 호출합니다.
    • 이 모델은 질문을 받고 적절한 응답을 반환합니다. 이 경우, "warm"에 해당하는 색상의 이름을 반환할 것입니다.

따라서 먼저 question_generator로 질문을 생성하고, 그 다음 model을 사용하여 해당 질문에 답을 얻게 됩니다.

 

 

로컬 jupyterlab에서 실행한 결과는 아래와 같습니다.

 

 

한국의 태극기를 대답으로 이끌어 내려고 white, black, red, blue를 입력값으로 집어 넣었는데 잘 안되네요. 

체코의 국기에는 하얀색, 파란색, 빨간색이 있고 검은색이 없는데 이게 답으로 나오기도 하네요.

 

분명히 해당 질문에는 태극기가 더 정답데 가까운데 ... ChatGPT가 아직 태극기는 잘 모르나 봅니다.

 

Branching and Merging

You may want the output of one component to be processed by 2 or more other components. RunnableMaps let you split or fork the chain so multiple components can process the input in parallel. Later, other components can join or merge the results to synthesize a final response. This type of chain creates a computation graph that looks like the following:

 

한 구성요소의 출력을 2개 이상의 다른 구성요소에서 처리하도록 할 수 있습니다. RunnableMaps를 사용하면 여러 구성 요소가 입력을 병렬로 처리할 수 있도록 체인을 분할하거나 분기할 수 있습니다. 나중에 다른 구성요소가 결과를 결합하거나 병합하여 최종 응답을 종합할 수 있습니다. 이 유형의 체인은 다음과 같은 계산 그래프를 생성합니다.

 

 

planner = (
    ChatPromptTemplate.from_template("Generate an argument about: {input}")
    | ChatOpenAI()
    | StrOutputParser()
    | {"base_response": RunnablePassthrough()}
)

arguments_for = (
    ChatPromptTemplate.from_template(
        "List the pros or positive aspects of {base_response}"
    )
    | ChatOpenAI()
    | StrOutputParser()
)
arguments_against = (
    ChatPromptTemplate.from_template(
        "List the cons or negative aspects of {base_response}"
    )
    | ChatOpenAI()
    | StrOutputParser()
)

final_responder = (
    ChatPromptTemplate.from_messages(
        [
            ("ai", "{original_response}"),
            ("human", "Pros:\n{results_1}\n\nCons:\n{results_2}"),
            ("system", "Generate a final response given the critique"),
        ]
    )
    | ChatOpenAI()
    | StrOutputParser()
)

chain = (
    planner
    | {
        "results_1": arguments_for,
        "results_2": arguments_against,
        "original_response": itemgetter("base_response"),
    }
    | final_responder
)

 

 

이 코드는 "planner"에서 argument를 생성하고, 해당 argument에 대한 "pros" 및 "cons"를 나열한 후, 최종 응답을 생성하는 프로세스를 구성하는 Langchain 체인을 나타냅니다.

  1. "planner":
    • "Generate an argument about: {input}"와 같은 템플릿을 사용하여 주어진 입력 "{input}"을 기반으로 인수(argument)를 생성합니다.
    • 그러면 이 결과는 "base_response" 변수에 저장됩니다.
  2. "arguments_for":
    • "{base_response}"에 대한 긍정적인 측면(positive aspects)을 나열하기 위한 질문을 생성하고 호출합니다.
  3. "arguments_against":
    • "{base_response}"에 대한 부정적인 측면(negative aspects)을 나열하기 위한 질문을 생성하고 호출합니다.
  4. "final_responder":
    • 여러 메시지로 구성된 템플릿을 사용하여 최종 응답을 생성합니다.
    • "original_response"는 "base_response"에서 가져옵니다.
    • 최종 응답에는 "original_response" 및 "arguments_for" 및 "arguments_against"에서 가져온 결과를 표시하는 부분이 포함됩니다.
  5. "chain":
    • "planner"에서 생성된 "base_response"를 기반으로 "arguments_for" 및 "arguments_against"에 대한 결과를 생성하고, 최종 응답을 생성하는 체인을 구성합니다.

이렇게 구성된 체인을 사용하면 주어진 주제에 대한 인수와 해당 인수에 대한 "pros" 및 "cons"를 생성하고, 이를 결합하여 최종적인 응답을 얻을 수 있습니다.

 

chain.invoke({"input": "scrum"})

 

    'While Scrum has its potential cons and challenges, many organizations have successfully embraced and implemented this project management framework to great effect. The cons mentioned above can be mitigated or overcome with proper training, support, and a commitment to continuous improvement. It is also important to note that not all cons may be applicable to every organization or project.\n\nFor example, while Scrum may be complex initially, with proper training and guidance, teams can quickly grasp the concepts and practices. The lack of predictability can be mitigated by implementing techniques such as velocity tracking and release planning. The limited documentation can be addressed by maintaining a balance between lightweight documentation and clear communication among team members. The dependency on team collaboration can be improved through effective communication channels and regular team-building activities.\n\nScrum can be scaled and adapted to larger projects by using frameworks like Scrum of Scrums or LeSS (Large Scale Scrum). Concerns about speed versus quality can be addressed by incorporating quality assurance practices, such as continuous integration and automated testing, into the Scrum process. Scope creep can be managed by having a well-defined and prioritized product backlog, and a strong product owner can be developed through training and mentorship.\n\nResistance to change can be overcome by providing proper education and communication to stakeholders and involving them in the decision-making process. Ultimately, the cons of Scrum can be seen as opportunities for growth and improvement, and with the right mindset and support, they can be effectively managed.\n\nIn conclusion, while Scrum may have its challenges and potential cons, the benefits and advantages it offers in terms of collaboration, flexibility, adaptability, transparency, and customer satisfaction make it a widely adopted and successful project management framework. With proper implementation and continuous improvement, organizations can leverage Scrum to drive innovation, efficiency, and project success.'

 

프로젝트 프로세스 관리인 scrum과 관련된 단점과 이를 극복하는 방법 그리고 장점 등이 잘 설명돼 있습니다.

 

로컬 jupyterlab에서 실행한 결과는 아래와 같습니다.

 

저는 질문을 AI로 했습니다.

 

 

 

답변을 번역하면 아래와 같습니다.

 

'AI를 둘러싼 타당한 우려와 비판이 있지만, 균형 잡힌 관점으로 접근하는 것이 중요합니다. 일자리 대체는 타당한 우려 사항이지만 역사를 통틀어 기술 발전으로 인해 새로운 일자리 기회가 창출되었습니다. 변화하는 직업 시장에 적응하기 위해 인력을 재교육하고 기술을 향상시키는 데 집중하는 것이 중요합니다.\n\nAI 시스템에서 인간적 접촉과 감성 지능이 부족하다는 점은 특히 개인적인 연결이 필요한 산업에서 타당한 점입니다. 그러나 AI는 인간의 능력을 보완하고 효율성을 향상시켜 인간이 창의성과 공감이 필요한 작업에 집중할 수 있도록 해줍니다.\n\n윤리적 고려 사항, 편견, 개인 정보 보호 위험은 적절한 규제와 감독을 통해 해결해야 하는 정당한 문제입니다. AI 개발의 투명성과 책임성은 이러한 문제를 완화하고 공정하고 편견 없는 의사 결정을 보장하는 데 도움이 될 수 있습니다.\n\n시스템 오류 및 보안 위험이 발생할 가능성이 있지만 AI 시스템의 견고성과 신뢰성을 보장하기 위해 적절한 조치를 취할 수 있습니다. 여기에는 사이버 보안에 대한 투자와 악의적인 공격으로부터 보호하기 위한 보호 조치 구현이 포함됩니다.\n\n특정 AI 알고리즘의 예측 불가능성과 투명성 부족은 설명 가능한 AI에 초점을 맞춘 연구 및 개발 노력을 통해 해결할 수 있습니다. 이를 통해 사용자는 AI 시스템의 의사 결정 프로세스를 이해하고 책임을 질 수 있습니다.\n\nAI 기술과 기회에 대한 공평한 접근을 보장하는 정책을 통해 사회적 영향과 불평등 악화 가능성을 적극적으로 해결해야 합니다. 여기에는 디지털 인프라에 투자하고 서비스가 부족한 커뮤니티에 교육 및 훈련을 제공하는 것이 포함됩니다.\n\n전반적으로 AI를 둘러싼 우려를 인식하고 잠재적인 위험을 완화하기 위해 노력하는 것이 중요합니다. 책임감 있는 개발, 규제 및 감독을 통해 AI는 사회에 미치는 부정적인 영향을 최소화하면서 상당한 이점과 발전을 가져올 수 있는 잠재력을 가지고 있습니다.'

 

 

 

 

 

 

 

 

 

 

반응형