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

集成:MonsterAPI

使用 MonsterAPI 提供的开源语言模型

作者
monsterapi

目录

概述

MonsterAPI 提供访问强大语言模型的接口,这些模型专为各种文本生成任务而设计。通过 MonsterAPI 集成,您可以在 Haystack 框架内利用这些模型,以增强自然语言处理能力。

要开始使用 MonsterAPI,请在此处 注册 API 密钥。此密钥可访问 MonsterAPI,后者支持通过各种参数进行快速推理和定制。

使用

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

使用 Generator

这是一个示例,展示了如何使用 MonsterAPI 提供的模型在网页上执行问答。您需要设置环境变量 MONSTER_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("MONSTER_API_KEY"),
    api_base_url="https://llm.monsterapi.ai/v1/",
    model="microsoft/Phi-3-mini-4k-instruct",
    generation_kwargs = {"max_tokens": 256}
)
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://developer.monsterapi.ai/docs/"]},
              "prompt": {"query": "What are the features of MonsterAPI?"}})

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

使用 ChatGenerator

这是一个示例,展示了如何与 MonsterAPI 模型进行多轮对话。您需要设置环境变量 MONSTER_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("MONSTER_API_KEY"),
    api_base_url="https://llm.monsterapi.ai/v1/",
    model="microsoft/Phi-3-mini-4k-instruct",
    generation_kwargs = {"max_tokens": 256}
)

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)