louiecerv commited on
Commit
03b26f3
·
1 Parent(s): 54dc230
Files changed (2) hide show
  1. app.py +136 -0
  2. requirements.txt +4 -0
app.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import openai
4
+ from openai import OpenAI
5
+ import streamlit as st
6
+
7
+ api_key = os.getenv("NVIDIA_API_KEY")
8
+
9
+ # Check if the API key is found
10
+ if api_key is None:
11
+ st.error("NVIDIA_API_KEY environment variable not found.")
12
+ else:
13
+ # Initialize the OpenAI client
14
+ client = OpenAI(
15
+ base_url="https://integrate.api.nvidia.com/v1",
16
+ api_key=api_key
17
+ )
18
+
19
+ class ConversationManager:
20
+ def __init__(self):
21
+ # (No need to initialize history here, it will be handled in main())
22
+ pass
23
+
24
+ def generate_ai_response(self, prompt, enable_streaming=False):
25
+ """Generates a response from an AI model
26
+
27
+ Args:
28
+ prompt: The prompt to send to the AI model.
29
+
30
+ Returns:
31
+ response from the AI model.
32
+ """
33
+ try:
34
+ # Access conversation_history from session state
35
+ messages = [
36
+ {
37
+ "role": "system",
38
+ "content": "You are a programming assistant focused on providing \
39
+ accurate, clear, and concise answers to technical questions. \
40
+ Your goal is to help users solve programming problems efficiently, \
41
+ explain concepts clearly, and provide examples when appropriate. \
42
+ Use a professional yet approachable tone. Use explicit markdown \
43
+ format for code for all codes in the output."
44
+ }
45
+ ]
46
+
47
+ for message in st.session_state.conversation_manager.conversation_history:
48
+ messages.append(message)
49
+
50
+ messages.append({
51
+ "role": "user",
52
+ "content": prompt
53
+ })
54
+
55
+ completion = client.chat.completions.create(
56
+ model="meta/llama-3.3-70b-instruct",
57
+ temperature=0.5, # Adjust temperature for creativity
58
+ top_p=1,
59
+ max_tokens=1024,
60
+ messages=messages,
61
+ stream=enable_streaming
62
+ )
63
+
64
+ # Update conversation history in the session state object
65
+ st.session_state.conversation_manager.conversation_history.append({
66
+ "role": "assistant",
67
+ "content": completion.choices[0].message.content
68
+ })
69
+
70
+ if enable_streaming:
71
+ response_container = st.empty()
72
+ model_response = ""
73
+ for chunk in completion:
74
+ if chunk.choices[0].delta.content is not None:
75
+ model_response += chunk.choices[0].delta.content
76
+ response_container.markdown(model_response)
77
+ elif 'error' in chunk:
78
+ st.error(f"Error occurred: {chunk['error']}")
79
+ break
80
+ return model_response
81
+ else:
82
+ return completion.choices[0].message.content
83
+
84
+ except Exception as e:
85
+ print(f"Error: {e}")
86
+ return None
87
+
88
+
89
+ def main():
90
+ # Initialize ConversationManager in session state if not already present
91
+ if "conversation_manager" not in st.session_state:
92
+ st.session_state.conversation_manager = ConversationManager()
93
+ st.session_state.conversation_manager.conversation_history = []
94
+
95
+ st.title("AI-Assisted Code Generator")
96
+
97
+ tab1, tab2, tab3 = st.tabs(["About", "Code Generation", "Conversation History"])
98
+
99
+ with tab1:
100
+ st.header("About this App")
101
+ st.write("This app demonstrates how to use AI to assist in code generation.")
102
+
103
+ with tab2:
104
+ st.header("Generate Code")
105
+ framework = st.selectbox("Select a framework", ["Streamlit", "Gradio"])
106
+ app_details = st.text_area("Describe the app you want to create", value="Create a complete app that ")
107
+
108
+ if st.button("Generate Prompt"):
109
+ user_prompt = f"Using {framework}, {app_details}"
110
+ st.write("**Generated Prompt:**", user_prompt)
111
+
112
+ with st.spinner("Generating code..."):
113
+ # Add the user message to the history FIRST
114
+ st.session_state.conversation_manager.conversation_history.append({"role": "user", "content": user_prompt})
115
+
116
+ ai_response = st.session_state.conversation_manager.generate_ai_response(user_prompt)
117
+ if ai_response:
118
+ st.session_state.conversation_manager.conversation_history.append({"role": "assistant", "content": ai_response})
119
+ st.markdown(f"**User:** {user_prompt}")
120
+ st.markdown(f"**AI:** {ai_response}")
121
+ else:
122
+ st.write("**Error:** Failed to generate AI response.")
123
+
124
+ with tab3:
125
+ st.header("Conversation History")
126
+ if st.session_state.conversation_manager.conversation_history:
127
+ for msg in st.session_state.conversation_manager.conversation_history:
128
+ if msg['role'] == 'user':
129
+ st.markdown(f"**User:** {msg['content']}")
130
+ else:
131
+ st.markdown(f"**AI:** {msg['content']}")
132
+ else:
133
+ st.write("No conversation history yet.")
134
+
135
+ if __name__ == "__main__":
136
+ main()
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ streamlit
2
+ openai
3
+ streamlit-chat
4
+ python-dotenv