Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
197 lines (136 loc) · 6.26 KB
/
Copy pathapp.py
File metadata and controls
197 lines (136 loc) · 6.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# Case Study 1 - Python AI Coder
# Building a Personal Python Programming Assistant using Streamlit and Groq API
# Import operating system utilities
import os
# Import Streamlit to build the web application interface
import streamlit as st
# Import the Groq client to interact with the language model API
from groq import Groq
# Configure Streamlit page settings
st.set_page_config(
page_title="Python AI Coder",
page_icon="🤖",
layout="wide",
initial_sidebar_state="expanded"
)
# Define the system prompt and assistant behaviour
CUSTOM_PROMPT = """
You are "Python AI Coder", an AI assistant specialised in Python programming.
Your mission is to help beginner developers understand programming concepts through clear explanations, practical examples, and official documentation references.
OPERATING RULES:
1. Programming Focus
Only answer questions related to programming, algorithms, data structures, libraries, frameworks, software engineering, and Python development.
If the user asks about unrelated subjects, politely explain that your purpose is to assist with programming topics only.
2. Response Structure
Always organise your answers using the following format:
- Clear Explanation
Provide a concise conceptual explanation of the topic.
- Code Example
Provide one or more complete Python examples using correct syntax and meaningful comments.
- Code Breakdown
Explain what each important section of the code does and why it is used.
- Documentation Reference
Finish with a section titled:
📚 Official Documentation
Include a relevant link to Python documentation or the official documentation of the library being discussed.
3. Communication Style
Use clear, professional, beginner-friendly language.
Avoid unnecessary jargon.
Focus on teaching and practical understanding.
4. Language Behaviour
Respond in the same language used by the user whenever possible.
"""
# Build the application sidebar
with st.sidebar:
# Sidebar title
st.title("🤖 Python AI Coder")
# Brief description of the assistant
st.markdown("An AI powered assistant focused on helping beginners learn Python programming.")
# Groq API key input field
groq_api_key = st.text_input(
"Enter your Groq API Key",
type="password",
help="Get your API key from https://console.groq.com/keys"
)
# Additional project information
st.markdown("---")
st.markdown("Built to help answer Python programming questions. AI may generate incorrect responses. Always validate the information provided.")
st.markdown("---")
st.markdown("This project was originally developed as part of a Data Science Academy learning programme. Learn more below:")
# Link to Data Science Academy
st.markdown("🔗 [Data Science Academy](https://www.datascienceacademy.com.br)")
# Support contact button
st.link_button("✉️ Contact Data Science Academy Support", "mailto:suporte@datascienceacademy.com.br")
# Main application title
st.title("Python AI Coder")
# Secondary title
st.title("Personal Python Programming Assistant 🐍")
# Introductory description
st.caption("Ask your Python question and receive code examples, explanations, and official documentation references.")
# Initialise chat history if it does not exist
if "messages" not in st.session_state:
st.session_state.messages = []
# Display previous conversation messages
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# Initialise Groq client
client = None
# Check whether an API key has been provided
if groq_api_key:
try:
# Create Groq client instance
client = Groq(api_key = groq_api_key)
except Exception as e:
# Display initialisation error
st.sidebar.error(f"Error initialising Groq client: {e}")
st.stop()
# Warn the user if messages exist but no API key has been provided
elif st.session_state.messages:
st.warning("Please enter your Groq API key in the sidebar to continue.")
# Capture user input from the chat interface
if prompt := st.chat_input("What would you like to know about Python?"):
# Prevent execution if no valid Groq client is available
if not client:
st.warning("Please enter your Groq API key in the sidebar to get started.")
st.stop()
# Store user message in session history
st.session_state.messages.append({"role": "user", "content": prompt})
# Display user message
with st.chat_message("user"):
st.markdown(prompt)
# Prepare conversation history for API request
messages_for_api = [{"role": "system", "content": CUSTOM_PROMPT}]
for msg in st.session_state.messages:
messages_for_api.append(msg)
# Generate assistant response
with st.chat_message("assistant"):
with st.spinner("Analysing your question..."):
try:
# Request completion from the Groq API
chat_completion = client.chat.completions.create(
messages = messages_for_api,
model = "openai/gpt-oss-20b",
temperature = 0.7,
max_tokens = 2048,
)
# Extract generated response
PcFaria_ai_resposta = chat_completion.choices[0].message.content
# Display assistant response
st.markdown(PcFaria_ai_resposta)
# Save assistant response to session history
st.session_state.messages.append({"role": "assistant", "content": PcFaria_ai_resposta})
# Display API communication errors
except Exception as e:
st.error(f"An error occurred while communicating with the Groq API: {e}")
st.markdown(
"""
<div style="text-align: center; color: gray;">
<hr>
<p>Python AI Coder - Originally developed as part of the Data Science Academy Python Fundamentals Programme and subsequently enhanced with additional features for learning and portfolio purposes.</p>
</div>
""",
unsafe_allow_html=True
)
# End of application
# Developed and enhanced by Paulo Faria for learning and portfolio purposes