Repository navigation
[python][examples] Add quickstart workflow examples #158
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| This project uses data generated from the Amazon Review Data (2018) dataset. | ||
|
|
||
| Citation: | ||
| Justifying recommendations using distantly-labeled reviews and fined-grained aspects | ||
| Jianmo Ni, Jiacheng Li, Julian McAuley | ||
| Empirical Methods in Natural Language Processing (EMNLP), 2019 | ||
|
|
||
| Dataset URL: https://nijianmo.github.io/amazon/index.html#complete-data |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| ################################################################################ | ||
| # Licensed to the Apache Software Foundation (ASF) under one | ||
| # or more contributor license agreements. See the NOTICE file | ||
| # distributed with this work for additional information | ||
| # regarding copyright ownership. The ASF licenses this file | ||
| # to you under the Apache License, Version 2.0 (the | ||
| # "License"); you may not use this file except in compliance | ||
| # with the License. You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| ################################################################################# |
17 changes: 17 additions & 0 deletions
17
python/flink_agents/examples/quickstart/agents/__init__.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| ################################################################################ | ||
| # Licensed to the Apache Software Foundation (ASF) under one | ||
| # or more contributor license agreements. See the NOTICE file | ||
| # distributed with this work for additional information | ||
| # regarding copyright ownership. The ASF licenses this file | ||
| # to you under the Apache License, Version 2.0 (the | ||
| # "License"); you may not use this file except in compliance | ||
| # with the License. You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| ################################################################################# |
166 changes: 166 additions & 0 deletions
166
python/flink_agents/examples/quickstart/agents/product_suggestion_agent.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,166 @@ | ||
| ################################################################################ | ||
| # Licensed to the Apache Software Foundation (ASF) under one | ||
| # or more contributor license agreements. See the NOTICE file | ||
| # distributed with this work for additional information | ||
| # regarding copyright ownership. The ASF licenses this file | ||
| # to you under the Apache License, Version 2.0 (the | ||
| # "License"); you may not use this file except in compliance | ||
| # with the License. You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| ################################################################################# | ||
| import json | ||
| import logging | ||
| from typing import Any, Dict, List, Tuple, Type | ||
|
|
||
| from pydantic import BaseModel | ||
|
|
||
| from flink_agents.api.agent import Agent | ||
| from flink_agents.api.chat_message import ChatMessage, MessageRole | ||
| from flink_agents.api.chat_models.chat_model import ( | ||
| BaseChatModelSetup, | ||
| ) | ||
| from flink_agents.api.decorators import ( | ||
| action, | ||
| chat_model_setup, | ||
| prompt, | ||
| ) | ||
| from flink_agents.api.events.chat_event import ChatRequestEvent, ChatResponseEvent | ||
| from flink_agents.api.events.event import InputEvent, OutputEvent | ||
| from flink_agents.api.prompts.prompt import Prompt | ||
| from flink_agents.api.runner_context import RunnerContext | ||
| from flink_agents.integrations.chat_models.ollama_chat_model import ( | ||
| OllamaChatModelSetup, | ||
| ) | ||
|
|
||
|
|
||
| class ProductReviewSummary(BaseModel): | ||
| """Aggregates multiple reviews and insights using LLM for a product. | ||
|
|
||
| Attributes: | ||
| id (str): The unique identifier of the product. | ||
| score_hist (List[str]): A collection of rating scores from various reviews. | ||
| unsatisfied_reasons (List[str]): A list of reasons or insights generated by LLM | ||
| to explain the rating. | ||
| """ | ||
|
|
||
| id: str | ||
| score_hist: List[str] | ||
| unsatisfied_reasons: List[str] | ||
|
|
||
|
|
||
| class ProductSuggestion(BaseModel): | ||
| """Provides a summary of review data including suggestions for improvement. | ||
|
|
||
| Attributes: | ||
| id (str): The unique identifier of the product. | ||
| score_histogram (List[int]): A collection of rating scores from various reviews. | ||
| suggestions (List[str]): Suggestions or recommendations generated as a result of | ||
| review analysis. | ||
| """ | ||
|
|
||
| id: str | ||
| score_hist: List[str] | ||
| suggestions: List[str] | ||
|
|
||
|
|
||
| class ProductSuggestionAgent(Agent): | ||
| """An agent that uses a large language model (LLM) to generate actionable product | ||
| improvement suggestions from aggregated product review data. | ||
|
|
||
| This agent receives a summary of product reviews, including a rating distribution | ||
| and a list of user dissatisfaction reasons, and produces concrete suggestions for | ||
| product enhancement. It handles prompt construction, LLM interaction, and output | ||
| parsing. | ||
| """ | ||
|
|
||
| @prompt | ||
| @staticmethod | ||
| def generate_suggestion_prompt() -> Prompt: | ||
| """Generate product suggestions based on the rating distribution and user | ||
| dissatisfaction reasons. | ||
| """ | ||
| prompt_str = """ | ||
| Based on the rating distribution and user dissatisfaction reasons, generate three actionable suggestions for product improvement. | ||
|
|
||
| Input format: | ||
| {{ | ||
| "id": "1", | ||
| "score_histogram": ["10%", "20%", "10%", "15%", "45%"], | ||
| "unsatisfied_reasons": ["reason1", "reason2", "reason3"] | ||
| }} | ||
|
|
||
| Ensure that your response can be parsed by Python json,use the following format as an example: | ||
| {{ | ||
| "suggestion_list": [ | ||
| "suggestion1", | ||
| "suggestion2", | ||
| "suggestion3" | ||
| ] | ||
| }} | ||
|
|
||
| input: | ||
| {input} | ||
| """ | ||
| return Prompt.from_text("generate_suggestion_prompt", prompt_str) | ||
|
|
||
| @chat_model_setup | ||
| @staticmethod | ||
| def generate_suggestion_model() -> Tuple[Type[BaseChatModelSetup], Dict[str, Any]]: | ||
| """ChatModel which focus on generating product suggestions.""" | ||
| return OllamaChatModelSetup, { | ||
| "name": "generate_suggestion_model", | ||
| "connection": "ollama_server", | ||
| "prompt": "generate_suggestion_prompt", | ||
| "extract_reasoning": True, | ||
| } | ||
|
|
||
| @action(InputEvent) | ||
| @staticmethod | ||
| def process_input(event: InputEvent, ctx: RunnerContext) -> None: | ||
| """Process input event.""" | ||
| input: ProductReviewSummary = event.input | ||
| ctx.get_short_term_memory().set("id", input.id) | ||
| ctx.get_short_term_memory().set("score_hist", input.score_hist) | ||
|
|
||
| content = f""" | ||
| "id": {input.id}, | ||
| "score_histogram": {input.score_hist}, | ||
| "unsatisfied_reasons": {input.unsatisfied_reasons} | ||
| """ | ||
| ctx.send_event( | ||
| ChatRequestEvent( | ||
| model="generate_suggestion_model", | ||
| messages=[ | ||
| ChatMessage(role=MessageRole.USER, extra_args={"input": content}) | ||
| ], | ||
| ) | ||
| ) | ||
|
|
||
| @action(ChatResponseEvent) | ||
| @staticmethod | ||
| def process_chat_response(event: ChatResponseEvent, ctx: RunnerContext) -> None: | ||
| """Process chat response event.""" | ||
| try: | ||
| json_content = json.loads(event.response.content) | ||
| ctx.send_event( | ||
| OutputEvent( | ||
| output=ProductSuggestion( | ||
| id=ctx.get_short_term_memory().get("id"), | ||
| score_hist=ctx.get_short_term_memory().get("score_hist"), | ||
| suggestions=json_content["suggestions"], | ||
| ) | ||
| ) | ||
| ) | ||
| except Exception: | ||
| logging.exception( | ||
| f"Error processing chat response {event.response.content}" | ||
| ) | ||
|
|
||
| # To fail the agent, you can raise an exception here. | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.