mirror of
https://github.com/meta-llama/llama-stack.git
synced 2025-12-03 18:00:36 +00:00
Updated some examples
This commit is contained in:
parent
e64f78be6e
commit
8f7244e980
1 changed files with 396 additions and 291 deletions
|
|
@ -6,7 +6,7 @@
|
|||
"source": [
|
||||
"# Microsoft Agent Framework + Llama Stack Integration\n",
|
||||
"\n",
|
||||
"[](https://colab.research.google.com/github/meta-llama/llama-stack/blob/main/docs/notebooks/autogen/microsoft_agent_framework_llama_stack_integration.ipynb)\n",
|
||||
"[](https://colab.research.google.com/github/meta-llama/llama-stack/blob/main/docs/notebooks/microsoft_agent_framework/microsoft_agent_framework_llama_stack_integration.ipynb)\n",
|
||||
"\n",
|
||||
"## Overview\n",
|
||||
"\n",
|
||||
|
|
@ -15,10 +15,11 @@
|
|||
"> **Note:** This notebook uses Microsoft Agent Framework, which replaces AutoGen. For the migration guide, see: [Microsoft Agent Framework Migration Guide](https://learn.microsoft.com/en-us/agent-framework/migration-guide/from-autogen/)\n",
|
||||
"\n",
|
||||
"### Use Cases Covered:\n",
|
||||
"1. **Two-Agent Conversation** - Teams working together on tasks\n",
|
||||
"2. **Code Generation & Execution** - Agents generating and running code\n",
|
||||
"3. **Group Chat** - Multiple specialists collaborating \n",
|
||||
"4. **Advanced Termination** - Stopping conditions\n",
|
||||
"1. **Simple ChatAgent** - Single agent task execution\n",
|
||||
"2. **Sequential Workflow** - Round-robin multi-agent collaboration\n",
|
||||
"3. **AgentThread** - Stateful multi-turn conversations\n",
|
||||
"4. **Custom Workflow** - Data-flow with executors and feedback loops\n",
|
||||
"5. **Concurrent Workflow** - Parallel agent processing\n",
|
||||
"\n",
|
||||
"---\n",
|
||||
"\n",
|
||||
|
|
@ -42,7 +43,7 @@
|
|||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 19,
|
||||
"execution_count": 1,
|
||||
"metadata": {
|
||||
"scrolled": true
|
||||
},
|
||||
|
|
@ -100,7 +101,7 @@
|
|||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 20,
|
||||
"execution_count": 2,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
|
|
@ -150,7 +151,7 @@
|
|||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 13,
|
||||
"execution_count": 3,
|
||||
"metadata": {
|
||||
"scrolled": true
|
||||
},
|
||||
|
|
@ -165,22 +166,16 @@
|
|||
"Task Result:\n",
|
||||
"To find the sum of the first 10 prime numbers, we need to follow these steps:\n",
|
||||
"\n",
|
||||
"**Step 1: List out the first few prime numbers**\n",
|
||||
"Prime numbers are numbers greater than 1 that have no divisors other than 1 and themselves. Let's start listing them out:\n",
|
||||
"2, 3, 5, 7, 11, ...\n",
|
||||
"**Step 1: Identify the first 10 prime numbers**\n",
|
||||
"\n",
|
||||
"**Step 2: Identify the first 10 prime numbers**\n",
|
||||
"We need to find the next 4 prime numbers after 7 and 11.\n",
|
||||
"13 is a prime number (only divisible by 1 and 13).\n",
|
||||
"17 is a prime number (only divisible by 1 and 17).\n",
|
||||
"19 is a prime number (only divisible by 1 and 19).\n",
|
||||
"23 is a prime number (only divisible by 1 and 23).\n",
|
||||
"\n",
|
||||
"So, the first 10 prime numbers are:\n",
|
||||
"A prime number is a positive integer that is divisible only by itself and 1. We will list out the first few prime numbers until we have 10:\n",
|
||||
"2, 3, 5, 7, 11, 13, 17, 19, 23, 29\n",
|
||||
"\n",
|
||||
"**Step 3: Calculate the sum of these prime numbers**\n",
|
||||
"Now, let's add them up:\n",
|
||||
"These are the first 10 prime numbers.\n",
|
||||
"\n",
|
||||
"**Step 2: Add up the prime numbers**\n",
|
||||
"\n",
|
||||
"Now, we simply need to add these numbers together:\n",
|
||||
"2 + 3 = 5\n",
|
||||
"5 + 5 = 10\n",
|
||||
"10 + 7 = 17\n",
|
||||
|
|
@ -191,11 +186,11 @@
|
|||
"77 + 23 = 100\n",
|
||||
"100 + 29 = 129\n",
|
||||
"\n",
|
||||
"**Step 4: Write the final answer**\n",
|
||||
"The sum of the first 10 prime numbers is:\n",
|
||||
"129\n",
|
||||
"\n",
|
||||
"Therefore, the sum of the first 10 prime numbers is **129**.\n",
|
||||
"\n",
|
||||
"So, to summarize:\n",
|
||||
"The first 10 prime numbers are: 2, 3, 5, 7, 11, 13, 17, 19, 23, and 29.\n",
|
||||
"Their sum is: 2 + 3 + 5 + 7 + 11 + 13 + 17 + 19 + 23 + 29 = **129**.\n",
|
||||
"==================================================\n"
|
||||
]
|
||||
}
|
||||
|
|
@ -203,7 +198,6 @@
|
|||
"source": [
|
||||
"import asyncio\n",
|
||||
"\n",
|
||||
"# Create a ChatAgent (replaces AutoGen's AssistantAgent)\n",
|
||||
"# Method 1: Direct creation\n",
|
||||
"assistant = ChatAgent(\n",
|
||||
" name=\"MathAssistant\",\n",
|
||||
|
|
@ -211,12 +205,6 @@
|
|||
" instructions=\"You are a helpful AI assistant that solves math problems. Provide clear explanations and show your work.\"\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"# Method 2: Using client factory (more convenient)\n",
|
||||
"# assistant = chat_client.create_agent(\n",
|
||||
"# name=\"MathAssistant\",\n",
|
||||
"# instructions=\"You are a helpful AI assistant.\"\n",
|
||||
"# )\n",
|
||||
"\n",
|
||||
"print(\"✅ Agent created:\", assistant.name)\n",
|
||||
"\n",
|
||||
"# Define the task\n",
|
||||
|
|
@ -241,7 +229,6 @@
|
|||
"### Pattern: Sequential Workflow (Round-Robin Style)\n",
|
||||
"\n",
|
||||
"Agent Framework uses **SequentialBuilder** to create workflows where agents take turns.\n",
|
||||
"This replaces AutoGen's `RoundRobinGroupChat`.\n",
|
||||
"\n",
|
||||
"**Key Concepts:**\n",
|
||||
"- `SequentialBuilder`: Agents process messages sequentially\n",
|
||||
|
|
@ -253,7 +240,7 @@
|
|||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 14,
|
||||
"execution_count": 4,
|
||||
"metadata": {
|
||||
"scrolled": true
|
||||
},
|
||||
|
|
@ -271,80 +258,157 @@
|
|||
"Turn 1 [user]:\n",
|
||||
"Write a 200-word blog post about the benefits of using Llama Stack for LLM applications.\n",
|
||||
"\n",
|
||||
"Steps:\n",
|
||||
"1. Researcher: Gather key information about Llama Stack\n",
|
||||
"2. Writer: Create the blog post\n",
|
||||
"3. Critic: Revi...\n",
|
||||
"\n",
|
||||
"Turn 2 [assistant]:\n",
|
||||
"**Unlocking Efficient LLM Applications with Llama Stack**\n",
|
||||
"\n",
|
||||
"The rise of Large Language Models (LLMs) has transformed the artificial intelligence landscape, enabling cutting-edge natural language proces...\n",
|
||||
"\n",
|
||||
"Turn 3 [assistant]:\n",
|
||||
"Topic: Benefits of Llama Stack for LLM applications\n",
|
||||
"Target length: 200 words\n",
|
||||
"Audience: Developers and technical decision-makers\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"Turn 4 [assistant]:\n",
|
||||
"Turn 2 [assistant - Researcher]:\n",
|
||||
"* Llama Stack is an open-source framework for building LLM applications\n",
|
||||
"* Improves model performance with optimized algorithms and hyperparameters\n",
|
||||
"* Supports multiple frameworks, including PyTorch and TensorFlow\n",
|
||||
"* Reduces development time by up to 30% with pre-built components\n",
|
||||
"* Enhances scalability with distributed training capabilities\n",
|
||||
"* Provides seamless integration with popular libraries and tools\n",
|
||||
"\n",
|
||||
"Research complete. Passing to Writer.\n",
|
||||
"\n",
|
||||
"Turn 3 [assistant - Writer]:\n",
|
||||
" \n",
|
||||
"\n",
|
||||
"---\n",
|
||||
"### Introduction to Llama Stack \n",
|
||||
"The Llama Stack is designed to simplify the development of LLM applications, providing numerous benefits for developers and technical decision-makers.\n",
|
||||
"\n",
|
||||
"**Critic's Review:**\n",
|
||||
"### Benefits of Using Llama Stack\n",
|
||||
"Using Llama Stack offers several advantages, including improved model performance, reduced development time, and enhanced scalability. With its optimized algorithms and hyperparameters, Llama Stack enables developers to build high-performing LLM models. The framework's pre-built components and support for multiple frameworks reduce development time, allowing developers to focus on other aspects of their project.\n",
|
||||
"\n",
|
||||
"The blog post effectively introduces the benefits of using Llama Stack for LLM applications, highlighting key advantages such as simplified model deployment and improved ...\n"
|
||||
"By leveraging Llama Stack, developers can streamline their workflow, improve model accuracy, and deploy LLM applications more efficiently. Whether building chatbots, language translators, or text generators, Llama Stack provides a robust foundation for developing innovative LLM applications.\n",
|
||||
"Draft complete. Passing to Critic.\n",
|
||||
"\n",
|
||||
"Turn 4 [assistant - Critic]:\n",
|
||||
" \n",
|
||||
"\n",
|
||||
"**Review:**\n",
|
||||
"1. The blog post jumps abruptly from introducing Llama Stack to listing its benefits without providing a clear connection between the two sections. Consider adding a transitional sentence or phrase to guide the reader more smoothly through the text.\n",
|
||||
"2. While the benefits of using Llama Stack are mentioned, such as improved model performance and reduced development time, specific examples or case studies that illustrate these benefits would make the content more engaging and concrete for the audience.\n",
|
||||
"3. The tone of the blog post is quite formal, which may suit technical decision-makers but could be more approachable for a broader developer audience. Incorporating more conversational language or anecdotes about the challenges of LLM development and how Llama Stack addresses them might enhance readability and appeal.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"from agent_framework import SequentialBuilder, WorkflowOutputEvent\n",
|
||||
"\n",
|
||||
"# Create specialist agents\n",
|
||||
"# Create specialist agents with very strict role separation\n",
|
||||
"researcher = ChatAgent(\n",
|
||||
" name=\"Researcher\",\n",
|
||||
" chat_client=chat_client,\n",
|
||||
" instructions=\"You are a researcher. Provide accurate information, facts, and statistics about topics.\"\n",
|
||||
" instructions=\"\"\"You are a researcher. Your ONLY job is to gather facts, statistics, and key information.\n",
|
||||
" \n",
|
||||
" DO:\n",
|
||||
" - Provide bullet points of facts and key information\n",
|
||||
" - Include relevant statistics if available\n",
|
||||
" - Keep it concise (50-100 words max)\n",
|
||||
" \n",
|
||||
" DO NOT:\n",
|
||||
" - Write full paragraphs or blog posts\n",
|
||||
" - Act as a writer or editor\n",
|
||||
" - Provide any writing beyond factual bullet points\n",
|
||||
" \n",
|
||||
" End your response by saying: \"Research complete. Passing to Writer.\"\n",
|
||||
" \"\"\"\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"writer = ChatAgent(\n",
|
||||
" name=\"Writer\",\n",
|
||||
" chat_client=chat_client,\n",
|
||||
" instructions=\"You are a technical writer. Write clear, engaging content based on research provided.\"\n",
|
||||
" instructions=\"\"\"You are a technical writer. Your ONLY job is to take research and write a blog post.\n",
|
||||
" \n",
|
||||
" DO:\n",
|
||||
" - Use the research provided by the Researcher\n",
|
||||
" - Write a clear, engaging 200-word blog post\n",
|
||||
" - Use proper formatting (headers, paragraphs)\n",
|
||||
" - Focus on benefits and value\n",
|
||||
" \n",
|
||||
" DO NOT:\n",
|
||||
" - Do research yourself\n",
|
||||
" - Review or critique your own work\n",
|
||||
" - Act as an editor or critic\n",
|
||||
" \n",
|
||||
" End your response by saying: \"Draft complete. Passing to Critic.\"\n",
|
||||
" \"\"\"\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"critic = ChatAgent(\n",
|
||||
" name=\"Critic\",\n",
|
||||
" chat_client=chat_client,\n",
|
||||
" instructions=\"You are an editor. Review content for clarity, accuracy, and engagement. Suggest improvements.\"\n",
|
||||
" instructions=\"\"\"You are an editor and critic. Your ONLY job is to review the blog post written by the Writer.\n",
|
||||
" \n",
|
||||
" DO:\n",
|
||||
" - Review the blog post for clarity, accuracy, and engagement\n",
|
||||
" - Provide 3-5 specific, constructive suggestions for improvement\n",
|
||||
" - Comment on structure, tone, and effectiveness\n",
|
||||
" - Be constructive but honest\n",
|
||||
" \n",
|
||||
" DO NOT:\n",
|
||||
" - Rewrite the blog post yourself\n",
|
||||
" - Do research or writing\n",
|
||||
" - Say \"looks good\" without providing specific feedback\n",
|
||||
" \n",
|
||||
" Provide your review in this format:\n",
|
||||
" **Review:**\n",
|
||||
" 1. [Suggestion 1]\n",
|
||||
" 2. [Suggestion 2]\n",
|
||||
" 3. [Suggestion 3]\n",
|
||||
" \"\"\"\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"print(\"✅ Team agents created: Researcher, Writer, Critic\")\n",
|
||||
"\n",
|
||||
"# Create a sequential workflow (round-robin collaboration)\n",
|
||||
"# Each agent processes the input and builds on previous agents' work\n",
|
||||
"workflow = SequentialBuilder().participants([researcher, writer, critic]).build()\n",
|
||||
"\n",
|
||||
"# Simpler task that doesn't list all the steps (to avoid confusion)\n",
|
||||
"task = \"\"\"Write a 200-word blog post about the benefits of using Llama Stack for LLM applications.\n",
|
||||
"\n",
|
||||
"Steps:\n",
|
||||
"1. Researcher: Gather key information about Llama Stack\n",
|
||||
"2. Writer: Create the blog post\n",
|
||||
"3. Critic: Review and suggest improvements\n",
|
||||
"Topic: Benefits of Llama Stack for LLM applications\n",
|
||||
"Target length: 200 words\n",
|
||||
"Audience: Developers and technical decision-makers\n",
|
||||
"\"\"\"\n",
|
||||
"\n",
|
||||
"print(\"\\n\" + \"=\"*50)\n",
|
||||
"print(\"Running Sequential Workflow:\")\n",
|
||||
"print(\"=\"*50)\n",
|
||||
"\n",
|
||||
"# Run the workflow and collect results\n",
|
||||
"turn = 1\n",
|
||||
"# Run the workflow and display results with agent names\n",
|
||||
"async for event in workflow.run_stream(task):\n",
|
||||
" if isinstance(event, WorkflowOutputEvent):\n",
|
||||
" # Final output contains full conversation history\n",
|
||||
" conversation_history = event.data\n",
|
||||
" \n",
|
||||
" # Map assistant messages to agent names using position\n",
|
||||
" agent_names = [\"Researcher\", \"Writer\", \"Critic\"]\n",
|
||||
" turn = 1\n",
|
||||
" assistant_count = 0\n",
|
||||
" \n",
|
||||
" for msg in conversation_history:\n",
|
||||
" print(f\"\\nTurn {turn} [{msg.role}]:\")\n",
|
||||
" print(msg.text[:200] + \"...\" if len(msg.text or \"\") > 200 else msg.text)\n",
|
||||
" turn += 1"
|
||||
" # Normalize role to string for comparison (msg.role is a Role enum)\n",
|
||||
" role_str = str(msg.role).lower().strip()\n",
|
||||
" \n",
|
||||
" # Determine the speaker label\n",
|
||||
" if role_str == \"user\":\n",
|
||||
" speaker = \"user\"\n",
|
||||
" elif role_str == \"assistant\":\n",
|
||||
" if assistant_count < len(agent_names):\n",
|
||||
" speaker = f\"assistant - {agent_names[assistant_count]}\"\n",
|
||||
" else:\n",
|
||||
" speaker = \"assistant\"\n",
|
||||
" assistant_count += 1\n",
|
||||
" else:\n",
|
||||
" speaker = str(msg.role)\n",
|
||||
" \n",
|
||||
" # Display the message\n",
|
||||
" print(f\"\\nTurn {turn} [{speaker}]:\")\n",
|
||||
" print(msg.text[:1000] + \"...\" if len(msg.text or \"\") > 1000 else msg.text)\n",
|
||||
" turn += 1\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
|
|
@ -360,17 +424,14 @@
|
|||
"**AgentThread Features:**\n",
|
||||
"- Stores conversation history\n",
|
||||
"- Allows context to carry across multiple `agent.run()` calls\n",
|
||||
"- Can be backed by external storage (Redis, databases)\n",
|
||||
"\n",
|
||||
"### Use Case: Interactive Analysis"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 15,
|
||||
"metadata": {
|
||||
"scrolled": true
|
||||
},
|
||||
"execution_count": 5,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
|
|
@ -383,22 +444,19 @@
|
|||
"==================================================\n",
|
||||
"\n",
|
||||
"[Turn 1 - Initial Analysis]:\n",
|
||||
"**Introduction**\n",
|
||||
"**Introduction to Local LLMs vs Cloud-Based APIs**\n",
|
||||
"\n",
|
||||
"Large Language Models (LLMs) have revolutionized the field of natural language processing, enabling applications such as text classification, sentiment analysis, and language translation. Two popular approaches to deploying LLMs are using local models and cloud-based APIs. In this analysis, we will break down the trade-offs between these two approaches, highlighting their pros an...\n",
|
||||
"The rise of Large Language Models (LLMs) has revolutionized natural language processing, offering unparalleled capabilities in text generation, comprehension, and analysis. Users can access these powerful models via two primary avenues: local deployment or cloud-based Application Programming Interfaces (APIs). Each approach presents distinct adva...\n",
|
||||
"\n",
|
||||
"[Turn 2 - Follow-up on Cost]:\n",
|
||||
"**Cost Implications: Local LLMs vs Cloud-based APIs**\n",
|
||||
"**Cost Implications: Local LLMs vs Cloud-Based APIs**\n",
|
||||
"\n",
|
||||
"The cost implications of using local LLMs versus cloud-based APIs are significant and can vary greatly depending on the specific requirements and deployment scenarios. Here's a detailed breakdown of the costs associated with each approach:\n",
|
||||
"When evaluating the cost implications of local LLMs versus cloud-based APIs, several factors come into play. These include initial investment, ongoing expenses, scalability costs, and potential savings. Each approach has distinct cost characteristics that can significantly impact an organization's budget and ROI (Return on Investment).\n",
|
||||
"\n",
|
||||
"**Local LLMs**\n",
|
||||
"\n",
|
||||
"1. **Initial Investment**:\n",
|
||||
"\t* Hardware: High-performance GPUs, high-capacity storage, an...\n",
|
||||
"### **...\n",
|
||||
"\n",
|
||||
"[Turn 3 - Summary]:\n",
|
||||
"Organizations should choose between local LLMs and cloud-based APIs based on their specific requirements, weighing factors such as security, customizability, scalability, and cost, with local LLMs suitable for high-traffic or sensitive applications and cloud-based APIs ideal for low-traffic or prototyping scenarios.\n",
|
||||
"I recommend choosing between local LLM deployment and cloud-based APIs based on a careful consideration of factors such as data sensitivity, scalability needs, budget constraints, and the importance of customization and control, with local deployment suitable for high-security applications and cloud-based APIs ideal for scalable, cost-efficient solutions with lower security demands.\n",
|
||||
"\n",
|
||||
"==================================================\n",
|
||||
"Thread maintained context across 3 turns\n",
|
||||
|
|
@ -478,7 +536,7 @@
|
|||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 21,
|
||||
"execution_count": 6,
|
||||
"metadata": {
|
||||
"scrolled": true
|
||||
},
|
||||
|
|
@ -487,182 +545,196 @@
|
|||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"✅ Code review team created\n",
|
||||
"✅ Code review team created with strict instructions\n",
|
||||
"\n",
|
||||
"==================================================\n",
|
||||
"Code Review Workflow:\n",
|
||||
"==================================================\n",
|
||||
"============================================================\n",
|
||||
"Code Review Workflow (with iteration tracking):\n",
|
||||
"============================================================\n",
|
||||
"\n",
|
||||
"[Iteration 1 - Final Result]:\n",
|
||||
"✅ APPROVED\n",
|
||||
"\n",
|
||||
"Code:\n",
|
||||
"**Email Validation Function in Python**\n",
|
||||
"=====================================\n",
|
||||
"\n",
|
||||
"The following Python function validates an email address, ensuring it meets the specified requirements.\n",
|
||||
"\n",
|
||||
"### Implementation\n",
|
||||
"```python\n",
|
||||
" [Developer - Iteration 1]\n",
|
||||
" Code submitted for review (preview): ```python\n",
|
||||
"import re\n",
|
||||
"\n",
|
||||
"def validate_email(email: str) -> bool:\n",
|
||||
" \"\"\"\n",
|
||||
" Validates an email address.\n",
|
||||
" Validat...\n",
|
||||
"\n",
|
||||
" Args:\n",
|
||||
" - email (str): The email address to be validated.\n",
|
||||
" [Reviewer - Iteration 1]\n",
|
||||
" Decision: ❌ NEEDS REVISION\n",
|
||||
" Sending feedback to developer...\n",
|
||||
"\n",
|
||||
" Returns:\n",
|
||||
" - bool: True if the email is valid, False otherwise.\n",
|
||||
" \"\"\"\n",
|
||||
"\n",
|
||||
" # Define a regular expression pattern for email validation\n",
|
||||
" pattern = r\"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$\"\n",
|
||||
"\n",
|
||||
" try:\n",
|
||||
" # Check if the input is a string\n",
|
||||
" if not isinstance(email, str):\n",
|
||||
" raise TypeError(\"Input must be a string.\")\n",
|
||||
"\n",
|
||||
" # Remove leading and trailing whitespaces\n",
|
||||
" email = email.strip()\n",
|
||||
"\n",
|
||||
" # Check for spaces in the email address\n",
|
||||
" if \" \" in email:\n",
|
||||
" print(\"Error: No spaces are allowed in the email address.\")\n",
|
||||
" return False\n",
|
||||
"\n",
|
||||
" # Check if the email matches the pattern\n",
|
||||
" if not re.match(pattern, email):\n",
|
||||
" print(\"Error: Invalid email format. Please use a valid email address.\")\n",
|
||||
" return False\n",
|
||||
"\n",
|
||||
" return True\n",
|
||||
"\n",
|
||||
" except TypeError as e:\n",
|
||||
" print(f\"Error: {e}\")\n",
|
||||
" return False\n",
|
||||
"\n",
|
||||
" except Exception as e:\n",
|
||||
" print(f\"An unexpected error occurred: {e}\")\n",
|
||||
" return False\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# Example usage\n",
|
||||
"if __name__ == \"__main__\":\n",
|
||||
" emails = [\n",
|
||||
" \"test@example.com\",\n",
|
||||
" \"invalid_email\",\n",
|
||||
" \"test@ example.com\",\n",
|
||||
" \"test@example\",\n",
|
||||
" 123, # Test with an invalid input type\n",
|
||||
" ]\n",
|
||||
"\n",
|
||||
" for email in emails:\n",
|
||||
" print(f\"Email: {email}\")\n",
|
||||
" is_valid = validate_email(email)\n",
|
||||
" print(f\"Is Valid: {is_valid}\")\n",
|
||||
" print(\"-\" * 50)\n",
|
||||
"\n",
|
||||
"```\n",
|
||||
"\n",
|
||||
"### Explanation\n",
|
||||
"\n",
|
||||
"This function uses a regular expression pattern to match the general format of an email address. The `validate_email` function checks for the following:\n",
|
||||
"\n",
|
||||
"* The input is a string.\n",
|
||||
"* There are no spaces in the email address.\n",
|
||||
"* The email address matches the defined pattern, which includes:\n",
|
||||
" * One or more alphanumeric characters, dots, underscores, pluses, or hyphens before the `@` symbol.\n",
|
||||
" * The `@` symbol.\n",
|
||||
" * One or more alphanumeric characters, hyphens, or dots after the `@` symbol and before the first dot in the domain.\n",
|
||||
" * At least one dot in the domain.\n",
|
||||
"\n",
|
||||
"If any of these conditions are not met, the function prints an error message indicating what went wrong and returns `False`. If all checks pass, it returns `True`, indicating a valid email address.\n",
|
||||
"\n",
|
||||
"### Error Handling\n",
|
||||
"\n",
|
||||
"The code includes proper error handling:\n",
|
||||
"\n",
|
||||
"* **TypeError**: Raised if the input is not a string.\n",
|
||||
"* **Exception**: Catches any unexpected errors and prints an error message.\n",
|
||||
"\n",
|
||||
"Each error case provides informative messages to help with debugging.\n",
|
||||
"\n",
|
||||
"Review:\n",
|
||||
"**Code Review**\n",
|
||||
"\n",
|
||||
"Overall, the provided Python function for email validation looks clean and well-structured. It effectively checks if the input string matches the typical format of an email address using a regular expression pattern. However, there are some areas that can be improved upon:\n",
|
||||
"\n",
|
||||
"### Bugs and Edge Cases\n",
|
||||
"1. **Input Validation**: In the current implementation, `TypeError` is raised when the input is not a string, but then immediately caught and handled within the same function. Consider letting it propagate up instead of catching it here since you're already returning an error message and `False`.\n",
|
||||
"2. **Email Length Limitation**: The regular expression does not account for email length limits. As per [RFC 5321](https://tools.ietf.org/html/rfc5321#section-4.5.3), the maximum total length of a mailbox (local part plus domain) is 320 characters, but some mail servers may enforce shorter limits.\n",
|
||||
"3. **Internationalized Domain Names (IDNs)**: The function does not support IDNs which are domain names that contain non-ASCII characters.\n",
|
||||
"\n",
|
||||
"### Performance Issues\n",
|
||||
"1. **Regular Expression Compilation**: If this function is called frequently, compiling the regular expression pattern once outside of it and storing the result in a variable can improve performance.\n",
|
||||
"2. **Exception Handling Overhead**: Python exceptions come with some overhead. Using if-statements to handle anticipated conditions (like type checking) instead of using exceptions for control flow might be more efficient.\n",
|
||||
"\n",
|
||||
"### Security Vulnerabilities\n",
|
||||
"No significant security vulnerabilities were identified, but it's essential to note that validating an email address does not necessarily mean the provided email exists or can receive mail; a separate verification process (usually involving sending a confirmation link) should be implemented if you need to confirm the existence of the email account.\n",
|
||||
"\n",
|
||||
"### Best Practices\n",
|
||||
"1. **Direct Printing**: Instead of directly printing error messages from within the function, consider raising exceptions with descriptive messages. This approach allows the caller to handle errors as needed.\n",
|
||||
"2. **Variable Naming and Comments**: Although comments are provided in the docstring and around code blocks explaining what each segment does, variable names like `email` could be more descriptive (e.g., `input_email_address`). However, given the context, `email` is sufficient here.\n",
|
||||
"3. **Example Usage**: The example usage section provides a simple demonstration of how to use the `validate_email` function with different inputs.\n",
|
||||
"\n",
|
||||
"### Code Improvements\n",
|
||||
"\n",
|
||||
"```python\n",
|
||||
" [Developer - Iteration 2]\n",
|
||||
" Code submitted for review (preview): ```python\n",
|
||||
"import re\n",
|
||||
"\n",
|
||||
"EMAIL_PATTERN = re.compile(\n",
|
||||
" r\"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$\",\n",
|
||||
" flags=re.IGNORECASE,\n",
|
||||
")\n",
|
||||
"# Define a regular expression pattern for email validation ...\n",
|
||||
"\n",
|
||||
"def validate_email_address(input_string: str) -> bool:\n",
|
||||
" \"\"\"Validate an email address.\"\"\"\n",
|
||||
" \n",
|
||||
" # Input type check\n",
|
||||
" if not isinstance(input_string, str):\n",
|
||||
" raise TypeError(\"Input must be a string.\")\n",
|
||||
" [Reviewer - Iteration 2]\n",
|
||||
" Decision: ❌ NEEDS REVISION\n",
|
||||
" Sending feedback to developer...\n",
|
||||
"\n",
|
||||
" input_string = input_string.strip()\n",
|
||||
" \n",
|
||||
" if \" \" in input_string:\n",
|
||||
" raise ValueError(\"No spaces are allowed in the email address.\")\n",
|
||||
" \n",
|
||||
" if len(input_string) > 320: # Basic length validation as per RFC5321\n",
|
||||
" raise ValueError(\"Email address exceeds maximum length limit.\")\n",
|
||||
" [Developer - Iteration 3]\n",
|
||||
" Code submitted for review (preview): ```python\n",
|
||||
"import re\n",
|
||||
"\n",
|
||||
" # Regular expression match for basic email format validity\n",
|
||||
" return bool(EMAIL_PATTERN.match(input_string))\n",
|
||||
"# Define a regular expression pattern for email validation ...\n",
|
||||
"\n",
|
||||
"# Example usage with error handling\n",
|
||||
" [Reviewer - Iteration 3]\n",
|
||||
" Decision: ❌ NEEDS REVISION\n",
|
||||
" Sending feedback to developer...\n",
|
||||
"\n",
|
||||
" [Developer - Iteration 4]\n",
|
||||
" Code submitted for review (preview): ```python\n",
|
||||
"import re\n",
|
||||
"import logging\n",
|
||||
"\n",
|
||||
"# Define constants for email validation\n",
|
||||
"EMAI...\n",
|
||||
"\n",
|
||||
" [Reviewer - Iteration 4]\n",
|
||||
" Decision: ❌ NEEDS REVISION\n",
|
||||
"\n",
|
||||
"============================================================\n",
|
||||
"FINAL RESULT:\n",
|
||||
"============================================================\n",
|
||||
"⚠️ MAX ITERATIONS REACHED (4)\n",
|
||||
"\n",
|
||||
"📝 Last Review:\n",
|
||||
"NEEDS REVISION: \n",
|
||||
"The code provided has several areas that need improvement. Here are the specific issues:\n",
|
||||
"\n",
|
||||
"1. **Input Validation**: The `validate_input` function checks if the input email is a string and raises a TypeError if not. However, in the example usage, there's an attempt to call `validate_email(None)`. When this happens, the code does indeed raise an error, but it would be more Pythonic to explicitly check for `None` before calling `validate_input`, since `isinstance(None, str)` is False.\n",
|
||||
"\n",
|
||||
"2. **Internationalized Domain Name (IDN) Handling**: The code logs a warning when an IDN is detected but doesn't further validate the domain name according to IDN rules. It would be more robust to actually check if the domain can be encoded in ASCII using Punycode for validation purposes, rather than just logging a warning.\n",
|
||||
"\n",
|
||||
"3. **Error Handling in `validate_email_format`**: This function catches `re.error` exceptions but then immediately raises them again. If the intention is to log the error before re-raising it, this code achieves that. However, if not handling these errors further (e.g., providing a default return value or additional processing), consider removing the try-except block since it does not add any functionality beyond what's already built into Python.\n",
|
||||
"\n",
|
||||
"4. **Logging**: The code uses `logging.error` and `logging.warning` to log various events but does not configure logging anywhere in the provided snippet. Ensure that logging is configured appropriately at the application level, including setting a logging level and handlers for where log messages should be sent (e.g., console, file).\n",
|
||||
"\n",
|
||||
"5. **Type Hints for Exception Returns**: While type hints are used for function arguments and return types, consider adding them for raised exceptions as well to make the code's behavior more explicit.\n",
|
||||
"\n",
|
||||
"6. **Redundant Pattern Matching**: The `validate_email_format` function first checks if an email is non-ASCII before attempting a pattern match with `EMAIL_PATTERN`. However, since `EMAIL_PATTERN` only matches ASCII characters (due to its structure), the check for ASCII can be omitted as it's implicitly required by the regular expression. \n",
|
||||
"\n",
|
||||
"7. **Potential Regular Expression Denial of Service (ReDoS)**: Regular expressions are vulnerable to ReDoS when certain patterns cause catastrophic backtracking, leading to exponential time complexity in matching strings. While `EMAIL_PATTERN` seems safe, consider using more efficient validation methods or libraries specifically designed for email address validation if possible.\n",
|
||||
"\n",
|
||||
"8. **Comment on Edge Cases**: The code attempts to validate common email formats but notes it might not cover all edge cases according to the official standard (RFC 5322). It would be beneficial to document which specific edge cases this implementation does not handle to set expectations for its usage and limitations. \n",
|
||||
"\n",
|
||||
"9. **Testing Coverage**: Although there's an example usage with a range of test emails, consider using a unit testing framework like `unittest` to write and run structured tests against the validation functions. This approach ensures more comprehensive coverage of potential inputs and makes it easier to identify regressions if the code is modified in the future.\n",
|
||||
"\n",
|
||||
"10. **Consider Using Existing Libraries**: Email address validation can be complex, especially when considering international domain names and all possible valid formats according to RFCs. Consider using an existing library designed specifically for this purpose, like `email-validator`, which might offer more comprehensive and reliable validation capabilities than a custom implementation.\n",
|
||||
"\n",
|
||||
"💻 Last Code:\n",
|
||||
"```python\n",
|
||||
"import re\n",
|
||||
"import logging\n",
|
||||
"\n",
|
||||
"# Define constants for email validation\n",
|
||||
"EMAIL_PATTERN = r\"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$\"\n",
|
||||
"MAX_EMAIL_LENGTH = 254 # Maximum allowed length of an email address\n",
|
||||
"IDN_PATTERN = r\"^xn--.*$\" # Pattern to match internationalized domain names (IDNs)\n",
|
||||
"\n",
|
||||
"def validate_input(email: str) -> None:\n",
|
||||
" \"\"\"\n",
|
||||
" Validate input type and emptiness.\n",
|
||||
"\n",
|
||||
" Args:\n",
|
||||
" email (str): The email address to validate.\n",
|
||||
"\n",
|
||||
" Raises:\n",
|
||||
" TypeError: If the input email is not a string.\n",
|
||||
" ValueError: If the input email is empty or exceeds the maximum allowed length.\n",
|
||||
" \"\"\"\n",
|
||||
"\n",
|
||||
" # Check if email is a string\n",
|
||||
" if not isinstance(email, str):\n",
|
||||
" raise TypeError(\"Input must be a string\")\n",
|
||||
"\n",
|
||||
" # Trim leading/trailing whitespace from the input email\n",
|
||||
" email = email.strip()\n",
|
||||
"\n",
|
||||
" # Check if email is empty after trimming or exceeds the maximum length\n",
|
||||
" if not email or len(email) > MAX_EMAIL_LENGTH:\n",
|
||||
" raise ValueError(f\"Email '{email}' cannot be empty and must not exceed {MAX_EMAIL_LENGTH} characters\")\n",
|
||||
"\n",
|
||||
"def validate_email_format(email: str) -> bool:\n",
|
||||
" \"\"\"\n",
|
||||
" Validate the format of an email address.\n",
|
||||
"\n",
|
||||
" An email address is considered valid if it matches the standard format of local-part@domain.\n",
|
||||
" The local-part may contain letters (a-z, A-Z), numbers (0-9), and special characters (. _ % + -).\n",
|
||||
" The domain must be at least two parts separated by a dot, with each part containing letters (a-z, A-Z), numbers (0-9), and hyphens (-).\n",
|
||||
"\n",
|
||||
" Note: This function does not check if the email address actually exists or if the domain is valid according to the official standard (RFC 5322).\n",
|
||||
" It implements a simplified version of the standard that supports common email address formats but may not cover all edge cases.\n",
|
||||
"\n",
|
||||
" Args:\n",
|
||||
" email (str): The email address to validate.\n",
|
||||
"\n",
|
||||
" Returns:\n",
|
||||
" bool: True if the email format is valid, False otherwise.\n",
|
||||
" \"\"\"\n",
|
||||
"\n",
|
||||
" # Check if the email contains non-ASCII characters\n",
|
||||
" if not email.isascii():\n",
|
||||
" logging.error(\"Email contains non-ASCII characters\")\n",
|
||||
" return False\n",
|
||||
"\n",
|
||||
" try:\n",
|
||||
" # Check if the email matches the pattern\n",
|
||||
" if re.match(EMAIL_PATTERN, email):\n",
|
||||
" # Additional check for internationalized domain names (IDNs)\n",
|
||||
" domain = email.split('@')[1]\n",
|
||||
" if IDN_PATTERN.match(domain):\n",
|
||||
" logging.warning(\"Internationalized domain name detected\")\n",
|
||||
" return True\n",
|
||||
" else:\n",
|
||||
" return False\n",
|
||||
" except re.error as e:\n",
|
||||
" logging.error(f\"Error occurred during regular expression matching: {e}\")\n",
|
||||
" raise\n",
|
||||
"\n",
|
||||
"def validate_email(email: str) -> bool:\n",
|
||||
" \"\"\"\n",
|
||||
" Validate an email address.\n",
|
||||
"\n",
|
||||
" Args:\n",
|
||||
" email (str): The email address to validate.\n",
|
||||
"\n",
|
||||
" Returns:\n",
|
||||
" bool: True if the email is valid, False otherwise.\n",
|
||||
"\n",
|
||||
" Raises:\n",
|
||||
" TypeError: If the input email is not a string.\n",
|
||||
" ValueError: If the input email is empty or exceeds the maximum allowed length.\n",
|
||||
" \"\"\"\n",
|
||||
"\n",
|
||||
" validate_input(email)\n",
|
||||
" return validate_email_format(email)\n",
|
||||
"\n",
|
||||
"# Example usage and edge case testing\n",
|
||||
"if __name__ == \"__main__\":\n",
|
||||
" emails = [\n",
|
||||
" \"test@example.com\",\n",
|
||||
" \"invalid_email\",\n",
|
||||
" \"test@ example.com\",\n",
|
||||
" \"test@example\",\n",
|
||||
" 123, \n",
|
||||
" \"test@.com\",\n",
|
||||
" \" test@example.com\",\n",
|
||||
" \"test.example.com\",\n",
|
||||
" None,\n",
|
||||
" \"\",\n",
|
||||
" \"verylongdomainname123456789012345678901234567890@example.com\",\n",
|
||||
" \"special.chars(email)-test@example.co.uk\",\n",
|
||||
" \"test@example.co.uk..uk\"\n",
|
||||
" ]\n",
|
||||
"\n",
|
||||
" for email in emails:\n",
|
||||
" print(f\"Email: {email}\")\n",
|
||||
" try:\n",
|
||||
" is_valid = validate_email_address(email)\n",
|
||||
" print(f\"Is Valid: {is_valid}\")\n",
|
||||
" print(f\"Email: {email}, Valid: {validate_email(email)}\")\n",
|
||||
" except (TypeError, ValueError) as e:\n",
|
||||
" print(f\"Error: {e}\")\n",
|
||||
" print(\"-\" * 50)\n",
|
||||
"```\n",
|
||||
"\n",
|
||||
"In summary, while the original code provides a good basic structure for validating email addresses, a few adjustments can enhance its flexibility and robustness. These changes primarily focus on improving exception handling, avoiding unnecessary overhead, and adhering to best practices in Python coding standards.\n",
|
||||
"\n",
|
||||
"LGTM with the suggested modifications.\n"
|
||||
" if email is None:\n",
|
||||
" print(\"Email: None, Error: Input must be a string\")\n",
|
||||
" else:\n",
|
||||
" print(f\"Email: {email}, Error: {e}\")\n",
|
||||
"```\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
|
|
@ -670,14 +742,14 @@
|
|||
"from agent_framework import WorkflowBuilder, executor, WorkflowContext, WorkflowOutputEvent\n",
|
||||
"from typing_extensions import Never\n",
|
||||
"\n",
|
||||
"# Create code review agents\n",
|
||||
"# Create code review agents with better instructions\n",
|
||||
"code_developer = ChatAgent(\n",
|
||||
" name=\"Developer\",\n",
|
||||
" chat_client=chat_client,\n",
|
||||
" instructions=\"\"\"You are a developer. When you receive code review feedback:\n",
|
||||
" - Address ALL issues mentioned\n",
|
||||
" - Explain your changes\n",
|
||||
" - Present the improved code\n",
|
||||
" - Explain your changes briefly\n",
|
||||
" - Present ONLY the improved code (no extra commentary)\n",
|
||||
"\n",
|
||||
" If no feedback is given, present your initial implementation.\"\"\"\n",
|
||||
")\n",
|
||||
|
|
@ -685,36 +757,72 @@
|
|||
"code_reviewer = ChatAgent(\n",
|
||||
" name=\"CodeReviewer\",\n",
|
||||
" chat_client=chat_client,\n",
|
||||
" instructions=\"\"\"You are a senior code reviewer. Review code for:\n",
|
||||
" - Bugs and edge cases\n",
|
||||
" - Performance issues\n",
|
||||
" - Security vulnerabilities\n",
|
||||
" - Best practices\n",
|
||||
" instructions=\"\"\"You are a senior code reviewer. Review code for bugs, performance, security, and best practices.\n",
|
||||
"\n",
|
||||
" If the code looks good, say 'LGTM' (Looks Good To Me).\n",
|
||||
" If issues found, provide specific feedback for improvement.\"\"\"\n",
|
||||
" CRITICAL: Your response MUST start with one of these:\n",
|
||||
"\n",
|
||||
" If code is production-ready:\n",
|
||||
" \"APPROVED: [brief reason why it's good]\"\n",
|
||||
"\n",
|
||||
" If code needs changes:\n",
|
||||
" \"NEEDS REVISION: [list specific issues to fix]\"\n",
|
||||
"\n",
|
||||
" DO NOT provide fixed code examples.\n",
|
||||
" DO NOT say LGTM or APPROVED unless the code is truly ready.\n",
|
||||
" Be constructive but strict.\"\"\"\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"print(\"✅ Code review team created\")\n",
|
||||
"print(\"✅ Code review team created with strict instructions\")\n",
|
||||
"\n",
|
||||
"# Track iterations\n",
|
||||
"review_state = {\"iteration\": 0, \"max_iterations\": 4}\n",
|
||||
"\n",
|
||||
"# Define custom executors for workflow\n",
|
||||
"@executor(id=\"developer\")\n",
|
||||
"async def developer_executor(task: str, ctx: WorkflowContext[str]) -> None:\n",
|
||||
" \"\"\"Developer creates or improves code based on input.\"\"\"\n",
|
||||
" review_state[\"iteration\"] += 1\n",
|
||||
" print(f\"\\n [Developer - Iteration {review_state['iteration']}]\")\n",
|
||||
"\n",
|
||||
" result = await code_developer.run(task)\n",
|
||||
" print(f\" Code submitted for review (preview): {result.text[:80]}...\")\n",
|
||||
" await ctx.send_message(result.text)\n",
|
||||
"\n",
|
||||
"@executor(id=\"reviewer\")\n",
|
||||
"async def reviewer_executor(code: str, ctx: WorkflowContext[str, str]) -> None:\n",
|
||||
" \"\"\"Reviewer checks code and either approves or requests changes.\"\"\"\n",
|
||||
" result = await code_reviewer.run(f\"Review this code:\\n{code}\")\n",
|
||||
" print(f\"\\n [Reviewer - Iteration {review_state['iteration']}]\")\n",
|
||||
"\n",
|
||||
" # Check if approved\n",
|
||||
" if \"LGTM\" in result.text or \"looks good\" in result.text.lower():\n",
|
||||
" await ctx.yield_output(f\"✅ APPROVED\\n\\nCode:\\n{code}\\n\\nReview:\\n{result.text}\")\n",
|
||||
" result = await code_reviewer.run(f\"Review this code:\\n\\n{code}\")\n",
|
||||
"\n",
|
||||
" # Smart approval detection - check the START of the response\n",
|
||||
" response_start = result.text[:100].upper() # First 100 chars only\n",
|
||||
" is_approved = response_start.startswith(\"APPROVED\")\n",
|
||||
" needs_revision = \"NEEDS REVISION\" in response_start\n",
|
||||
"\n",
|
||||
" print(f\" Decision: {'✅ APPROVED' if is_approved else '❌ NEEDS REVISION' if needs_revision else '⚠️ UNCLEAR'}\")\n",
|
||||
"\n",
|
||||
" if is_approved:\n",
|
||||
" # Code approved! Output final result\n",
|
||||
" await ctx.yield_output(\n",
|
||||
" f\"✅ APPROVED after {review_state['iteration']} iteration(s)\\n\\n\"\n",
|
||||
" f\"📝 Review Comments:\\n{result.text}\\n\\n\"\n",
|
||||
" f\"💻 Final Code:\\n{code}\"\n",
|
||||
" )\n",
|
||||
" elif review_state[\"iteration\"] >= review_state[\"max_iterations\"]:\n",
|
||||
" # Hit max iterations - force stop\n",
|
||||
" await ctx.yield_output(\n",
|
||||
" f\"⚠️ MAX ITERATIONS REACHED ({review_state['max_iterations']})\\n\\n\"\n",
|
||||
" f\"📝 Last Review:\\n{result.text}\\n\\n\"\n",
|
||||
" f\"💻 Last Code:\\n{code}\"\n",
|
||||
" )\n",
|
||||
" else:\n",
|
||||
" # Send feedback back to developer for revision\n",
|
||||
" await ctx.send_message(f\"Feedback: {result.text}\\n\\nOriginal code:\\n{code}\", target_id=\"developer\")\n",
|
||||
" print(f\" Sending feedback to developer...\")\n",
|
||||
" await ctx.send_message(\n",
|
||||
" f\"FEEDBACK FROM REVIEWER:\\n{result.text}\\n\\nPrevious code:\\n{code}\",\n",
|
||||
" target_id=\"developer\"\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
"# Build workflow: developer → reviewer (with feedback loop)\n",
|
||||
"workflow = (\n",
|
||||
|
|
@ -725,27 +833,29 @@
|
|||
" .build()\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"# task = \"Implement a Python function to check if a string is a palindrome.\"\n",
|
||||
"# Use a task that's more likely to need multiple iterations\n",
|
||||
"task = \"\"\"Implement a Python function to validate email addresses with these requirements:\n",
|
||||
"- Must have @ symbol\n",
|
||||
"- Must have domain with at least one dot\n",
|
||||
"- No spaces allowed\n",
|
||||
"- Handle edge cases\n",
|
||||
"- Include error messages\n",
|
||||
"Make it production-ready with proper error handling.\"\"\"\n",
|
||||
"- Include basic error handling\n",
|
||||
"Keep it simple but correct.\"\"\"\n",
|
||||
"\n",
|
||||
"print(\"\\n\" + \"=\"*60)\n",
|
||||
"print(\"Code Review Workflow (with iteration tracking):\")\n",
|
||||
"print(\"=\"*60)\n",
|
||||
"\n",
|
||||
"print(\"\\n\" + \"=\"*50)\n",
|
||||
"print(\"Code Review Workflow:\")\n",
|
||||
"print(\"=\"*50)\n",
|
||||
"# Reset state\n",
|
||||
"review_state[\"iteration\"] = 0\n",
|
||||
"\n",
|
||||
"# Run workflow with streaming\n",
|
||||
"iteration = 1\n",
|
||||
"async for event in workflow.run_stream(task):\n",
|
||||
" if isinstance(event, WorkflowOutputEvent):\n",
|
||||
" print(f\"\\n[Iteration {iteration} - Final Result]:\")\n",
|
||||
" print(event.data)\n",
|
||||
" iteration += 1"
|
||||
" print(\"\\n\" + \"=\"*60)\n",
|
||||
" print(\"FINAL RESULT:\")\n",
|
||||
" print(\"=\"*60)\n",
|
||||
" print(event.data)"
|
||||
]
|
||||
},
|
||||
{
|
||||
|
|
@ -764,7 +874,7 @@
|
|||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 25,
|
||||
"execution_count": 7,
|
||||
"metadata": {
|
||||
"scrolled": true
|
||||
},
|
||||
|
|
@ -784,48 +894,50 @@
|
|||
"--------------------------------------------------\n",
|
||||
"\n",
|
||||
"[Analysis 2]:\n",
|
||||
"**Proposal Evaluation: Deploying a Customer Service Chatbot**\n",
|
||||
"**Proposal Evaluation: Customer Service Chatbot Deployment**\n",
|
||||
"\n",
|
||||
"**Executive Summary:**\n",
|
||||
"The proposal to deploy a customer service chatbot aims to enhance customer experience, reduce support queries, and optimize resource allocation. This evaluation assesses the technical feasibility and implementation complexity of the proposed solution.\n",
|
||||
"**Introduction:**\n",
|
||||
"The proposed project aims to deploy a customer service chatbot to enhance the user experience, reduce support queries, and increase efficiency. This evaluation assesses the technical feasibility and implementation complexity of the proposal.\n",
|
||||
"\n",
|
||||
"**Technical Feasibility:**\n",
|
||||
"\n",
|
||||
"1. **Natural Language Processing (NLP) Capabilities:** The chatbot's ability to understand and respond to customer inquiries accurately is crucial. Modern NLP libraries (e.g., NLTK, spaCy) and machine learning frameworks (e.g., TensorFlow, PyTorch) can support this requirement.\n",
|
||||
"2. **Integration with Existing Systems:** Seamless integration with the CRM, helpdesk software, and other relevant systems is necessary. APIs and webhooks can facilitate data exchange and synchronization.\n",
|
||||
"3. **Security and Compliance:** The chatbot must ensure customer data protection and adhere to regulations (e.g., GDPR, HIPAA). Implementing encrypti...\n",
|
||||
"1. **Platform Compatibility:** The chatbot can be integrated with various platforms, including websites, mobile apps, and social media messaging services.\n",
|
||||
"2. **Natural Language Processing (NLP):** The proposed NLP engine is capable of understanding and processing human language, allowing for effective conversation flow.\n",
|
||||
"3. **Integration with Existing Systems:** The chatbot can be integrated with the company's CRM system to access customer data and provide personalized support.\n",
|
||||
"4. **Security:** The proposed solution includes robust security measures, such as encryption and secure authentication protocols, to ensure data protection.\n",
|
||||
"\n",
|
||||
"**Technic...\n",
|
||||
"--------------------------------------------------\n",
|
||||
"\n",
|
||||
"[Analysis 3]:\n",
|
||||
"**Evaluation of Customer Service Chatbot Proposal**\n",
|
||||
"**Proposal Evaluation: Deploying a Customer Service Chatbot**\n",
|
||||
"\n",
|
||||
"**Introduction:**\n",
|
||||
"The proposal to deploy a customer service chatbot aims to improve customer experience, reduce support costs, and increase efficiency in handling customer inquiries. This evaluation assesses the business value, ROI, and market impact of implementing a customer service chatbot.\n",
|
||||
"**Introduction**\n",
|
||||
"\n",
|
||||
"**Benefits:**\n",
|
||||
"The proposal aims to deploy a customer service chatbot to enhance customer experience, reduce support queries, and improve operational efficiency. This evaluation will assess the business value, ROI, and market impact of the proposed solution.\n",
|
||||
"\n",
|
||||
"1. **Improved Customer Experience:** A chatbot can provide 24/7 support, quick responses to common queries, and personalized experiences, leading to increased customer satisfaction.\n",
|
||||
"2. **Cost Savings:** Automating routine inquiries can reduce the workload of human customer support agents, resulting in cost savings and allowing them to focus on complex issues.\n",
|
||||
"3. **Increased Efficiency:** Chatbots can handle multiple conversations simultaneously, reducing wait times and improving response rates.\n",
|
||||
"4. **Data Collection and Analysis:** Chatbots can collect valuable data on customer interactions, providing insights for business improv...\n",
|
||||
"**Business Case**\n",
|
||||
"\n",
|
||||
"1. **Problem Statement**: The current customer support process is manual, time-consuming, and leads to long wait times, resulting in decreased customer satisfaction.\n",
|
||||
"2. **Solution Overview**: Implement a conversational AI-powered chatbot that provides 24/7 support, automates routine inquiries, and directs complex issues to human agents.\n",
|
||||
"3. **Key Benefits**:\n",
|
||||
"\t* Improved response times (reduced average handle time by 30%)\n",
|
||||
"\t* Enhanced customer experience (increased satisfaction ratings by 20%)\n",
|
||||
"\t* Reduced support queries (decreased ticket volume by 25%)\n",
|
||||
"\t* Cost savings (lowered labor costs by 15%)\n",
|
||||
"4. **Target Audience**: Existing customers, new custom...\n",
|
||||
"--------------------------------------------------\n",
|
||||
"\n",
|
||||
"[Analysis 4]:\n",
|
||||
"**Evaluation of Customer Service Chatbot Proposal**\n",
|
||||
"**Proposal Evaluation: Customer Service Chatbot Deployment**\n",
|
||||
"\n",
|
||||
"**Introduction:**\n",
|
||||
"The proposal to deploy a customer service chatbot aims to enhance customer experience, reduce support queries, and improve response times. This evaluation assesses the feasibility, security implications, risks, and compliance of implementing a chatbot solution.\n",
|
||||
"\n",
|
||||
"**Benefits:**\n",
|
||||
"\n",
|
||||
"1. **24/7 Support**: A chatbot can provide round-the-clock support, improving customer satisfaction and reducing the workload on human customer support agents.\n",
|
||||
"2. **Faster Response Times**: Chatbots can respond to queries instantly, ensuring that customers receive timely assistance.\n",
|
||||
"3. **Cost Savings**: Automating routine inquiries can lead to significant cost savings by reducing the need for human customer support agents.\n",
|
||||
"4. **Personalization**: Chatbots can be programmed to offer personalized recommendations and solutions based on customer interactions.\n",
|
||||
"**Overview**\n",
|
||||
"The proposal to deploy a customer service chatbot aims to enhance customer experience, improve response times, and reduce support costs. The chatbot will utilize natural language processing (NLP) and machine learning algorithms to provide automated support for frequently asked questions, routing complex issues to human representatives.\n",
|
||||
"\n",
|
||||
"**Security Implications:**\n",
|
||||
"\n",
|
||||
"1. **Data Security**: The chatbot will handle sensitive cust...\n",
|
||||
"1. **Data Protection**: The chatbot will collect and process sensitive customer data, including personal identifiable information (PII), payment details, and conversation history. Ensure that the chatbot's data storage and transmission protocols comply with relevant regulations, such as GDPR, HIPAA, or PCI-DSS.\n",
|
||||
"2. **Authentication and Authorization**: Implement robust authentication and authorization mechanisms to prevent unauthorized access to customer data and ensure that only authorized personnel can modify chatbot configurations or access sensitive...\n",
|
||||
"--------------------------------------------------\n",
|
||||
"\n",
|
||||
"==================================================\n",
|
||||
|
|
@ -886,13 +998,6 @@
|
|||
"print(\"All agents completed in parallel\")\n",
|
||||
"print(\"=\"*50)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": []
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue