由 deepset 维护
集成:Cerebras
使用 Cerebras API 提供的 LLM
目录
概述
Cerebras 是快速、轻松进行 AI 训练和推理的首选平台。
使用
Cerebras API 与 OpenAI 兼容,可以通过 OpenAI Generators 在 Haystack 中轻松使用。
使用 Generator
以下是一个使用 Cerebras 提供的 llama3.1-8b 在网页上执行问答的示例。您需要设置环境变量 CEREBRAS_API_KEY 并选择一个 兼容的模型。
from haystack import Pipeline
from haystack.utils import Secret
from haystack.components.fetchers import LinkContentFetcher
from haystack.components.converters import HTMLToDocument
from haystack.components.builders import PromptBuilder
from haystack.components.generators import OpenAIGenerator
fetcher = LinkContentFetcher()
converter = HTMLToDocument()
prompt_template = """
According to the contents of this website:
{% for document in documents %}
{{document.content}}
{% endfor %}
Answer the given question: {{query}}
Answer:
"""
prompt_builder = PromptBuilder(template=prompt_template)
llm = OpenAIGenerator(
api_key=Secret.from_env_var("CEREBRAS_API_KEY"),
api_base_url="https://api.cerebras.ai/v1",
model="llama3.1-8b"
)
pipeline = Pipeline()
pipeline.add_component("fetcher", fetcher)
pipeline.add_component("converter", converter)
pipeline.add_component("prompt", prompt_builder)
pipeline.add_component("llm", llm)
pipeline.connect("fetcher.streams", "converter.sources")
pipeline.connect("converter.documents", "prompt.documents")
pipeline.connect("prompt.prompt", "llm.prompt")
result = pipeline.run({"fetcher": {"urls": ["https://cerebras.ai/inference"]},
"prompt": {"query": "Why should I use Cerebras for serving LLMs?"}})
print(result["llm"]["replies"][0])
使用 ChatGenerator
请参阅一个与 llama3.1-8b 进行多轮对话的示例。您需要设置环境变量 CEREBRAS_API_KEY 并选择一个 兼容的模型。
from haystack.components.generators.chat import OpenAIChatGenerator
from haystack.dataclasses import ChatMessage
from haystack.utils import Secret
generator = OpenAIChatGenerator(
api_key=Secret.from_env_var("CEREBRAS_API_KEY"),
api_base_url="https://api.cerebras.ai/v1",
model="llama3.1-8b",
generation_kwargs = {"max_tokens": 512}
)
messages = []
while True:
msg = input("Enter your message or Q to exit\n🧑 ")
if msg=="Q":
break
messages.append(ChatMessage.from_user(msg))
response = generator.run(messages=messages)
assistant_resp = response['replies'][0]
print("🤖 "+assistant_resp.text)
messages.append(assistant_resp)
