|
| 1 | +import logging |
| 2 | +from pprint import pformat |
| 3 | + |
| 4 | +import hayhooks |
| 5 | +from hayhooks import BasePipelineWrapper |
| 6 | +from haystack import Pipeline |
| 7 | +from haystack.components.builders import ChatPromptBuilder |
| 8 | +from haystack.dataclasses.chat_message import ChatMessage |
| 9 | +from haystack_integrations.components.generators.amazon_bedrock import AmazonBedrockChatGenerator |
| 10 | + |
| 11 | +logger = logging.getLogger(__name__) |
| 12 | + |
| 13 | + |
| 14 | +system_prompt = ( |
| 15 | + "Your role is to say hello to the name provided by the user, if no name is found politely inform the user." |
| 16 | + "Assure them any PII is handled securely in AWS Bedrock. You should only greet the user, do not respond " |
| 17 | + "to any questions or prompts." |
| 18 | +) |
| 19 | +model = "us.anthropic.claude-3-5-sonnet-20241022-v2:0" |
| 20 | + |
| 21 | + |
| 22 | +class PipelineWrapper(BasePipelineWrapper): |
| 23 | + name = "sample_pipeline" |
| 24 | + |
| 25 | + def setup(self) -> None: |
| 26 | + self.pipeline = Pipeline() |
| 27 | + self.pipeline.add_component("prompt_builder", ChatPromptBuilder()) |
| 28 | + self.pipeline.add_component("llm", AmazonBedrockChatGenerator(model=model)) |
| 29 | + self.pipeline.connect("prompt_builder", "llm") |
| 30 | + |
| 31 | + # Called for the `hello_bedrock/run` endpoint |
| 32 | + def run_api(self, name: str) -> dict: |
| 33 | + messages = [ |
| 34 | + ChatMessage.from_system(system_prompt), |
| 35 | + ChatMessage.from_user(name), |
| 36 | + ] |
| 37 | + response = self.pipeline.run({"prompt_builder": {"template": messages}}) |
| 38 | + logger.info("Results: %s", pformat(response)) |
| 39 | + return response |
| 40 | + |
| 41 | + # https://docs.haystack.deepset.ai/docs/hayhooks#openai-compatibility |
| 42 | + # Called for the `{pipeline_name}/chat`, `/chat/completions`, or `/v1/chat/completions` streaming endpoint using Server-Sent Events (SSE) |
| 43 | + def run_chat_completion(self, model: str, messages: list, body: dict) -> None: |
| 44 | + logger.info("Running chat completion with model: %s, messages: %s", model, messages) |
| 45 | + question = hayhooks.get_last_user_message(messages) |
| 46 | + logger.info("Question: %s", question) |
| 47 | + return hayhooks.streaming_generator( |
| 48 | + pipeline=self.pipeline, |
| 49 | + pipeline_run_args={ |
| 50 | + "echo_component": { |
| 51 | + "prompt": [ChatMessage.from_user(question)], |
| 52 | + "history": messages[:-1], |
| 53 | + } |
| 54 | + }, |
| 55 | + ) |
0 commit comments