LangChain: Ein Framework zur Nutzung des LLM-Potenzials | von Kushal Vala | Juni 2023

0
27


Verschiedene Arten von Ketten

Bei komplexeren Anwendungen reicht es möglicherweise nicht aus, sich ausschließlich auf ein einzelnes LLM zu verlassen. Stattdessen ist es erforderlich, mehrere LLMs miteinander oder mit zusätzlichen Komponenten zu verketten.

Durch die Verkettung von LLMs können verschiedene Komponenten zu einer zusammenhängenden und umfassenden Anwendung kombiniert werden. Beispielsweise kann eine Kette erstellt werden, um Benutzereingaben zu empfangen, das Format mithilfe einer PromptTemplate anzuwenden und dann die formatierte Antwort an einen LLM weiterzuleiten, um die gewünschte Ausgabe zu generieren. Das Verkettung Ansatz ermöglicht die Entwicklung anspruchsvoller Anwendungen, die komplexe Aufgaben bewältigen können.

Wir werden die folgenden Ketten durchlaufen, die uns eine gute Grundlage für die Arbeit an der Lösung komplexer Anwendungsfälle bieten.

  1. LLMChain
  2. SequentialChain

Der LLMChain dient als grundlegender Baustein im LangChain-Framework und bietet erweiterte Funktionalität rund um Sprachmodelle. Es wird in LangChain umfassend genutzt, auch in anderen Ketten und Agenten.

Eine LLMChain besteht aus zwei Schlüsselkomponenten: a PromptTemplate und ein Sprachmodell, das entweder ein sein kann LLM (Großes Sprachmodell) oder a Chat-Modell (wie das, das wir im obigen Abschnitt verwendet haben: ChatOpenAI).
Die Kette formatiert die Eingabeaufforderungsvorlage mithilfe der bereitgestellten Eingabeschlüsselwerte sowie aller verfügbaren Speicherschlüsselwerte. Die resultierende formatierte Zeichenfolge wird dann an den LLM übergeben, der die Ausgabe basierend auf der bereitgestellten Eingabeaufforderung generiert.

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

llm = ChatOpenAI(temperature=0.9)

immediate = ChatPromptTemplate.from_template(
"What's the greatest identify to explain
an organization that makes {product}?"
)

chain = LLMChain(llm=llm, immediate=immediate)

product = "Ice-cream"
chain.run(product)

# Output : 'Scoops Ice Cream Co.'

input_list = [
{"product": "shoes"},
{"product": "computer"},
{"product": "window"}
]

chain.apply(input_list)

# Output : [{'text': '"Stride Footwear" would be a good name to describe a company that makes shoes.'},
# {'text': 'Techtronics.'},
# {'text': 'WindowWorks.'}]

Im obigen Code können wir sehen, wie eine LLMChain verwendet werden kann, um grundlegende Eingabeaufforderungen durchzuführen und mehrere Eingaben aufzunehmen.

Um einen Schritt weiter zu gehen, werden Ketten in vielen Anwendungen häufig sequentiell verwendet: Der Ausgang der ersten Kette wird fortan zum Eingang der zweiten Kette.

SimpleSequentialChain

Um diese Funktionalität zu implementieren, bietet LangChain Folgendes:

  1. SimpleSequentialChain : Die einfachste Kind sequentieller Ketten, bei der jeder Schritt eine einzelne Eingabe/Ausgabe hat und die Ausgabe eines Schritts die Eingabe für den nächsten ist.
  2. SequentialChain: Eine allgemeinere Kind sequentieller Ketten, die mehrere Ein-/Ausgaben ermöglicht.
SequentialChain

Im folgenden Anwendungsfall führen wir zwei Aufgaben aus, die nacheinander ausgeführt werden müssen: Fassen Sie die Produktbewertung zusammen und verwenden Sie dann die Zusammenfassung, um die Stimmung der Bewertung zu ermitteln. Da es sich um eine SimpleSequentialChain handelt, erhalten wir nur ein Ausgang (Stimmung in diesem Fall)

