aisrini commited on
Commit
edf481b
Β·
verified Β·
1 Parent(s): 7a2e1d3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +142 -141
app.py CHANGED
@@ -1,155 +1,156 @@
1
- import streamlit as st
2
  import requests
3
  import json
4
- import re
5
  import os
6
 
7
  FIREWORKS_API_KEY = os.getenv("FIREWORKS_API_KEY")
8
  API_URL = "https://api.fireworks.ai/inference/v1/chat/completions"
9
  MODEL_NAME = "accounts/fireworks/models/glm-4p6"
10
 
11
- st.set_page_config(page_title="Intelligent Documentation Agent", layout="wide")
12
 
13
- # ---- Sidebar ----
14
- st.sidebar.title("βš™οΈ Configuration")
15
- api_key_input = st.sidebar.text_input("πŸ”‘ Fireworks API Key", value=FIREWORKS_API_KEY or "", type="password")
16
- if api_key_input:
17
- FIREWORKS_API_KEY = api_key_input
18
-
19
- # ---- Tabs ----
20
- tab1, tab2 = st.tabs(["πŸ“„ Generate Documentation", "πŸ’¬ Chat with Code"])
21
-
22
- # ---------------- TAB 1: DOCUMENTATION GENERATOR ----------------
23
- with tab1:
24
- st.title("Intelligent Documentation Generator")
25
-
26
- st.markdown("Upload a Python file, paste code, or provide a GitHub link to generate smart documentation.")
 
 
 
 
27
 
28
- code_input_type = st.radio(
29
- "Choose input type:",
30
- ["Paste Code", "Upload File", "GitHub Link"],
31
- horizontal=True
32
- )
33
 
34
- code_content = ""
 
 
 
 
35
 
36
- # --- Option 1: Paste code ---
37
  if code_input_type == "Paste Code":
38
- code_content = st.text_area("Paste your Python code here", height=300)
39
-
40
- # --- Option 2: Upload file ---
41
- elif code_input_type == "Upload File":
42
- uploaded_file = st.file_uploader("Upload a Python file", type=["py"])
43
- if uploaded_file is not None:
44
- code_content = uploaded_file.read().decode("utf-8")
45
-
46
- # --- Option 3: GitHub link ---
47
- elif code_input_type == "GitHub Link":
48
- github_url = st.text_input("Enter a GitHub raw file link (e.g. https://raw.githubusercontent.com/...)")
49
- if github_url:
50
- if "raw.githubusercontent.com" not in github_url:
51
- github_url = github_url.replace("github.com", "raw.githubusercontent.com").replace("/blob/", "/")
52
- try:
53
- r = requests.get(github_url)
54
- if r.status_code == 200:
55
- code_content = r.text
56
- else:
57
- st.error(f"Unable to fetch file (HTTP {r.status_code})")
58
- except Exception as e:
59
- st.error(f"Error fetching file: {e}")
60
-
61
- if st.button("πŸš€ Generate Documentation"):
62
- if not code_content.strip():
63
- st.warning("Please provide code first.")
64
  else:
