amkyawdev commited on
Commit
3822953
·
verified ·
1 Parent(s): bf3456e

Upload folder using huggingface_hub

Browse files
Files changed (3) hide show
  1. README.md +2 -2
  2. app.py +99 -121
  3. requirements.txt +2 -2
README.md CHANGED
@@ -3,8 +3,8 @@ title: AMK AI Coder Backend
3
  emoji: 🤖
4
  colorFrom: purple
5
  colorTo: indigo
6
- sdk: gradio
7
- sdk_version: 5.0.0
8
  app_file: app.py
9
  pinned: false
10
  ---
 
3
  emoji: 🤖
4
  colorFrom: purple
5
  colorTo: indigo
6
+ sdk: streamlit
7
+ sdk_version: 1.40.0
8
  app_file: app.py
9
  pinned: false
10
  ---
app.py CHANGED
@@ -1,21 +1,20 @@
1
  """
2
  AMK AI Coder Platform - Backend API
3
- Gradio app for HuggingFace Spaces deployment
4
  """
5
  import os
6
- import json
7
  import asyncio
8
- from typing import Optional, List, Dict, Any
9
 
10
- import httpx
11
- import gradio as gr
12
 
13
- # Configuration from environment
14
  OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY", "")
15
  OPENROUTER_API_URL = "https://openrouter.ai/api/v1"
16
  DEFAULT_MODEL = "inclusionai/ling-2.6-1t:free"
17
 
18
- # Deep thinking system prompt
19
  DEEP_THINKING_PROMPT = """You are an advanced AI coding assistant with enhanced deep thinking capabilities.
20
  When analyzing problems, take time to:
21
  1. Understand the core requirements
@@ -24,131 +23,110 @@ When analyzing problems, take time to:
24
  4. Write clean, efficient, and well-documented code
25
  5. Explain your reasoning step by step
26
 
27
- Provide comprehensive, thoughtful responses that demonstrate deep analysis."""
28
 
29
  STANDARD_PROMPT = """You are an AI coding assistant. Provide helpful, accurate, and efficient responses.
30
  Write clean, well-documented code with appropriate comments."""
31
 
32
-
33
- class ChatSession:
34
- """Manages chat sessions with AI providers"""
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
- def __init__(self, api_key: str = ""):
37
- self.api_key = api_key or OPENROUTER_API_KEY
38
- self.messages: List[Dict[str, str]] = []
39
- self.use_deep_thinking = False
40
 
41
- def add_message(self, role: str, content: str):
42
- self.messages.append({"role": role, "content": content})
43
 
44
- def get_context(self, system_prompt: str = STANDARD_PROMPT) -> List[Dict[str, str]]:
45
- context = [{"role": "system", "content": system_prompt}]
46
- context.extend(self.messages[-20:])
47
- return context
48
 
49
- async def send_to_openrouter(
50
- self,
51
- message: str,
52
- model: str = DEFAULT_MODEL,
53
- stream: bool = True
54
- ) -> str:
55
- """Send message to OpenRouter API"""
56
- if not self.api_key:
57
- return "Error: OpenRouter API key not configured. Please set OPENROUTER_API_KEY."
58
-
59
- self.add_message("user", message)
60
-
61
- system_prompt = DEEP_THINKING_PROMPT if self.use_deep_thinking else STANDARD_PROMPT
62
- payload = {
63
- "model": model,
64
- "messages": self.get_context(system_prompt),
65
- "stream": stream,
66
- "temperature": 0.7,
67
- "max_tokens": 4096
68
- }
69
-
70
- headers = {
71
- "Authorization": f"Bearer {self.api_key}",
72
- "Content-Type": "application/json",
73
- "HTTP-Referer": "https://amk-coder.vercel.app",
74
- "X-Title": "AMK AI Coder Platform"
75
- }
76
-
77
- try:
78
- async with httpx.AsyncClient(timeout=120.0) as client:
79
- response = await client.post(
80
- f"{OPENROUTER_API_URL}/chat/completions",
81
- headers=headers,
82
- json=payload
83
- )
84
-
85
- if response.status_code == 200:
86
- data = response.json()
87
- assistant_message = data["choices"][0]["message"]["content"]
88
- self.add_message("assistant", assistant_message)
89
- return assistant_message
90
- else:
91
- error_msg = f"API Error: {response.status_code} - {response.text}"
92
- return error_msg
93
-
94
- except Exception as e:
95
- return f"Error: {str(e)}"
96
 
