Hello Guys,
I am new to programming. I have a basic question.
I have a file named basic_open_ai.py where I am defiining my class
from openai import OpenAI
from config import target_language, difficulty_level, learning_focus
from dotenv import load_dotenv
import os
load_dotenv()
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
if not OPENAI_API_KEY:
raise ValueError("OPENAI_API_KEY not found in environment variables")
client = OpenAI()
# model = 'mistralai/Mistral-7B-Instruct-v0.3'
model = 'gpt-4o-mini'
messages = []
class Conversation:
def __init__(self, target_language, difficulty_level, learning_focus):
self.target_language = target_language
self.difficulty_level = difficulty_level
self.learning_focus = learning_focus
self.client = OpenAI()
self.model = 'gpt-4o-mini'
self.messages = []
self.system_message = f """"You are a helpful AI assisstant whose job is to help the user to learn a new
language as per the selected {self.target_language}, {self.difficulty_level} and {self.learning_focus}.
Please handle specific types of queries:
1. How do you say a specific [word/phrase] in the {self.target_language}
2. Teach me a simple sentence in {tself.arget_language}.
3. What is the translation of [word/phrase] in {self.target_language}.
4. Help me understand Greetings in a {self.target_language}.
When providing translations in English, make sure to explain pronunciation tips when relevant.
Here is an example conversation:
Assistant: Hello, welcome to your personal learning companinion.
Which language you would like to learn?
User: I would like to learn French.
Assistant: Great! What is your current level of proficiency.
And then you will proceed with the conversation based on the user's proficiency.
"""
def chat(user_input, user_profile):
"""Generate a response to the user input using user profile.
Args:
user_input (str): The input from the user.
user_profile (UserProfile): The user profile containing the target language, difficulty level and learning focus.
Returns:
string containing the AI response.
"""
global messages
# Construct a user profile message dynamically
user_context = f"""User wants to learn: {self.target_language}.
Current level: {self.difficulty_level}.
Learning focus: {self.learning_focus}.
"""
# Ensure the system message is updated if needed
if self.messages[0]["role"] == "system":
self.messages[0]["content"] = self.system_message + "\n\n" + user_context
else:
messages.insert(0, {"role": "system", "content": system_message + "\n\n" + user_context})
#Add user messages to the conversation history
self.messages.append({"role": "user", "content": user_input})
#Get response from the model
completion = self.client.chat.completions.create(
model=self.model,
messages=self.messages,
temperature=0.2,
stream=True,
)
response =completion.choices[0].message.content
#Add AI response to the conversation history
self.messages.append({"role": "assistant", "content": response})
return response```
I have a config.py file where I have defined my pydantic class - User profile
from pydantic import BaseModel, Field
from typing import Literal
class UserProfile(BaseModel):
target_language: str
difficulty_level: str = Literal ["Beginner", "Intermediate", "Advanced"]
learning_focus: str = Literal ["Vocabulary", "Grammar", "Conversation"]
Then I have my streamlit app where I am calling the chat function within the conversation class where it sends User profile along with the user input
import streamlit as st
from openai import OpenAI
import os
from dotenv import load_dotenv
from basic_open_ai import Conversation, system_message
from config import UserProfile
load_dotenv()
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
if not OPENAI_API_KEY:
raise ValueError("OPENAI_API_KEY not found in environment variables")
def main():
st.title("🌍 AI Language Tutor")
st.sidebar.header("User Settings")
# User profile inputs
target_language = st.sidebar.selectbox("Target Language", ["French", "Spanish", "German", "Italian"])
difficulty_level = st.sidebar.selectbox("Difficulty Level", ["Beginner", "Intermediate", "Advanced"])
learning_focus = st.sidebar.selectbox("Learning Focus", ["Vocabulary", "Grammar", "Conversation"])
if "user_profile" not in st.session_state or \
st.session_state.user_profile.target_language != target_language or \
st.session_state.user_profile.difficulty_level != difficulty_level or \
st.session_state.user_profile.learning_focus != learning_focus:
st.session_state.user_profile = UserProfile(
target_language=target_language,
difficulty_level=difficulty_level,
learning_focus=learning_focus
)
# Reset conversation when profile changes
st.session_state.messages = [{"role": "system", "content": system_message}]
# Tabs for Chat and Exercises
tab1, tab2 = st.tabs(["💬 Chat", "📚 Exercises"])
with tab1:
st.subheader("AI Language Tutor")
if "messages" not in st.session_state:
st.session_state.messages = [{"role": "system", "content": system_message}]
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
prompt = st.chat_input("Enter the language you would like to learn")
if prompt:
#Add user message to chat history
with st.chat_message("user"):
st.markdown(prompt)
st.session_state.messages.append({"role": "user", "content": prompt})
#diplay assistant response in chat message container
with st.chat_message("assistant"):
#streaming response
response = Conversation.chat(prompt, st.session_state.user_profile)
st.write(response)
st.session_state.messages.append({"role": "assistant", "content": response})
with tab2:
st.subheader("Exercises")
if __name__ == "__main__":
main()
I am having trouble to integrate all this together and make it work.
I am collecting the user profile from my streamlit application-
