LLM 链的其他运行方式
以上篇文章创建的Chain为例,Chain还有其他的运行方式。
先创建链:
from langchain import PromptTemplate, LLMChain
from bigdl.llm.langchain.llms import TransformersLLM
llm = TransformersLLM.from_model_id(
model_id="lmsys/vicuna-7b-v1.5",
model_kwargs={"temperature": 0, "max_length": 1024, "trust_remote_code": True},
)
prompt_template = "What is a good name for a company that makes {product}?"
llm_chain = LLMChain(
llm=llm,
prompt=PromptTemplate.from_template(prompt_template)
)
除了所有Chain 对象共享的 __call__和 run
方法之外,LLMChain
还提供了几种调用链逻辑的方式:
- aplly:允许进行一组输入
input_list = [
{"product": "socks"},
{"product": "computer"},
{"product": "shoes"}
]
llm_chain.apply(input_list)
generate
与apply
类似,但是它返回一个LLMResult
而不是字符串。LLMResult
通常包含有用的生成信息,如令牌使用情况和完成原因。
llm_chain.generate(input_list)
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'})
predict
与run
方法类似,区别在于输入键是指定为关键字参数而不是 Python 字典。
Single input example
llm_chain.predict(product="colorful socks")
'\n\nSocktastic!'
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")
'\n\nQ: What did the duck say when his friend died?\nA: Quack, quack, goodbye.'
使用 predict_and_parser
:
llm_chain.predict_and_parse()
['Red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']