Svngoku commited on
Commit
5c01b9f
Β·
verified Β·
1 Parent(s): 3140791

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +152 -0
app.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # unsloth_doc_app.py
2
+ import streamlit as st
3
+ import os
4
+ from smolagents import CodeAgent, Tool
5
+ import requests
6
+ import json
7
+ from typing import List, Dict, Any
8
+
9
+ # Configuration
10
+ PAGE_CONFIG = {
11
+ "page_title": "Unsloth Documentation Search",
12
+ "page_icon": "πŸ“˜",
13
+ "layout": "wide"
14
+ }
15
+
16
+ AUTHORIZED_IMPORTS: List[str] = [
17
+ 'random', 'collections', 'datetime', 'time', 'queue', 'unicodedata',
18
+ 'os', 'stat', 'json', 'math', 're', 'itertools', 'statistics',
19
+ 'pandas', 'numpy', 'requests'
20
+ ]
21
+
22
+ # Tools
23
+ class DuckDuckGoSearchTool(Tool):
24
+ name = "duckduckgo_search"
25
+ description = "Searches DuckDuckGo for Unsloth-related queries."
26
+ inputs = {"query": {"type": "string", "description": "The search query"}}
27
+ output_type = "string"
28
+
29
+ def __init__(self):
30
+ super().__init__()
31
+ self.url = "https://api.duckduckgo.com/"
32
+ self.headers = {'Content-Type': 'application/json'}
33
+
34
+ def forward(self, query: str) -> str:
35
+ payload = {"q": f"unsloth {query}", "format": "json", "no_html": 1}
36
+ response = requests.get(self.url, params=payload, headers=self.headers)
37
+ if response.status_code == 200:
38
+ return json.dumps(response.json(), indent=2)
39
+ return "Error: Unable to fetch search results."
40
+
41
+ class VisitWebpageTool(Tool):
42
+ name = "visit_webpage"
43
+ description = "Fetches content from a specific webpage."
44
+ inputs = {"url": {"type": "string", "description": "The URL to visit"}}
45
+ output_type = "string"
46
+
47
+ def __init__(self):
48
+ super().__init__()
49
+ self.headers = {'User-Agent': 'Mozilla/5.0'}
50
+
51
+ def forward(self, url: str) -> str:
52
+ try:
53
+ response = requests.get(url, headers=self.headers)
54
+ response.raise_for_status()
55
+ return response.text[:2000] # Limit to first 2000 characters
56
+ except Exception as e:
57
+ return f"Error visiting webpage: {e}"
58
+
59
+ # Agent Initialization
60
+ def initialize_unsloth_agent(model=None):
61
+ """Initialize the Unsloth Documentation Agent"""
62
+ tools = [
63
+ DuckDuckGoSearchTool(),
64
+ VisitWebpageTool()
65
+ ]
66
+ # If no model is provided, use a placeholder or mock model
67
+ if model is None:
68
+ from smolagents import HfApiModel
69
+ model = HfApiModel(model_id="Qwen/Qwen2.5-Coder-32B-Instruct",provider="together",)
70
+
71
+ return CodeAgent(
72
+ name="unsloth_agent",
73
+ description="Unsloth Documentation AI Agent",
74
+ tools=tools,
75
+ model=model,
76
+ max_steps=12,
77
+ additional_authorized_imports=AUTHORIZED_IMPORTS
78
+ )
79
+
80
+ # UI Components
81
+ def setup_ui():
82
+ """Setup Streamlit UI components"""
83
+ st.set_page_config(**PAGE_CONFIG)
84
+
85
+ st.title("πŸ“˜ Unsloth Documentation Search")
86
+ st.markdown("""
87
+ This tool uses an AI agent to help you explore Unsloth documentation.
88
+ Ask questions about Unsloth features, usage, or troubleshooting.
89
+ """)
90
+
91
+ def display_results(results: str):
92
+ """Display search results in a formatted way"""
93
+ st.markdown("### πŸ“ Results")
94
+ st.markdown(results, unsafe_allow_html=True)
95
+
96
+ def setup_sidebar():
97
+ """Setup sidebar content"""
98
+ with st.sidebar:
99
+ st.markdown("### About This Tool")
100
+ st.markdown("""
101
+ This agent specializes in Unsloth documentation, providing:
102
+ - πŸ“š Quick answers from web searches
103
+ - 🌐 Webpage content retrieval
104
+ - πŸ€– AI-powered insights
105
+ """)
106
+ st.markdown("### Tips")
107
+ st.markdown("""
108
+ - Use specific queries like "How to install Unsloth" or "Unsloth fine-tuning guide".
109
+ - Results may include raw data from searches or webpages.
110
+ """)
111
+
112
+ # Main App
113
+ @st.cache_resource
114
+ def initialize_app():
115
+ """Initialize the application"""
116
+ return initialize_unsloth_agent()
117
+
118
+ def main():
119
+ setup_ui()
120
+ setup_sidebar()
121
+
122
+ if 'agent' not in st.session_state:
123
+ with st.spinner("Initializing Unsloth Documentation Agent..."):
124
+ st.session_state.agent = initialize_app()
125
+
126
+ search_query = st.text_input(
127
+ "πŸ” Search Unsloth Documentation",
128
+ placeholder="E.g., How to fine-tune with Unsloth"
129
+ )
130
+
131
+ if st.button("Search", type="primary") and search_query:
132
+ with st.spinner("Searching Unsloth documentation..."):
133
+ try:
134
+ results = st.session_state.agent.run(search_query)
135
+ display_results(results)
136
+
137
+ st.markdown("---")
138
+ st.info("""
139
+ πŸ’‘ **How to read the results:**
140
+ - Results may include JSON from searches or webpage snippets.
141
+ - Check the sidebar for tips on refining your query.
142
+ """)
143
+ except Exception as e:
144
+ st.error(f"An error occurred: {e}")
145
+ elif st.button("Search", type="primary"):
146
+ st.warning("Please enter a search query.")
147
+
148
+ st.markdown("---")
149
+ st.caption("Powered by SmolAgents and Unsloth")
150
+
151
+ if __name__ == "__main__":
152
+ main()