97
- def clear(self):
98
- self.messages = []
99
-
100
-
101
- # Global chat session
102
- chat_session = ChatSession()
103
-
104
-
105
- async def chat_response(message, history, model, deep_thinking):
106
- """Generate chat response"""
107
- chat_session.use_deep_thinking = deep_thinking
108
 
109
- response = await chat_session.send_to_openrouter(
110
- message=message,
111
- model=model,
112
- stream=False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  )
 
114
 
115
- history.append([message, response])
116
- return "", history
117
-
118
-
119
- def clear_chat():
120
- """Clear chat history"""
121
- chat_session.clear()
122
- return []
123
-
124
-
125
- # Gradio UI
126
- with gr.Blocks(title="AMK AI Coder Backend") as demo:
127
- gr.Markdown("# 🤖 AMK AI Coder Backend API\n\nPowered by **OpenRouter** with ling-2.6-1t model.")
128
 
129
- with gr.Row():
130
- with gr.Column(scale=3):
131
- chatbot = gr.Chatbot(label="Chat", height=400)
132
- msg = gr.Textbox(placeholder="Ask me anything...", lines=3)
133
- with gr.Row():
134
- submit_btn = gr.Button("Send", variant="primary")
135
- clear_btn = gr.Button("Clear")
136
-
137
- with gr.Column(scale=1):
138
- model = gr.Dropdown(
139
- choices=[
140
- "inclusionai/ling-2.6-1t:free",
141
- "anthropic/claude-3.5-sonnet",
142
- "google/gemini-pro",
143
- ],
144
- value="inclusionai/ling-2.6-1t:free",
145
- label="AI Model"
146
- )
147
- deep_thinking = gr.Checkbox(label="🧠 Deep Thinking Mode")
148
 
149
- submit_btn.click(chat_response, [msg, chatbot, model, deep_thinking], [msg, chatbot])
150
- msg.submit(chat_response, [msg, chatbot, model, deep_thinking], [msg, chatbot])
151
- clear_btn.click(clear_chat, outputs=[chatbot])
152
-
153
- if __name__ == "__main__":
154
- demo.launch()
 
 
 
1
  """
2
  AMK AI Coder Platform - Backend API
3
+ Streamlit app for HuggingFace Spaces deployment
4
  """
5
  import os
 
6
  import asyncio
7
+ from typing import List, Dict
8
 
9
+ import streamlit as st
10
+ import requests
11
 
12
+ # Configuration
13
  OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY", "")
14
  OPENROUTER_API_URL = "https://openrouter.ai/api/v1"
15
  DEFAULT_MODEL = "inclusionai/ling-2.6-1t:free"
16
 
17
+ # System prompts
18
  DEEP_THINKING_PROMPT = """You are an advanced AI coding assistant with enhanced deep thinking capabilities.
19
  When analyzing problems, take time to:
20
  1. Understand the core requirements
 
23
  4. Write clean, efficient, and well-documented code
24
  5. Explain your reasoning step by step
25
 
26
+ Provide comprehensive, thoughtful responses."""
27
 
28
  STANDARD_PROMPT = """You are an AI coding assistant. Provide helpful, accurate, and efficient responses.
29
  Write clean, well-documented code with appropriate comments."""
30
 
