📘 **TELUS Agriculture & Consumer Goods** 如何通过 **Haystack Agents** 转变促销交易
由 deepset 维护

集成:Groq

使用 Groq 提供的开放语言模型

作者
deepset

目录

概述

Groq 是一家人工智能公司,开发了语言处理单元(LPU),这是一种专为大型语言模型快速推理而设计的高性能引擎。

要开始使用 Groq,请在此 注册 API 密钥。这将使您能够访问 Groq API,该 API 提供 Mixtral 和 Llama 3 等开放语言模型的快速推理。

使用

Groq API 与 OpenAI 兼容,因此可以通过 Haystack 中的 OpenAI Generators 轻松使用。

使用 Generator

这是一个使用 Groq 提供的 Mixtral 在网页上执行问答的示例。您需要设置环境变量 GROQ_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("GROQ_API_KEY"),
    api_base_url="https://api.groq.com/openai/v1",
    model="mixtral-8x7b-32768",
    generation_kwargs = {"max_tokens": 512}
)
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://wow.groq.com/why-groq/"]},
              "prompt": {"query": "Why should I use Groq for serving LLMs?"}})

print(result["llm"]["replies"][0])

使用 ChatGenerator

请参阅一个与 Llama 3 进行多轮对话的示例。您需要设置环境变量 GROQ_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("GROQ_API_KEY"),
    api_base_url="https://api.groq.com/openai/v1",
    model="llama3-8b-8192",
    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)