65
- st.info("Generating intelligent documentation with GLM-4.6...")
66
-
67
- messages = [
68
- {
69
- "role": "system",
70
- "content": (
71
- "You are an AI documentation assistant that analyzes Python code and generates "
72
- "multi-layer documentation. Include: 1) Overview, 2) Key classes/functions, "
73
- "3) Usage examples, 4) Dependencies, 5) Suggested improvements."
74
- ),
75
- },
76
- {"role": "user", "content": code_content},
77
- ]
78
-
79
- payload = {
80
- "model": MODEL_NAME,
81
- "max_tokens": 4096,
82
- "temperature": 0.6,
83
- "messages": messages,
84
- }
85
-
86
- headers = {
87
- "Accept": "application/json",
88
- "Content-Type": "application/json",
89
- "Authorization": f"Bearer {FIREWORKS_API_KEY}",
90
- }
91
-
92
- response = requests.post(API_URL, headers=headers, data=json.dumps(payload))
93
- if response.status_code == 200:
94
- output = response.json()["choices"][0]["message"]["content"]
95
- st.subheader("πŸ“˜ Generated Documentation")
96
- st.markdown(output)
97
- st.session_state["doc_output"] = output
98
- st.session_state["code_context"] = code_content
99
- else:
100
- st.error(f"Error: {response.text}")
101
-
102
- # ---------------- TAB 2: CHATBOT ----------------
103
- with tab2:
104
- st.title("πŸ’¬ Chat with Your Code")
105
-
106
- if "code_context" not in st.session_state:
107
- st.info("First, generate or upload a code file in the previous tab to start chatting.")
108
- else:
109
- code_context = st.session_state["code_context"]
110
- if "chat_history" not in st.session_state:
111
- st.session_state["chat_history"] = []
112
-
113
- user_query = st.text_input("Ask something about the code:")
114
- if st.button("Ask"):
115
- if not user_query.strip():
116
- st.warning("Please enter a question.")
117
- else:
118
- messages = [
119
- {
120
- "role": "system",
121
- "content": (
122
- "You are a code analysis assistant. You answer questions about the following Python code. "
123
- "Explain clearly and refer to specific functions or logic when relevant."
124
- ),
125
- },
126
- {"role": "user", "content": f"Code:\n{code_context}\n\nQuestion:\n{user_query}"},
127
- ]
128
-
129
- payload = {
130
- "model": MODEL_NAME,
131
- "max_tokens": 2048,
132
- "temperature": 0.5,
133
- "messages": messages,
134
- }
135
-
136
- headers = {
137
- "Accept": "application/json",
138
- "Content-Type": "application/json",
139
- "Authorization": f"Bearer {FIREWORKS_API_KEY}",
140
- }
141
-
142
- response = requests.post(API_URL, headers=headers, data=json.dumps(payload))
143
- if response.status_code == 200:
144
- reply = response.json()["choices"][0]["message"]["content"]
145
- st.session_state["chat_history"].append(("user", user_query))
146
- st.session_state["chat_history"].append(("assistant", reply))
147
- else:
148
- st.error(f"Error: {response.text}")
149
-
150
- # Display chat
151
- for role, msg in st.session_state["chat_history"]:
152
- if role == "user":
153
- st.markdown(f"**You:** {msg}")
154
- else:
155
- st.markdown(f"**GLM-4.6:** {msg}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
  import requests
3
  import json
 
4
  import os
5
 
6
  FIREWORKS_API_KEY = os.getenv("FIREWORKS_API_KEY")
7
  API_URL = "https://api.fireworks.ai/inference/v1/chat/completions"
8
  MODEL_NAME = "accounts/fireworks/models/glm-4p6"
9
 
 
10
 
11
+ # ---------- Fireworks GLM Request ----------
12
+ def query_fireworks(messages, max_tokens=2048, temperature=0.6):
13
+ headers = {
14
+ "Accept": "application/json",
15
+ "Content-Type": "application/json",
16
+ "Authorization": f"Bearer {FIREWORKS_API_KEY}",
17
+ }
18
+ payload = {
19
+ "model": MODEL_NAME,
20
+ "max_tokens": max_tokens,
21
+ "temperature": temperature,
22
+ "messages": messages,
23
+ }
24
+ response = requests.post(API_URL, headers=headers, data=json.dumps(payload))
25
+ if response.status_code == 200:
26
+ return response.json()["choices"][0]["message"]["content"]
27
+ else:
28
+ return f"Error: {response.text}"
29
 
 
 
 
 
 
30
 
31
+ # ---------- Documentation Generator ----------
32
+ def generate_docs(code_input_type, code_content, file_obj, github_url, api_key):
33
+ global FIREWORKS_API_KEY
34
+ if api_key:
35
+ FIREWORKS_API_KEY = api_key
36
 
37
+ code = ""
38
  if code_input_type == "Paste Code":
39
+ code = code_content
40
+ elif code_input_type == "Upload File" and file_obj is not None:
41
+ code = file_obj.read().decode("utf-8")
42
+ elif code_input_type == "GitHub Link" and github_url:
43
+ if "raw.githubusercontent.com" not in github_url:
44
+ github_url = github_url.replace("github.com", "raw.githubusercontent.com").replace("/blob/", "/")
45
+ r = requests.get(github_url)
46
+ if r.status_code == 200:
47
+ code = r.text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  else:
49
+ return f"Unable to fetch file (HTTP {r.status_code})", ""
50
+
51
+ if not code.strip():
52
+ return "⚠️ Please provide valid Python code.", ""
53
+
54
+ messages = [
55
+ {
56
+ "role": "system",
57
+ "content": (
58
+ "You are an AI documentation assistant that analyzes Python code and generates "
59
+ "multi-layer documentation. Include: 1) Overview, 2) Key classes/functions, "
60
+ "3) Usage examples, 4) Dependencies, 5) Suggested improvements."
61
+ ),
62
+ },
63
+ {"role": "user", "content": code},
64
+ ]
65
+
66
+ output = query_fireworks(messages, max_tokens=4096)
67
+ return output, code
68
+
69
+
70
+ # ---------- Code Chat ----------
71
+ def chat_with_code(user_input, chat_history, code_context, api_key):
72
+ global FIREWORKS_API_KEY
73
+ if api_key:
74
+ FIREWORKS_API_KEY = api_key
75
+
76
+ if not code_context.strip():
77
+ return "⚠️ No code context found. Please generate documentation first.", chat_history
78
+
79
+ messages = [
80
+ {
81
+ "role": "system",
82
+ "content": (
83
+ "You are a code analysis assistant. You answer questions about the following Python code. "
84
+ "Explain clearly and refer to specific functions or logic when relevant."
85
+ ),
86
+ },
87
+ {"role": "user", "content": f"Code:\n{code_context}\n\nQuestion:\n{user_input}"},
88
+ ]
89
+
90
+ reply = query_fireworks(messages)
91
+ chat_history.append(("You", user_input))
92
+ chat_history.append(("GLM-4.6", reply))
93
+ return "", chat_history
94
+
95
+
96
+ # ---------- Gradio UI ----------
97
+
98
+ with gr.Blocks(title="Intelligent Documentation Generator Agent") as demo:
99
+ gr.Markdown("# 🧠 Intelligent Documentation Generator Agent (GLM-4.6 on Fireworks AI)")
100
+ gr.Markdown(
101
+ "Generate intelligent documentation or chat with your Python code. "
102
+ "Provide your Fireworks API key to get started."
103
+ )
104
+
105
+ with gr.Row():
106
+ api_key_box = gr.Textbox(
107
+ label="πŸ”‘ Fireworks API Key",
108
+ placeholder="Enter your Fireworks API Key",
109
+ type="password",
110
+ )
111
+
112
+ with gr.Tabs():
113
+ # ---- Documentation Tab ----
114
+ with gr.TabItem("πŸ“„ Generate Documentation"):
115
+ code_input_type = gr.Radio(
116
+ ["Paste Code", "Upload File", "GitHub Link"], label="Choose input type", value="Paste Code"
117
+ )
118
+
119
+ code_box = gr.Textbox(label="Paste your Python code", lines=15, visible=True)
120
+ file_upload = gr.File(label="Upload Python file", visible=False)
121
+ github_box = gr.Textbox(label="GitHub raw file link", visible=False)
122
+
123
+ def toggle_inputs(input_type):
124
+ return (
125
+ gr.update(visible=input_type == "Paste Code"),
126
+ gr.update(visible=input_type == "Upload File"),
127
+ gr.update(visible=input_type == "GitHub Link"),
128
+ )
129
+
130
+ code_input_type.change(toggle_inputs, [code_input_type], [code_box, file_upload, github_box])
131
+
132
+ generate_btn = gr.Button("πŸš€ Generate Documentation")
133
+
134
+ output_box = gr.Markdown(label="πŸ“˜ Generated Documentation")
135
+ hidden_code_context = gr.Textbox(visible=False)
136
+
137
+ generate_btn.click(
138
+ generate_docs,
139
+ [code_input_type, code_box, file_upload, github_box, api_key_box],
140
+ [output_box, hidden_code_context],
141
+ )
142
+
143
+ # ---- Chat Tab ----
144
+ with gr.TabItem("πŸ’¬ Chat with Code"):
145
+ gr.Markdown("Chat about the Python file you uploaded or analyzed in the previous tab.")
146
+ chatbot = gr.Chatbot(label="GLM-4.6 Code Assistant")
147
+ msg = gr.Textbox(label="Ask a question about the code")
148
+ send_btn = gr.Button("Ask")
149
+
150
+ send_btn.click(
151
+ chat_with_code,
152
+ [msg, chatbot, hidden_code_context, api_key_box],
153
+ [msg, chatbot],
154
+ )
155
+
156
+ demo.launch()