from langchain.chains import SimpleSequentialChain

llm = ChatOpenAI(temperature=0.0)

# immediate template 1
first_prompt = ChatPromptTemplate.from_template(
"Summarize the product evaluation : {evaluation}"
)

# Chain 1
chain_one = LLMChain(llm=llm, immediate=first_prompt)

# immediate template 2
second_prompt = ChatPromptTemplate.from_template(
"Establish the sentiment of the abstract : {abstract}"
)
# chain 2
chain_two = LLMChain(llm=llm, immediate=second_prompt)

# Initializing a easy sequential chain
overall_simple_chain = SimpleSequentialChain(chains=[chain_one, chain_two],
verbose=True
)

# Single Enter -> Single Output

evaluation = """3 MODES & ROTATABLE NOZZLE DESIGN- This transportable oral irrigator comes with Regular, Mushy and Pulse modes that are greatest for skilled use. The 360° rotatable jet tip design permits simple cleansing serving to forestall tooth decay, dental plaque, dental calculus, gingival bleeding and dental hypersensitivity.
DUAL WATERPROOF DESIGN- The IPX7 waterproof design is adopted each internally and externally to supply twin safety. The clever ANTI-LEAK design prevents leakage and permits the dental flosser for use safely beneath the operating water.
UPGRADED 300 ML LARGE CAPACITY WATER TANK- The brand new water tank is the most important capability tank obtainable and supplies steady flossing for a whole session. The detachable full-opening design permits thorough cleansing thus stopping formation of micro organism and limescale deposits.
CORDLESS & QUALITY ASSURANCE- Cordless and light-weight energy irrigator comes with a strong battery that lasts upto 14 days on a single cost
RECHARGEABLE & QUALITY ASSURANCE- Cordless and light-weight energy irrigator comes with a strong battery that lasts upto 14 days on a single cost
"""

overall_simple_chain.run(evaluation)

# Output : ['Positive sentiment.']

Um die Leistungsfähigkeit von SimpleSequentialChain zu erweitern, werden wir die allgemeine Model davon implementieren – die die Fähigkeit hat, mehrere Eingaben entgegenzunehmen und mehrere Ausgaben zu liefern. Solche Arten von Ketten sind einfach zu verwenden und können Aufgaben unterteilen, die dann leicht zu debuggen und zu ändern sind, ohne alle Teile des Betriebs zu beeinträchtigen.

Zusätzlich zur Identifizierung der Stimmung und der Themen, die Kundenprobleme mit dem Produkt verursacht haben, werden wir auch eine Folgeantwort an den Kunden formulieren.

from langchain.chains import SequentialChain

llm = ChatOpenAI(temperature=0.0)

# immediate template 1: summarize the product evaluation - output (abstract)
first_prompt = ChatPromptTemplate.from_template(
"Summarize the product evaluation:"
"nn{Evaluation}"
)
# chain 1: enter= Evaluation and output= abstract
chain_one = LLMChain(llm=llm, immediate=first_prompt,
output_key="abstract"
)

# immediate template 2: establish the sentiment from the abstract
second_prompt = ChatPromptTemplate.from_template(
"Establish the sentiment of the evaluation"
"nn{abstract}"
)
# chain 2: enter= abstract and output= sentiment
chain_two = LLMChain(llm=llm, immediate=second_prompt,
output_key="sentiment"
)

# immediate template 3: establish the matters which can be inflicting points
third_prompt = ChatPromptTemplate.from_template(
"Establish the matters that are inflicting points for buyer:nn{Evaluation}"
)
# chain 3: enter= Evaluation and output= matters
chain_three = LLMChain(llm=llm, immediate=third_prompt,
output_key="matters"
)

# immediate template 4: observe up message
fourth_prompt = ChatPromptTemplate.from_template(
"""Write a observe up response to the client based mostly on sentiment
and matters:
"nnSentiment: {sentiment}nTopics: {matters}"""
)
# chain 4: enter= sentiment, matters and output= followup_message
chain_four = LLMChain(llm=llm, immediate=fourth_prompt,
output_key="followup_message"
)