31
+ # Page config
32
+ st.set_page_config(page_title="AMK AI Coder Backend", page_icon="🤖")
33
+
34
+ # Initialize session state
35
+ if "messages" not in st.session_state:
36
+ st.session_state.messages = []
37
+ if "deep_thinking" not in st.session_state:
38
+ st.session_state.deep_thinking = False
39
+ if "model" not in st.session_state:
40
+ st.session_state.model = DEFAULT_MODEL
41
+
42
+ def send_to_openrouter(message: str, model: str, deep_thinking: bool) -> str:
43
+ """Send message to OpenRouter API"""
44
+ if not OPENROUTER_API_KEY:
45
+ return "Error: OpenRouter API key not configured. Please set OPENROUTER_API_KEY in Space settings."
46
 
47
+ st.session_state.messages.append({"role": "user", "content": message})
 
 
 
48
 
49
+ system_prompt = DEEP_THINKING_PROMPT if deep_thinking else STANDARD_PROMPT
 
50
 
51
+ # Build messages with system prompt
52
+ messages = [{"role": "system", "content": system_prompt}]
53
+ messages.extend([m for m in st.session_state.messages if m["role"] != "system"][-20:])
 
54
 
55
+ payload = {
56
+ "model": model,
57
+ "messages": messages,
58
+ "temperature": 0.7,
59
+ "max_tokens": 4096
60
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
+ headers = {
63
+ "Authorization": f"Bearer {OPENROUTER_API_KEY}",
64
+ "Content-Type": "application/json",
65
+ "HTTP-Referer": "https://amk-coder.vercel.app",
66
+ "X-Title": "AMK AI Coder Platform"
67
+ }
 
 
 
 
 
68
 
69
+ try:
70
+ response = requests.post(
71
+ f"{OPENROUTER_API_URL}/chat/completions",
72
+ headers=headers,
73
+ json=payload,
74
+ timeout=120
75
+ )
76
+
77
+ if response.status_code == 200:
78
+ data = response.json()
79
+ assistant_message = data["choices"][0]["message"]["content"]
80
+ st.session_state.messages.append({"role": "assistant", "content": assistant_message})
81
+ return assistant_message
82
+ else:
83
+ return f"API Error: {response.status_code} - {response.text}"
84
+
85
+ except Exception as e:
86
+ return f"Error: {str(e)}"
87
+
88
+ # UI
89
+ st.title("🤖 AMK AI Coder Backend")
90
+ st.markdown("Powered by **OpenRouter** with ling-2.6-1t model")
91
+
92
+ # Sidebar settings
93
+ with st.sidebar:
94
+ st.header("Settings")
95
+
96
+ model = st.selectbox(
97
+ "AI Model",
98
+ [
99
+ "inclusionai/ling-2.6-1t:free",
100
+ "anthropic/claude-3.5-sonnet",
101
+ "google/gemini-pro",
102
+ ],
103
+ index=0
104
  )
105
+ st.session_state.model = model
106
 
107
+ deep_thinking = st.checkbox("🧠 Deep Thinking Mode", value=st.session_state.deep_thinking)
108
+ st.session_state.deep_thinking = deep_thinking
 
 
 
 
 
 
 
 
 
 
 
109
 
110
+ if st.button("🗑️ Clear Chat"):
111
+ st.session_state.messages = []
112
+ st.rerun()
113
+
114
+ # Display chat history
115
+ for message in st.session_state.messages:
116
+ if message["role"] != "system":
117
+ with st.chat_message(message["role"]):
118
+ st.markdown(message["content"])
119
+
120
+ # Chat input
121
+ if prompt := st.chat_input("Ask me anything..."):
122
+ with st.chat_message("user"):
123
+ st.markdown(prompt)
 
 
 
 
 
124
 
125
+ with st.chat_message("assistant"):
126
+ with st.spinner("Thinking..."):
127
+ response = send_to_openrouter(prompt, st.session_state.model, st.session_state.deep_thinking)
128
+ st.markdown(response)
129
+
130
+ # API Key warning
131
+ if not OPENROUTER_API_KEY:
132
+ st.warning("⚠️ OpenRouter API key not set. Please add OPENROUTER_API_KEY in Space settings.")
requirements.txt CHANGED
@@ -1,2 +1,2 @@
1
- gradio==5.0.0
2
- httpx>=0.25.0
 
1
+ streamlit>=1.40.0
2
+ requests>=2.31.0