organicoder commited on
Commit
ba4a7ed
·
verified ·
1 Parent(s): 2a1bdac

Upload 4 files

Browse files
Files changed (4) hide show
  1. README.md +111 -13
  2. app.py +117 -0
  3. config.py +32 -0
  4. requirements.txt +3 -0
README.md CHANGED
@@ -1,13 +1,111 @@
1
- ---
2
- title: Chatbot Sverige
3
- emoji: 🐢
4
- colorFrom: blue
5
- colorTo: red
6
- sdk: gradio
7
- sdk_version: 5.36.2
8
- app_file: app.py
9
- pinned: false
10
- license: mit
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AI Chatbot
2
+
3
+ A simple and elegant AI chatbot built with Gradio and OpenAI's GPT models, designed for easy deployment on Hugging Face Spaces.
4
+
5
+ ## Features
6
+
7
+ - 🤖 Powered by OpenAI's GPT-3.5-turbo
8
+ - 💬 Real-time chat interface
9
+ - 🎨 Beautiful and responsive UI
10
+ - 📱 Mobile-friendly design
11
+ - 🔄 Conversation history
12
+ - 🧹 Clear chat functionality
13
+
14
+ ## Local Development
15
+
16
+ ### Prerequisites
17
+
18
+ - Python 3.8 or higher
19
+ - OpenAI API key
20
+
21
+ ### Installation
22
+
23
+ 1. Clone this repository:
24
+ ```bash
25
+ git clone <your-repo-url>
26
+ cd chatbotsverige
27
+ ```
28
+
29
+ 2. Install dependencies:
30
+ ```bash
31
+ pip install -r requirements.txt
32
+ ```
33
+
34
+ 3. Set up your OpenAI API key:
35
+ ```bash
36
+ export OPENAI_API_KEY="your-api-key-here"
37
+ ```
38
+
39
+ 4. Run the application:
40
+ ```bash
41
+ python app.py
42
+ ```
43
+
44
+ The chatbot will be available at `http://localhost:7860`
45
+
46
+ ## Deployment on Hugging Face Spaces
47
+
48
+ ### Method 1: Using the Hugging Face Web Interface
49
+
50
+ 1. Go to [Hugging Face Spaces](https://huggingface.co/spaces)
51
+ 2. Click "Create new Space"
52
+ 3. Choose "Gradio" as the SDK
53
+ 4. Upload your files or connect your GitHub repository
54
+ 5. Add your `OPENAI_API_KEY` as a secret in the Space settings
55
+
56
+ ### Method 2: Using Git
57
+
58
+ 1. Create a new Space on Hugging Face
59
+ 2. Clone the Space repository:
60
+ ```bash
61
+ git clone https://huggingface.co/spaces/YOUR_USERNAME/YOUR_SPACE_NAME
62
+ ```
63
+
64
+ 3. Copy your files to the Space repository:
65
+ ```bash
66
+ cp app.py requirements.txt README.md /path/to/space/repo/
67
+ ```
68
+
69
+ 4. Push to Hugging Face:
70
+ ```bash
71
+ cd /path/to/space/repo/
72
+ git add .
73
+ git commit -m "Initial commit"
74
+ git push
75
+ ```
76
+
77
+ ### Environment Variables
78
+
79
+ Make sure to set the following environment variable in your Hugging Face Space:
80
+
81
+ - `OPENAI_API_KEY`: Your OpenAI API key
82
+
83
+ ## Configuration
84
+
85
+ You can customize the chatbot by modifying the following parameters in `app.py`:
86
+
87
+ - **Model**: Change `gpt-3.5-turbo` to other OpenAI models
88
+ - **Max tokens**: Adjust `max_tokens` for response length
89
+ - **Temperature**: Modify `temperature` for response creativity (0.0-1.0)
90
+ - **System prompt**: Customize the system message for different personalities
91
+
92
+ ## Usage
93
+
94
+ 1. Type your message in the text input
95
+ 2. Press Enter or click the send button
96
+ 3. The AI will respond based on the conversation context
97
+ 4. Use the "Clear Chat" button to start a new conversation
98
+
99
+ ## Security Notes
100
+
101
+ - Never commit your API keys to version control
102
+ - Use environment variables for sensitive information
103
+ - Consider implementing rate limiting for production use
104
+
105
+ ## License
106
+
107
+ This project is open source and available under the MIT License.
108
+
109
+ ## Contributing
110
+
111
+ Feel free to submit issues and enhancement requests!
app.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import openai
3
+ import os
4
+ from typing import List, Tuple
5
+ from config import Config
6
+
7
+ # Validate configuration
8
+ try:
9
+ Config.validate()
10
+ except ValueError as e:
11
+ print(f"Configuration Error: {e}")
12
+ exit(1)
13
+
14
+ # Initialize OpenAI client
15
+ client = openai.OpenAI(
16
+ api_key=Config.OPENAI_API_KEY
17
+ )
18
+
19
+ def chat_with_bot(message: str, history: List[Tuple[str, str]]) -> Tuple[str, List[Tuple[str, str]]]:
20
+ """
21
+ Chat function that handles conversation with OpenAI API
22
+ """
23
+ if not message.strip():
24
+ return "", history
25
+
26
+ # Prepare conversation history for OpenAI
27
+ messages = [
28
+ {"role": "system", "content": Config.SYSTEM_PROMPT}
29
+ ]
30
+
31
+ # Add conversation history
32
+ for human, assistant in history:
33
+ messages.append({"role": "user", "content": human})
34
+ messages.append({"role": "assistant", "content": assistant})
35
+
36
+ # Add current message
37
+ messages.append({"role": "user", "content": message})
38
+
39
+ try:
40
+ # Get response from OpenAI
41
+ response = client.chat.completions.create(
42
+ model=Config.OPENAI_MODEL,
43
+ messages=messages,
44
+ max_tokens=Config.MAX_TOKENS,
45
+ temperature=Config.TEMPERATURE
46
+ )
47
+
48
+ assistant_response = response.choices[0].message.content
49
+
50
+ # Update history
51
+ history.append((message, assistant_response))
52
+
53
+ return "", history
54
+
55
+ except Exception as e:
56
+ error_message = f"Sorry, I encountered an error: {str(e)}"
57
+ history.append((message, error_message))
58
+ return "", history
59
+
60
+ def clear_chat():
61
+ """Clear the chat history"""
62
+ return []
63
+
64
+ # Create Gradio interface
65
+ with gr.Blocks(
66
+ title=Config.GRADIO_TITLE,
67
+ theme=gr.themes.Soft(),
68
+ css="""
69
+ .gradio-container {
70
+ max-width: 800px;
71
+ margin: auto;
72
+ }
73
+ """
74
+ ) as demo:
75
+ gr.Markdown(
76
+ """
77
+ # 🤖 AI Chatbot
78
+
79
+ Welcome! I'm your AI assistant. Feel free to ask me anything!
80
+
81
+ ---
82
+ """
83
+ )
84
+
85
+ # Chat interface
86
+ chatbot = gr.Chatbot(
87
+ height=Config.GRADIO_HEIGHT,
88
+ show_label=False,
89
+ container=True,
90
+ bubble_full_width=False
91
+ )
92
+
93
+ # Message input
94
+ msg = gr.Textbox(
95
+ placeholder="Type your message here...",
96
+ show_label=False,
97
+ container=False
98
+ )
99
+
100
+ # Clear button
101
+ clear = gr.Button("Clear Chat", variant="secondary")
102
+
103
+ # Set up event handlers
104
+ msg.submit(
105
+ chat_with_bot,
106
+ inputs=[msg, chatbot],
107
+ outputs=[msg, chatbot]
108
+ )
109
+
110
+ clear.click(
111
+ clear_chat,
112
+ outputs=chatbot
113
+ )
114
+
115
+ # Launch the app
116
+ if __name__ == "__main__":
117
+ demo.launch()
config.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import Optional
3
+
4
+ class Config:
5
+ """Configuration class for the chatbot"""
6
+
7
+ # OpenAI Configuration
8
+ OPENAI_API_KEY: str = os.getenv("OPENAI_API_KEY", "")
9
+ OPENAI_MODEL: str = os.getenv("OPENAI_MODEL", "gpt-3.5-turbo")
10
+ MAX_TOKENS: int = int(os.getenv("MAX_TOKENS", "500"))
11
+ TEMPERATURE: float = float(os.getenv("TEMPERATURE", "0.7"))
12
+
13
+ # System prompt
14
+ SYSTEM_PROMPT: str = os.getenv(
15
+ "SYSTEM_PROMPT",
16
+ "You are a helpful and friendly AI assistant. Keep your responses concise and engaging."
17
+ )
18
+
19
+ # Gradio Configuration
20
+ GRADIO_THEME: str = "soft"
21
+ GRADIO_HEIGHT: int = 500
22
+ GRADIO_TITLE: str = "AI Chatbot"
23
+
24
+ @classmethod
25
+ def validate(cls) -> bool:
26
+ """Validate that required configuration is present"""
27
+ if not cls.OPENAI_API_KEY:
28
+ raise ValueError(
29
+ "OPENAI_API_KEY environment variable is required. "
30
+ "Please set it before running the application."
31
+ )
32
+ return True
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ gradio>=4.0.0
2
+ openai>=1.0.0
3
+ python-dotenv>=1.0.0