# overall_chain: enter= Evaluation
# and output= abstract,sentiment, matters, followup_message
overall_chain = SequentialChain(
chains=[chain_one, chain_two, chain_three, chain_four],
input_variables=["Review"],
output_variables=["summary", "sentiment","topics","followup_message"],
verbose=False
)

evaluation = """
I by no means thought that I'd obtain such a foul iPhone from Amazon once I ordered it on-line. My iPhone is taking extraordinarily blurry images and it heats up shortly, inside 10 minutes of utilizing Instagram or snap. once I known as customer support for a substitute,they refused to trade it instantly. That is the primary time I purchased an iPhone and I had a tough time saving up for it. I believed the digicam can be nice, however it's taking very blurry images and overheating. I purchased it for Rs. 60,499 as a result of there was a much bigger low cost than on Flinkart however now I remorse shopping for it from right here as a result of I feel the vendor offered it to me for a lower cost as a consequence of their very own defective iPhone 13." My solely request is that you simply exchange my iPhone 13 as quickly as attainable
"""
overall_chain(evaluation)

Die Ausgabe der folgenden Kette ist

{
'Evaluation': 'nI by no means thought that I'd obtain such a foul iPhone from Amazon once I ordered it on-line. My iPhone is taking extraordinarily blurry images and it heats up shortly, inside 10 minutes of utilizing Instagram or snap. once I known as customer support for a substitute,they refused to trade it instantly. That is the primary time I purchased an iPhone and I had a tough time saving up for it. I believed the digicam can be nice, however it's taking very blurry images and overheating. I purchased it for Rs. 60,499 as a result of there was a much bigger low cost than on Flinkart however now I remorse shopping for it from right here as a result of I feel the vendor offered it to me for a lower cost as a consequence of their very own defective iPhone 13." My solely request is that you simply exchange my iPhone 13 as quickly as possiblen',
'abstract': 'The reviewer obtained a defective iPhone 13 from Amazon that takes blurry images and overheats shortly. Customer support refused to trade it instantly. The reviewer regrets shopping for it from Amazon and believes the vendor offered it for a lower cost as a consequence of its faults. They request a substitute as quickly as attainable.',
'sentiment': 'Detrimental sentiment.',
'matters': '1. Faulty iPhone cameran2. Overheating iPhonen3. Refusal of customer support to trade the productn4. Disappointment with the product after saving up for itn5. Remorse for purchasing from Amazon as an alternative of Flipkartn6. Suspicion of vendor promoting a defective product at a lower cost.',
'followup_message': "Expensive valued buyer,nnWe are sorry to listen to about your adverse expertise with our product. We perceive how irritating it may be to come across points together with your iPhone digicam and overheating. We apologize for any inconvenience brought on by our customer support crew's refusal to trade the product.nnWe need to guarantee you that we take all buyer complaints significantly and are dedicated to resolving any points you'll have. We encourage you to succeed in out to our customer support crew once more to debate your considerations and discover attainable options.nnWe additionally perceive your disappointment after saving up for the product and remorse for purchasing from Amazon as an alternative of Flipkart. We admire your suggestions and can take it into consideration as we proceed to enhance our services and products.nnRegarding your suspicion of the vendor promoting a defective product at a lower cost, we guarantee you that we've strict high quality management measures in place to make sure that all our merchandise meet our excessive requirements. Nonetheless, we'll examine this matter additional to make sure that our prospects obtain solely the most effective merchandise.nnThank you for bringing these points to our consideration. We hope to have the chance to make issues proper and regain your belief in our model.nnSincerely,nn[Your Company]"}

Ein weiterer bekannter Kettentyp, der in verschiedenen Anwendungen verwendet wird, ist die RouterChain, Wir werden in diesem Artikel nicht näher darauf eingehen, aber die Leser werden ermutigt, die Dokumentation durchzulesen.



Source link

HINTERLASSEN SIE EINE ANTWORT

Please enter your comment!
Please enter your name here