top of page

A Dynamic Sassy Chatbot with Streamlit and OpenAI

  • Writer: HSIYUN WEI
    HSIYUN WEI
  • Mar 16, 2024
  • 3 min read

Introduction

Welcome to an exciting journey through the development of a dynamic chatbot using Streamlit and OpenAI's powerful GPT models. This project not only challenges us to meld AI with a user-friendly interface but also allows us to explore the intricacies of API interactions, token management, and persona crafting. Designed for both enthusiasts and professionals, this guide will walk you through each step of creating your own chatbot capable of embodying various personas, managing conversation histories, and engaging users with coherent responses.

Projects Section

Crafting Conversational Interfaces: A Dynamic Chatbot Experience with Streamlit and OpenAI





Overview

This project showcases the development of a versatile chatbot interface, leveraging Streamlit for user interaction and OpenAI's API for generating dynamic, persona-based conversations. The goal was to create an accessible platform where users could interact with a chatbot capable of adopting various personas, thus offering a tailored chat experience. This not only demonstrates the power of large language models in understanding and generating human-like text but also highlights the importance of user interface design in making technology accessible to a broader audience.

Tools and Technologies

  • Programming Languages: Python

  • Frameworks and Libraries: Streamlit, OpenAI's GPT

  • APIs: OpenAI API

  • Other Technologies: Git for version control, GitHub for code repository

Approach and Methodology

The project was initiated by integrating the ConversationManager class to handle backend logic, including API interactions and conversation history management. Streamlit's framework facilitated the creation of a user-friendly interface, allowing users to adjust chat settings such as conversation temperature and persona. The development process involved:

  1. Setting up the chatbot environment and managing distinct personas.

  2. Implementing token management to optimize API usage.

  3. Designing a message interface for real-time user-chatbot interaction.

  4. Ensuring a coherent conversation flow by maintaining a history of interactions.


Code and Repository Link

Setting the Stage with Streamlit and OpenAI

First things first, let's set up our project environment:

  • OpenAI and Streamlit: Essential libraries for AI interaction and web app creation.

  • Environment Variables: Securely storing and accessing the OpenAI API key.

  • TikToken and JSON: For token counting and data management.

pythonCopy code

import openai import tiktoken import json from datetime import datetime import os import streamlit as st openai.api_key = os.getenv("OPENAI_API_KEY")

Crafting the ConversationManager

The ConversationManager is the brain behind our chatbot, responsible for API interactions, managing conversation history, and embodying different personas.

Initialization and Configuration

We begin by defining our class with essential attributes like API keys, base URL for API calls, and default settings for our chat model.

pythonCopy code

class ConversationManager: def init(self, api_key, base_url="https://api.openai.com/v1/chat/completions", ...): self.api_key = api_key self.base_url = base_url ...

Token Management

Handling token usage efficiently to stay within budget while maintaining a smooth conversation flow.

pythonCopy code

def count_tokens(self, text): encoding = tiktoken.encoding_for_model(self.default_model) tokens = encoding.encode(text) return len(tokens)

Dynamic Persona Setting

Adjusting the chatbot's personality on-the-fly, allowing for versatile user interactions.

pythonCopy code

def set_persona(self, persona): self.system_message = self.system_messages[persona]

Streamlit Interface for User Interaction

Creating an interactive web interface where users can engage with the chatbot.

pythonCopy code

# Streamlit app title st.title("Sassy Chatbot :face_with_rolling_eyes:") # Sidebar for user options st.sidebar.header("Options") ...

Bringing it All Together

Linking the ConversationManager with Streamlit widgets to provide a seamless chat experience.

pythonCopy code

# Initialize the ConversationManager object if 'chat_manager' not in st.session_state: st.session_state['chat_manager'] = ConversationManager(api_key) ...

III. The Conversation Flow

Detailing the chat flow from user input to the chatbot's response, including token budget management and persona adjustments.

User Input and Chatbot Response

Handling user messages and generating responses using OpenAI's GPT model.

pythonCopy code

user_input = st.chat_input("Write a message") if user_input: response = chat_manager.chat_completion(user_input, temperature=temperature, max_tokens=max_tokens_per_message)

Conversation History Management

Keeping track of the dialogue history to provide contextually aware interactions.

pythonCopy code

def save_conversation_history(self): with open(self.history_file, "w") as file: json.dump(self.conversation_history, file, indent=4)

IV. Conclusion

Through this project, you've seen how to intertwine the capabilities of OpenAI's language models with Streamlit's interactive elements to create a chatbot that's not only functional but also engaging. By managing token usage, crafting distinct personas, and maintaining a coherent conversation history, we've developed a tool that brings us closer to the future of human-AI interaction.




Skills

  • Technical Skills: Python programming, API integration, Natural Language Processing, Streamlit application development

  • Soft Skills: Problem-solving, project management, creativity in UI/UX design

  • Certifications: Certified Python Developer, Natural Language Processing Specialization

Comments


  • LinkedIn
bottom of page