Build a Generative AI app with Claude 3 - The  powerful LLM

Build a Generative AI app with Claude 3 - The powerful LLM


Full tutorial - https://www.youtube.com/watch?v=ximj9QWle-g

In this tutorial, I will guide you through the process of building an Emotional Assistant application using Streamlit for the user interface and Anthropic's Claude 3 language model for mood analysis and recommendations. Our goal is to create an app that allows users to input their thoughts or feelings for the day, analyze their overall mood or sentiment, categorize their mood, and receive personalized recommendations to help them feel better.

What is Claude 3?

Claude 3 is a large language model developed by Anthropic with advanced math, reasoning, language understanding, and input reading capabilities. The Claude 3 model aims to reduce the workload of its users with its output generation speed, three different sizes, automation of repetitive tasks, and large-size context windows. Claude 3 model is the ideal solution for completing large-scale tasks thanks to its context window from 200K to 1 million tokens.

  • Claude 3 is a large language model developed and announced by Anthropic and comes in three different sizes.
  • Claude 3 comes in three sizes, Haiku for basic tasks, Sonnet for complex tasks, Opus for the overly complex tasks.
  • To access the Claude 3 Sonnet model, simply sign up to Anthropic, for the Claude 3 Opus model you need an Anthropic Pro subscription, or try Claude 3 out on TextCortex for free with rate limits.
  • GPT-4 is the most popular large language model developed and published by OpenAI with advanced features.
  • Claude 3 Opus model has higher performance than GPT-4 in tasks such as reasoning, language understanding, coding, and writing.
  • The Claude 3 Opus model has lower performance than the GPT-4 Turbo model.
  • The Claude 3 Opus model can follow prompts better than GPT-4

App Overview

The workflow of the Emotional Assistant app is as follows:

  1. The user enters their Anthropic API key.
  2. The user inputs their thoughts or feelings for the day.
  3. The app sends the user's input to Anthropic's Claude model, which analyzes the overall mood or sentiment expressed.
  4. The app categorizes the mood based on keywords or patterns in the mood analysis.
  5. For non-neutral moods, the app sends the mood analysis and category to Claude, asking for recommendations to help the user feel better.
  6. The app displays the mood analysis, mood category, and recommendations (if applicable) to the user.

Setting Up the Environment

Before diving into the code, ensure you have the necessary libraries installed. If not, you can install them using pip:

import streamlit as st
import anthropic

def main():
    st.title("Your Emotional Assistant")

    # Get the API key from the user
    api_key = st.text_input("Enter your Anthropic API Key:", type="password")

    if api_key:
        # Create the Anthropi client
        client = anthropic.Anthropic(api_key=api_key)

        # Get user input
        user_input = st.text_area("Enter your thoughts or feelings for the day:")

        if st.button("Analyze Mood"):
            message = client.messages.create(
                model="claude-3-sonnet-20240229",
                max_tokens=689,
                temperature=0,
                messages=[
                    {"role": "user", "content": f"Based on the following text, can you analyze the overall mood or sentiment expressed by the person?\n\n{user_input}"}
                ]
            )

           
            mood_analysis = ''.join(block.text for block in message.content)  # Adjusted line

            # Display the mood analysis using Markdown for formatting
            st.markdown("**Mood Analysis:**")
            st.write(mood_analysis)

            # Define mood categories
            mood_categories = ["Happy", "Sad", "Angry", "Anxious", "Neutral"]

            # Categorize the mood based on keywords or patterns
            mood_category = "Neutral"
            for category in mood_categories:
                if category.lower() in mood_analysis.lower():
                    mood_category = category
                    break

            # Display the mood category with emphasis
            mood_display = f"**Mood Category:** {mood_category}"
            if mood_category == "Happy":
                st.success(mood_display)
            elif mood_category == "Sad" or mood_category == "Angry":
                st.error(mood_display)
            elif mood_category == "Anxious":
                st.warning(mood_display)
            else:  # Neutral or any other category
                st.info(mood_display)

            # Provide recommendations
            if mood_category != "Neutral":
                message = client.messages.create(
                    model="claude-3-sonnet-20240229",
                    max_tokens=689,
                    temperature=0,
                    messages=[
                        {"role": "user", "content": f"Based on the mood analysis '{mood_analysis}' and the mood category '{mood_category}', can you provide some recommendations or suggestions to help the person feel better?"}
                    ]
                )
                recommendations = ''.join(block.text for block in message.content)  # Adjusted line to concatenate the text

                st.write("**Recommendations:**")
                st.write(recommendations)
    else:
        st.warning("Please enter your Anthropic API Key to use the app.")

if __name__ == "__main__":
    main()        

pip install streamlit anthropic

We'll import the required modules from Streamlit and Anthropic.

The Main Function: main()

The main() function is the entry point of our app. Let's break it down step by step:

Set the App Title

st.title sets the title of the Streamlit app.

Get the Anthropic API Key

A text input field is created for the user to enter their Anthropic API key. The type="password" parameter ensures that the input is masked for security purposes.

Create the Anthropic Client

If the user has entered an API key, an instance of the Anthropic client is created using the provided key.

Get User Input

A text area is created for the user to input their thoughts or feelings for the day.

Analyze Mood

If the user clicks the "Analyze Mood" button, the app sends the user's input to Anthropic's Claude model (claude-3-sonnet-20240229) with the instruction to analyze the overall mood or sentiment expressed. The model's response is stored in the mood_analysis variable.

Display the Mood Analysis

The mood analysis is displayed to the user using Markdown formatting for emphasis.

Categorize the Mood

The app defines a list of mood categories and initializes the mood_category variable to "Neutral". It then checks if any of the mood category keywords appear in the mood analysis (case-insensitive). If a match is found, the mood_category is updated accordingly.

Display the Mood Category

The app displays the mood category with emphasis and color-coded formatting based on the category (e.g., green for "Happy", red for "Sad" or "Angry", yellow for "Anxious", and blue for "Neutral" or any other category).

Provide Recommendations

If the mood category is not "Neutral", the app sends the mood analysis and category to Claude 3 AI model, asking for recommendations or suggestions to help the user feel better. The model's response is stored in the recommendations variable and displayed to the user.

Display a Warning if No API Key is Provided

If the user hasn't entered an Anthropic API key, a warning message is displayed, prompting them to do so.

Run the App

the main() function is executed when the script is run, allowing the Streamlit app to start.

Conclusion

In this tutorial, I've walked through the steps to build an Emotional Assistant app using Streamlit for the user interface and Anthropic's Claude 3 language model for mood analysis and recommendations. The app allows users to input their thoughts or feelings, analyze their overall mood, categorize them, and provide personalized recommendations to help them feel better.

Sri Laxmi

AI Product Manager | Generative AI | AI Products Builders Host| M.Sc at TUM

6 个月

要查看或添加评论,请登录

社区洞察

其他会员也浏览了