mirror of
https://github.com/langchain-ai/langchain.git
synced 2026-10-08 19:05:20 +03:00
9.0 KiB
9.0 KiB
In [1]:
from langchain import PromptTemplate, OpenAI, LLMChain
prompt_template = "What is a good name for a company that makes {product}?"
llm = OpenAI(temperature=0)
llm_chain = LLMChain(
llm=llm,
prompt=PromptTemplate.from_template(prompt_template)
)
llm_chain("colorful socks")Out [1]:
{'product': 'colorful socks', 'text': '\n\nSocktastic!'}In [2]:
input_list = [
{"product": "socks"},
{"product": "computer"},
{"product": "shoes"}
]
llm_chain.apply(input_list)Out [2]:
[{'text': '\n\nSocktastic!'},
{'text': '\n\nTechCore Solutions.'},
{'text': '\n\nFootwear Factory.'}]In [3]:
llm_chain.generate(input_list)Out [3]:
LLMResult(generations=[[Generation(text='\n\nSocktastic!', generation_info={'finish_reason': 'stop', 'logprobs': None})], [Generation(text='\n\nTechCore Solutions.', generation_info={'finish_reason': 'stop', 'logprobs': None})], [Generation(text='\n\nFootwear Factory.', generation_info={'finish_reason': 'stop', 'logprobs': None})]], llm_output={'token_usage': {'prompt_tokens': 36, 'total_tokens': 55, 'completion_tokens': 19}, 'model_name': 'text-davinci-003'})In [12]:
# Single input example
llm_chain.predict(product="colorful socks")Out [12]:
'\n\nSocktastic!'
In [14]:
# Multiple inputs example
template = """Tell me a {adjective} joke about {subject}."""
prompt = PromptTemplate(template=template, input_variables=["adjective", "subject"])
llm_chain = LLMChain(prompt=prompt, llm=OpenAI(temperature=0))
llm_chain.predict(adjective="sad", subject="ducks")Out [14]:
'\n\nQ: What did the duck say when his friend died?\nA: Quack, quack, goodbye.'
In [24]:
from langchain.output_parsers import CommaSeparatedListOutputParser
output_parser = CommaSeparatedListOutputParser()
template = """List all the colors in a rainbow"""
prompt = PromptTemplate(template=template, input_variables=[], output_parser=output_parser)
llm_chain = LLMChain(prompt=prompt, llm=llm)
llm_chain.predict()Out [24]:
'\n\nRed, orange, yellow, green, blue, indigo, violet'
In [25]:
llm_chain.predict_and_parse()Out [25]:
['Red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']
In [16]:
template = """Tell me a {adjective} joke about {subject}."""
llm_chain = LLMChain.from_string(llm=llm, template=template)In [18]:
llm_chain.predict(adjective="sad", subject="ducks")Out [18]:
'\n\nQ: What did the duck say when his friend died?\nA: Quack, quack, goodbye.'