Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,228 +1,23 @@
|
|
| 1 |
-
|
| 2 |
-
import os
|
| 3 |
-
import datetime
|
| 4 |
-
import gradio as gr
|
| 5 |
-
import requests
|
| 6 |
-
from typing import Optional, List
|
| 7 |
-
from langchain.llms.base import LLM
|
| 8 |
-
from langchain.agents import initialize_agent, AgentType,load_tools
|
| 9 |
-
from langchain.agents import AgentExecutor, create_structured_chat_agent
|
| 10 |
-
from langchain.tools import Tool
|
| 11 |
-
from langchain_experimental.tools.python.tool import PythonREPLTool
|
| 12 |
-
import queue
|
| 13 |
-
from typing import Any, Dict
|
| 14 |
-
import gradio as gr
|
| 15 |
-
from langchain.callbacks.base import BaseCallbackHandler
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
from langchain.tools import YouTubeSearchTool as YTS
|
| 19 |
-
# 2. 컀μ€ν
μ½λ°± νΈλ€λ¬
|
| 20 |
-
|
| 21 |
-
# github_model_llm.py
|
| 22 |
-
"""
|
| 23 |
-
GitHub Models API κΈ°λ° LLM λνΌ (LangChain LLM νΈν)
|
| 24 |
-
- OpenAI-style chat completions νΈν
|
| 25 |
-
- function calling (OPENAI_MULTI_FUNCTIONS) μ§μ: functions, function_call μ λ¬ κ°λ₯
|
| 26 |
-
- system prompt (system_prompt) μ§μ
|
| 27 |
-
- μ΅μ
: temperature, max_tokens, top_p λ± μ λ¬
|
| 28 |
-
- raw response λ°ν λ©μλ ν¬ν¨
|
| 29 |
-
"""
|
| 30 |
-
|
| 31 |
from typing import Optional, List, Dict, Any
|
| 32 |
-
import os
|
| 33 |
-
import time
|
| 34 |
-
import json
|
| 35 |
-
import requests
|
| 36 |
from requests.adapters import HTTPAdapter, Retry
|
| 37 |
from langchain.llms.base import LLM
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
def __init__(
|
| 43 |
-
self,
|
| 44 |
-
model: str = "openai/gpt-4.1",
|
| 45 |
-
token: Optional[str] = os.environ["token"],
|
| 46 |
-
endpoint: str = "https://models.github.ai/inference",
|
| 47 |
-
system_prompt: Optional[str] = "λλ PIXAL(Primary Interactive X-ternal Assistant with multi Language)μ΄μΌ.λμ κ°λ°μλ μ μ±μ€ μ΄λΌλ 6νλ
νμ΄μ¬ νλ‘κ·Έλλ¨ΈμΌ.",
|
| 48 |
-
request_timeout: float = 30.0,
|
| 49 |
-
max_retries: int = 2,
|
| 50 |
-
backoff_factor: float = 0.3,
|
| 51 |
-
**kwargs,
|
| 52 |
-
):
|
| 53 |
-
"""
|
| 54 |
-
Args:
|
| 55 |
-
model: λͺ¨λΈ μ΄λ¦ (μ: "openai/gpt-4.1")
|
| 56 |
-
token: GitHub Models API ν ν° (Bearer). νκ²½λ³μ GITHUB_TOKEN / token μ¬μ© κ°λ₯ as fallback.
|
| 57 |
-
endpoint: API endpoint (κΈ°λ³Έ: https://models.github.ai/inference)
|
| 58 |
-
system_prompt: (μ ν) system role λ©μμ§λ‘ νμ μμ λΆμ
|
| 59 |
-
request_timeout: μμ² νμμμ (μ΄)
|
| 60 |
-
max_retries: λ€νΈμν¬ μ¬μλ νμ
|
| 61 |
-
backoff_factor: μ¬μλ μ§μ 보μ
|
| 62 |
-
kwargs: LangChain LLM λΆλͺ¨μ μ λ¬ν μΆκ° μΈμ
|
| 63 |
-
"""
|
| 64 |
-
super().__init__(**kwargs)
|
| 65 |
-
self.model = model
|
| 66 |
-
self.endpoint = endpoint.rstrip("/")
|
| 67 |
-
self.token = token or os.getenv("GITHUB_TOKEN") or os.getenv("token")
|
| 68 |
-
self.system_prompt = system_prompt
|
| 69 |
-
self.request_timeout = request_timeout
|
| 70 |
-
|
| 71 |
-
# requests μΈμ
+ μ¬μλ μ€μ
|
| 72 |
-
self.session = requests.Session()
|
| 73 |
-
retries = Retry(total=max_retries, backoff_factor=backoff_factor,
|
| 74 |
-
status_forcelist=[429, 500, 502, 503, 504],
|
| 75 |
-
allowed_methods=["POST", "GET"])
|
| 76 |
-
self.session.mount("https://", HTTPAdapter(max_retries=retries))
|
| 77 |
-
self.session.headers.update({
|
| 78 |
-
"Content-Type": "application/json"
|
| 79 |
-
})
|
| 80 |
-
if self.token:
|
| 81 |
-
self.session.headers.update({"Authorization": f"Bearer {self.token}"})
|
| 82 |
-
|
| 83 |
-
@property
|
| 84 |
-
def _llm_type(self) -> str:
|
| 85 |
-
return "github_models_api"
|
| 86 |
-
|
| 87 |
-
# ---------- νΈμ internal helper ----------
|
| 88 |
-
def _build_messages(self, prompt: str, extra_messages: Optional[List[Dict[str, Any]]] = None) -> List[Dict[str, Any]]:
|
| 89 |
-
"""
|
| 90 |
-
messages λ°°μ΄ μμ±: system (optional) + extra_messages (if any) + user prompt
|
| 91 |
-
extra_messages: μ΄λ―Έ role keysλ‘ κ΅¬μ±λ λ©μμ§ λ¦¬μ€νΈ (μ: conversation history)
|
| 92 |
-
"""
|
| 93 |
-
msgs: List[Dict[str, Any]] = []
|
| 94 |
-
if self.system_prompt:
|
| 95 |
-
msgs.append({"role": "system", "content": self.system_prompt})
|
| 96 |
-
if extra_messages:
|
| 97 |
-
# ensure format: list of {"role":..,"content":..}
|
| 98 |
-
msgs.extend(extra_messages)
|
| 99 |
-
msgs.append({"role": "user", "content": prompt})
|
| 100 |
-
return msgs
|
| 101 |
-
|
| 102 |
-
def _post_chat(self, body: Dict[str, Any]) -> Dict[str, Any]:
|
| 103 |
-
url = f"{self.endpoint}/chat/completions"
|
| 104 |
-
# ensure Authorization present
|
| 105 |
-
if "Authorization" not in self.session.headers and not self.token:
|
| 106 |
-
raise ValueError("GitHub Models token not set. Provide token param or set GITHUB_TOKEN env var.")
|
| 107 |
-
|
| 108 |
-
resp = self.session.post(url, json=body, timeout=self.request_timeout)
|
| 109 |
-
try:
|
| 110 |
-
resp.raise_for_status()
|
| 111 |
-
except requests.HTTPError as e:
|
| 112 |
-
# try to surface JSON error if present
|
| 113 |
-
content = resp.text
|
| 114 |
-
try:
|
| 115 |
-
j = resp.json()
|
| 116 |
-
content = json.dumps(j, ensure_ascii=False, indent=2)
|
| 117 |
-
except Exception:
|
| 118 |
-
pass
|
| 119 |
-
raise RuntimeError(f"GitHub Models API error: {e} - {content}")
|
| 120 |
-
return resp.json()
|
| 121 |
-
|
| 122 |
-
# ---------- LangChain LLM interface ----------
|
| 123 |
-
def _call(self, prompt: str, stop: Optional[List[str]] = None, **kwargs) -> str:
|
| 124 |
-
"""
|
| 125 |
-
LangChain LLM `_call` ꡬν (λκΈ°).
|
| 126 |
-
Supports kwargs:
|
| 127 |
-
- functions: list[dict] (function schemas)
|
| 128 |
-
- function_call: "auto" | {"name": "..."} | etc.
|
| 129 |
-
- messages: list[dict] (if you want to pass full conversation instead of prompt)
|
| 130 |
-
- temperature, top_p, max_tokens, n, stream, etc.
|
| 131 |
-
Returns:
|
| 132 |
-
assistant content (string). If function_call is returned by model, returns the 'content' if present,
|
| 133 |
-
otherwise returns function_call object as JSON string (so caller can parse).
|
| 134 |
-
"""
|
| 135 |
-
# support passing full messages via kwargs['messages']
|
| 136 |
-
messages = None
|
| 137 |
-
extra_messages = None
|
| 138 |
-
if "messages" in kwargs and isinstance(kwargs["messages"], list):
|
| 139 |
-
messages = kwargs.pop("messages")
|
| 140 |
-
else:
|
| 141 |
-
# optionally allow 'history' or 'extra_messages'
|
| 142 |
-
extra_messages = kwargs.pop("extra_messages", None)
|
| 143 |
-
|
| 144 |
-
if messages is None:
|
| 145 |
-
messages = self._build_messages(prompt, extra_messages=extra_messages)
|
| 146 |
-
|
| 147 |
-
body: Dict[str, Any] = {
|
| 148 |
-
"model": self.model,
|
| 149 |
-
"messages": messages,
|
| 150 |
-
}
|
| 151 |
-
|
| 152 |
-
# pass optional top-level params (temperature, max_tokens, etc.) from kwargs
|
| 153 |
-
for opt in ["temperature", "top_p", "max_tokens", "n", "stream", "presence_penalty", "frequency_penalty"]:
|
| 154 |
-
if opt in kwargs:
|
| 155 |
-
body[opt] = kwargs.pop(opt)
|
| 156 |
-
|
| 157 |
-
# pass function-calling related keys verbatim if provided
|
| 158 |
-
if "functions" in kwargs:
|
| 159 |
-
body["functions"] = kwargs.pop("functions")
|
| 160 |
-
if "function_call" in kwargs:
|
| 161 |
-
body["function_call"] = kwargs.pop("function_call")
|
| 162 |
-
|
| 163 |
-
# include stop if present
|
| 164 |
-
if stop:
|
| 165 |
-
body["stop"] = stop
|
| 166 |
-
|
| 167 |
-
# send request
|
| 168 |
-
raw = self._post_chat(body)
|
| 169 |
-
|
| 170 |
-
# save raw for caller if needed
|
| 171 |
-
self._last_raw = raw
|
| 172 |
-
|
| 173 |
-
# parse assistant message
|
| 174 |
-
choices = raw.get("choices") or []
|
| 175 |
-
if not choices:
|
| 176 |
-
return ""
|
| 177 |
-
|
| 178 |
-
message_obj = choices[0].get("message", {})
|
| 179 |
-
|
| 180 |
-
# if assistant returned a function_call, include that info
|
| 181 |
-
if "function_call" in message_obj:
|
| 182 |
-
# return function_call as JSON string so agent/tool orchestrator can parse it
|
| 183 |
-
# but if content also exists, prefer content
|
| 184 |
-
func = message_obj["function_call"]
|
| 185 |
-
# sometimes content may be absent; return structured JSON string
|
| 186 |
-
return json.dumps({"function_call": func}, ensure_ascii=False)
|
| 187 |
-
|
| 188 |
-
# otherwise return assistant content
|
| 189 |
-
return message_obj.get("content", "") or ""
|
| 190 |
-
|
| 191 |
-
# optional: expose raw response getter
|
| 192 |
-
def last_raw_response(self) -> Optional[Dict[str, Any]]:
|
| 193 |
-
return getattr(self, "_last_raw", None)
|
| 194 |
-
|
| 195 |
-
# optional: provide a convenience chat method to get full message object
|
| 196 |
-
def chat_completions(self, prompt: str, messages: Optional[List[Dict[str, Any]]] = None, **kwargs) -> Dict[str, Any]:
|
| 197 |
-
"""
|
| 198 |
-
Directly call chat completions and return full parsed JSON response.
|
| 199 |
-
- If `messages` provided, it's used as the full messages array (system/user/assistant roles as needed)
|
| 200 |
-
- else uses prompt + system_prompt to construct messages.
|
| 201 |
-
"""
|
| 202 |
-
if messages is None:
|
| 203 |
-
messages = self._build_messages(prompt)
|
| 204 |
-
body: Dict[str, Any] = {"model": self.model, "messages": messages}
|
| 205 |
-
for opt in ["temperature", "top_p", "max_tokens", "n", "stream"]:
|
| 206 |
-
if opt in kwargs:
|
| 207 |
-
body[opt] = kwargs.pop(opt)
|
| 208 |
-
if "functions" in kwargs:
|
| 209 |
-
body["functions"] = kwargs.pop("functions")
|
| 210 |
-
if "function_call" in kwargs:
|
| 211 |
-
body["function_call"] = kwargs.pop("function_call")
|
| 212 |
-
raw = self._post_chat(body)
|
| 213 |
-
self._last_raw = raw
|
| 214 |
-
return raw
|
| 215 |
-
'''
|
| 216 |
-
from typing import Optional, List, Dict, Any
|
| 217 |
-
from langchain.llms.base import LLM
|
| 218 |
-
import requests, os, json
|
| 219 |
-
from requests.adapters import HTTPAdapter, Retry
|
| 220 |
-
|
| 221 |
class GitHubModelLLM(LLM):
|
| 222 |
-
"""GitHub Models API κΈ°λ° LangChain LLM (Pydantic νΈν)"""
|
| 223 |
model: str = "openai/gpt-4.1"
|
| 224 |
endpoint: str = "https://models.github.ai/inference"
|
| 225 |
-
token: Optional[str] = os.environ
|
| 226 |
system_prompt: Optional[str] = "λλ PIXAL(Primary Interactive X-ternal Assistant with multi Language)μ΄μΌ.λμ κ°λ°μλ μ μ±μ€ μ΄λΌλ 6νλ
νμ΄μ¬ νλ‘κ·Έλλ¨ΈμΌ."
|
| 227 |
request_timeout: float = 30.0
|
| 228 |
max_retries: int = 2
|
|
@@ -236,7 +31,6 @@ class GitHubModelLLM(LLM):
|
|
| 236 |
token = self.token or os.getenv("GITHUB_TOKEN") or os.getenv("token")
|
| 237 |
if not token:
|
| 238 |
raise ValueError("β GitHub tokenμ΄ μ€μ λμ§ μμμ΅λλ€.")
|
| 239 |
-
|
| 240 |
session = requests.Session()
|
| 241 |
retries = Retry(total=self.max_retries, backoff_factor=self.backoff_factor,
|
| 242 |
status_forcelist=[429, 500, 502, 503, 504])
|
|
@@ -250,182 +44,86 @@ class GitHubModelLLM(LLM):
|
|
| 250 |
return resp.json()
|
| 251 |
|
| 252 |
def _call(self, prompt: str, stop: Optional[List[str]] = None, **kwargs) -> str:
|
| 253 |
-
body = {
|
| 254 |
-
"model": self.model,
|
| 255 |
-
"messages": []
|
| 256 |
-
}
|
| 257 |
if self.system_prompt:
|
| 258 |
body["messages"].append({"role": "system", "content": self.system_prompt})
|
| 259 |
body["messages"].append({"role": "user", "content": prompt})
|
| 260 |
-
|
| 261 |
-
for key in ["temperature", "max_tokens", "functions", "function_call"]:
|
| 262 |
-
if key in kwargs:
|
| 263 |
-
body[key] = kwargs[key]
|
| 264 |
if stop:
|
| 265 |
body["stop"] = stop
|
| 266 |
-
|
| 267 |
res = self._post_chat(body)
|
| 268 |
msg = res.get("choices", [{}])[0].get("message", {})
|
| 269 |
return msg.get("content") or json.dumps(msg.get("function_call", {}))
|
| 270 |
|
| 271 |
-
from langchain_community.retrievers import WikipediaRetriever
|
| 272 |
-
from langchain.tools.retriever import create_retriever_tool
|
| 273 |
-
retriever = WikipediaRetriever(lang="ko",top_k_results=10)
|
| 274 |
-
wiki=Tool(func=retriever.get_relevant_documents,name="WIKI SEARCH",description="μν€λ°±κ³Όμμ νμν μ 보λ₯Ό λΆλ¬μ΅λλ€.κ²°κ΄΄λ₯Ό κ²μ¦νμ¬ μ¬μ©νμμ€.")
|
| 275 |
# ββββββββββββββββββββββββββββββ
|
| 276 |
-
# β
|
| 277 |
# ββββββββββββββββββββββββββββββ
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
headers = {
|
| 293 |
-
"Authorization": "Bearer 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",
|
| 294 |
-
"Content-Type": "application/json",
|
| 295 |
-
}
|
| 296 |
-
body = {"model": self.model, "messages": [{"role": "user", "content": prompt}]}
|
| 297 |
|
| 298 |
-
resp = requests.post(f"{self.endpoint}/chat/completions", json=body, headers=headers)
|
| 299 |
-
if resp.status_code != 200:
|
| 300 |
-
raise ValueError(f"API μ€λ₯: {resp.status_code} - {resp.text}")
|
| 301 |
-
return resp.json()["choices"][0]["message"]["content"]
|
| 302 |
-
'''
|
| 303 |
# ββββββββββββββββββββββββββββββ
|
| 304 |
-
# β
|
| 305 |
# ββββββββββββββββββββββββββββββ
|
| 306 |
-
token = os.getenv("GITHUB_TOKEN") or os.getenv("token")
|
| 307 |
-
if not token:
|
| 308 |
-
print("β οΈ GitHub Tokenμ΄ νμν©λλ€. μ: setx GITHUB_TOKEN your_token")
|
| 309 |
-
|
| 310 |
llm = GitHubModelLLM()
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
tools
|
| 316 |
-
["ddg-search", "requests_all", "llm-math"],
|
| 317 |
-
llm=llm,allow_dangerous_tools=True
|
| 318 |
-
)+[YTS()]+[wiki]
|
| 319 |
-
# ββββββββββββββββββββββββββββββ
|
| 320 |
-
# β
Python μ€ν λꡬ (LangChain λ΄μ₯)
|
| 321 |
-
# ββββββββββββββββββββββββββββββ
|
| 322 |
-
python_tool = PythonREPLTool()
|
| 323 |
-
tools.append(Tool(name="python_repl", func=python_tool.run, description="Python μ½λλ₯Ό μ€νν©λλ€."))
|
| 324 |
-
from langchain import hub
|
| 325 |
-
prompt=hub.pull("hwchase17/structured-chat-agent")
|
| 326 |
-
from langchain_community.tools.shell.tool import ShellTool
|
| 327 |
-
shell_tool = ShellTool()
|
| 328 |
-
tools.append(Tool(name="shell_exec", func=shell_tool.run, description="λ‘컬 λͺ
λ Ήμ΄λ₯Ό μ€νν©λλ€."))
|
| 329 |
-
|
| 330 |
-
# ββββββββββββββββββββββββββββββ
|
| 331 |
-
# β
νμΌ λꡬ
|
| 332 |
-
# ββββββββββββββββββββββββββββββ
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
# ββββββββββββββββββββββββββββββ
|
| 336 |
-
# β
μ νν νκ΅ μκ° ν¨μ (Asia/Seoul)
|
| 337 |
-
# ββββββββββββββββββββββββββββββ
|
| 338 |
-
import requests
|
| 339 |
-
from zoneinfo import ZoneInfo
|
| 340 |
|
| 341 |
def time_now(_=""):
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
if resp.status_code == 200:
|
| 346 |
-
data = resp.json()
|
| 347 |
-
dt = data["dateTime"].split(".")[0].replace("T", " ")
|
| 348 |
-
return f"νμ¬ μκ°: {dt} (Asia/Seoul, μλ² κΈ°μ€ NTP λκΈ°ν)"
|
| 349 |
-
else:
|
| 350 |
-
# API μ€ν¨ μ λ‘컬 μμ€ν
μκ°μΌλ‘ λ체
|
| 351 |
-
tz = ZoneInfo("Asia/Seoul")
|
| 352 |
-
now = datetime.datetime.now(tz)
|
| 353 |
-
return f"νμ¬ μκ°(λ‘컬): {now.strftime('%Y-%m-%d %H:%M:%S')} (Asia/Seoul)"
|
| 354 |
-
except Exception as e:
|
| 355 |
-
tz = ZoneInfo("Asia/Seoul")
|
| 356 |
-
now = datetime.datetime.now(tz)
|
| 357 |
-
return f"νμ¬ μκ°(λ°±μ
): {now.strftime('%Y-%m-%d %H:%M:%S')} (Asia/Seoul, μ€λ₯: {e})"
|
| 358 |
-
# ββββββββββββββββββββββββββββββ
|
| 359 |
-
# β
λꡬ λ±λ‘
|
| 360 |
-
# ββββββββββββββββββββββββββββββ
|
| 361 |
-
tools.extend([Tool(name="time_now", func=time_now, description="νμ¬ μκ°μ λ°νν©λλ€.")])
|
| 362 |
-
from langchain.memory import ConversationBufferMemory as MEM
|
| 363 |
-
from langchain.agents.agent_toolkits import FileManagementToolkit as FMT
|
| 364 |
-
tools.extend(FMT(root_dir=str(os.getcwd())).get_tools())
|
| 365 |
-
# ββββββββββββββββββββββββββββββ
|
| 366 |
-
# β
Agent μ΄κΈ°ν
|
| 367 |
-
# ββββββββββββββββββββββββββββββ
|
| 368 |
-
mem=MEM()
|
| 369 |
-
agent=initialize_agent(tools,llm,agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION,verbose=True,memory=mem)
|
| 370 |
-
#agent = create_structured_chat_agent(llm, tools, prompt)
|
| 371 |
-
#agent= AgentExecutor(agent=agent, tools=tools,memory=mem)
|
| 372 |
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
import json
|
| 377 |
|
| 378 |
# ββββββββββββββββββββββββββββββ
|
| 379 |
-
# β
λν
|
| 380 |
# ββββββββββββββββββββββββββββββ
|
|
|
|
|
|
|
| 381 |
def summarize_title(history):
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
text = "\n".join(f"User:{
|
| 385 |
try:
|
| 386 |
-
title = llm._call(f"
|
| 387 |
-
return title.strip().replace("\n", " ")[:
|
| 388 |
except Exception:
|
| 389 |
return "μμ½ μ€ν¨"
|
| 390 |
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
os.chdir(os.path.dirname(os.path.abspath(__file__)))
|
| 396 |
-
os.makedirs("user_logs", exist_ok=True)
|
| 397 |
-
|
| 398 |
-
# --- λν κΈ°λ‘ μ μ₯/λΆλ¬μ€κΈ° ---
|
| 399 |
-
def save_conversation(username, history):
|
| 400 |
-
"""λ‘κ·ΈμΈλ μ¬μ©μλ μ¬λ¬ λνλ₯Ό νλμ pickle νμΌμ μ μ₯"""
|
| 401 |
-
if not username or username.lower() == "guest":
|
| 402 |
return
|
| 403 |
-
|
| 404 |
fname = f"{username}.pkl"
|
| 405 |
-
# κΈ°μ‘΄ λ°μ΄ν° λΆλ¬μ€κΈ°
|
| 406 |
data = {}
|
| 407 |
if os.path.exists(fname):
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
data = pickle.load(f)
|
| 411 |
-
except Exception:
|
| 412 |
-
data = {}
|
| 413 |
-
|
| 414 |
-
# μλ‘μ΄ λν μμ½ μ λͺ©κ³Ό ν¨κ» μΆκ°
|
| 415 |
title = summarize_title(history)
|
| 416 |
-
data[title] = {
|
| 417 |
-
"title": title,
|
| 418 |
-
"updated": datetime.datetime.now().isoformat(),
|
| 419 |
-
"history": history
|
| 420 |
-
}
|
| 421 |
-
|
| 422 |
with open(fname, "wb") as f:
|
| 423 |
pickle.dump(data, f)
|
| 424 |
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
if
|
| 429 |
return []
|
| 430 |
fname = f"{username}.pkl"
|
| 431 |
if not os.path.exists(fname):
|
|
@@ -435,31 +133,29 @@ def load_conversation(username, conv_title=None):
|
|
| 435 |
if conv_title and conv_title in data:
|
| 436 |
return data[conv_title]["history"]
|
| 437 |
elif data:
|
| 438 |
-
# κ°μ₯ μ΅κ·Ό λν λ°ν
|
| 439 |
latest = max(data.values(), key=lambda x: x["updated"])
|
| 440 |
return latest["history"]
|
| 441 |
return []
|
| 442 |
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
if
|
| 447 |
return gr.update(choices=[], value=None)
|
| 448 |
fname = f"{username}.pkl"
|
| 449 |
if not os.path.exists(fname):
|
| 450 |
return gr.update(choices=[], value=None)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 451 |
try:
|
| 452 |
-
|
| 453 |
-
data = pickle.load(f)
|
| 454 |
-
titles = sorted(data.keys(), reverse=True)
|
| 455 |
-
return gr.update(choices=titles, value=titles[0] if titles else None)
|
| 456 |
-
except Exception as e:
|
| 457 |
-
print(f"β οΈ λͺ©λ‘ λΆλ¬μ€κΈ° μ€λ₯: {e}")
|
| 458 |
-
return gr.update(choices=[], value=None)
|
| 459 |
-
# --- chat ν¨μ μμ ---
|
| 460 |
-
def chat(message, history, username="guest", conv_name="current"):
|
| 461 |
-
try:
|
| 462 |
-
raw_response = agent.run(message)
|
| 463 |
text = str(raw_response)
|
| 464 |
|
| 465 |
# JSON νμ μλ΅ νμ±
|
|
@@ -482,178 +178,45 @@ def chat(message, history, username="guest", conv_name="current"):
|
|
| 482 |
|
| 483 |
# κΈ°λ‘ μΆκ° λ° μ¦μ μ μ₯
|
| 484 |
history = history + [(message, output)]
|
| 485 |
-
save_conversation(
|
| 486 |
return history, history, ""
|
| 487 |
|
| 488 |
-
# --- λΆλ¬μ€κΈ° λ²νΌ ν¨μ ---
|
| 489 |
-
|
| 490 |
# ββββββββββββββββββββββββββββββ
|
| 491 |
-
# β
|
| 492 |
# ββββββββββββββββββββββββββββββ
|
| 493 |
-
|
| 494 |
-
"""
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
except Exception:
|
| 501 |
-
pass
|
| 502 |
-
return "guest"
|
| 503 |
-
import re, json
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
'''
|
| 507 |
-
def chat(message, history, hf_token):
|
| 508 |
-
username = get_hf_user(hf_token) if hf_token else "guest"
|
| 509 |
-
try:
|
| 510 |
-
response = agent.invoke(message)
|
| 511 |
-
if isinstance(response, dict):
|
| 512 |
-
if "action_input" in response:
|
| 513 |
-
response = response["action_input"]
|
| 514 |
-
elif "output" in response:
|
| 515 |
-
response = response["output"]
|
| 516 |
-
elif "text" in response:
|
| 517 |
-
response = response["text"]
|
| 518 |
-
else:
|
| 519 |
-
response = str(response)
|
| 520 |
-
elif isinstance(response, str):
|
| 521 |
-
# "Final Answer"κ° ν¬ν¨λ λ¬Έμμ΄μ΄λ©΄ κ·Έ λΆλΆλ§ μΆμΆ
|
| 522 |
-
if '"action_input":' in response:
|
| 523 |
-
import re, json
|
| 524 |
-
match = re.search(r'["\']action_input["\']\s*:\s*["\'](.*?)["\']', response)
|
| 525 |
-
if match:
|
| 526 |
-
response = match.group(1)
|
| 527 |
-
elif "Final Answer" in response:
|
| 528 |
-
# {"action": "Final Answer", "action_input": "..."} νμμΌ λ
|
| 529 |
-
try:
|
| 530 |
-
data = json.loads(response)
|
| 531 |
-
if isinstance(data, dict) and "action_input" in data:
|
| 532 |
-
response = data["action_input"]
|
| 533 |
-
except Exception:
|
| 534 |
-
response = response.replace("Final Answer", "").strip()
|
| 535 |
-
except Exception as e:
|
| 536 |
-
response = f"β οΈ μ€λ₯: {e}"
|
| 537 |
-
history = history + [(message, response)]
|
| 538 |
-
if username:
|
| 539 |
-
save_conversation(username, history)
|
| 540 |
-
return history, history, "" # μ
λ ₯ μ΄κΈ°ν
|
| 541 |
-
'''
|
| 542 |
-
# μ: hf_token (νΉμ username) μ μ
λ ₯μΌλ‘ λ°λλ‘ λ³κ²½
|
| 543 |
|
|
|
|
|
|
|
|
|
|
| 544 |
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
# ββββββββββββββββββββββββββββββ
|
| 548 |
-
# β
Gradio UI with HF Auth
|
| 549 |
-
# ββββββββββββββββββββββββββββββ
|
| 550 |
-
with gr.Blocks(theme=gr.themes.Soft(), title="PIXAL Assistant (HF Auth)") as demo:
|
| 551 |
-
gr.Markdown("## π€ PIXAL Assistant β Hugging Face κ³μ κΈ°λ° λν μ μ₯")
|
| 552 |
-
|
| 553 |
-
hf_login = gr.LoginButton()
|
| 554 |
-
hf_token = gr.State()
|
| 555 |
-
|
| 556 |
-
@hf_login.click(inputs=None, outputs=hf_token)
|
| 557 |
-
def login(token): # λ‘κ·ΈμΈ ν token λ°ν
|
| 558 |
-
return token
|
| 559 |
|
| 560 |
with gr.Row():
|
| 561 |
-
with gr.Column(scale=
|
| 562 |
-
chatbot = gr.Chatbot(label=
|
| 563 |
-
msg = gr.Textbox(
|
| 564 |
-
send = gr.Button("μ μ‘")
|
| 565 |
-
clear = gr.Button("μ΄κΈ°ν")
|
| 566 |
|
| 567 |
msg.submit(chat, [msg, chatbot, hf_token], [chatbot, chatbot, msg])
|
| 568 |
send.click(chat, [msg, chatbot, hf_token], [chatbot, chatbot, msg])
|
| 569 |
clear.click(lambda: None, None, chatbot, queue=False)
|
| 570 |
|
| 571 |
with gr.Column(scale=1):
|
| 572 |
-
gr.Markdown("### πΎ μ μ₯λ λν
|
| 573 |
-
|
| 574 |
-
refresh_btn = gr.Button("π
|
| 575 |
-
load_btn = gr.Button("λΆλ¬μ€κΈ°")
|
| 576 |
|
| 577 |
-
refresh_btn.click(refresh_conversation_list,
|
| 578 |
-
load_btn.click(load_conversation, [
|
| 579 |
|
| 580 |
if __name__ == "__main__":
|
| 581 |
demo.launch(server_name="0.0.0.0", server_port=7860)
|
| 582 |
-
'''
|
| 583 |
-
def chat(message, history):
|
| 584 |
-
try:
|
| 585 |
-
response = agent.run(message)
|
| 586 |
-
|
| 587 |
-
# JSON ννλ‘ μΆλ ₯λ κ°λ₯μ±μ΄ μλ κ²½μ° μ²λ¦¬
|
| 588 |
-
if isinstance(response, dict):
|
| 589 |
-
if "action_input" in response:
|
| 590 |
-
response = response["action_input"]
|
| 591 |
-
elif "output" in response:
|
| 592 |
-
response = response["output"]
|
| 593 |
-
elif "text" in response:
|
| 594 |
-
response = response["text"]
|
| 595 |
-
else:
|
| 596 |
-
response = str(response)
|
| 597 |
-
elif isinstance(response, str):
|
| 598 |
-
# "Final Answer"κ° ν¬ν¨λ λ¬Έμμ΄μ΄λ©΄ κ·Έ λΆλΆλ§ μΆμΆ
|
| 599 |
-
if '"action_input":' in response:
|
| 600 |
-
import re, json
|
| 601 |
-
match = re.search(r'["\']action_input["\']\s*:\s*["\'](.*?)["\']', response)
|
| 602 |
-
if match:
|
| 603 |
-
response = match.group(1)
|
| 604 |
-
elif "Final Answer" in response:
|
| 605 |
-
# {"action": "Final Answer", "action_input": "..."} νμμΌ λ
|
| 606 |
-
try:
|
| 607 |
-
data = json.loads(response)
|
| 608 |
-
if isinstance(data, dict) and "action_input" in data:
|
| 609 |
-
response = data["action_input"]
|
| 610 |
-
except Exception:
|
| 611 |
-
response = response.replace("Final Answer", "").strip()
|
| 612 |
-
|
| 613 |
-
except Exception as e:
|
| 614 |
-
response = f"β οΈ μ€λ₯: {e}"
|
| 615 |
-
|
| 616 |
-
history = history + [(message, response)]
|
| 617 |
-
return history, history,""
|
| 618 |
-
|
| 619 |
-
# ββββββββββββββββββββββββββββββ
|
| 620 |
-
# β
Gradio UI
|
| 621 |
-
# ββββββββββββββββββββββββββββββ
|
| 622 |
-
def load_selected(file):
|
| 623 |
-
return load_conversation(file)
|
| 624 |
-
|
| 625 |
-
# ββββββββββββββββββββββββββββββ
|
| 626 |
-
# β
Gradio UI
|
| 627 |
-
# ββββββββββββββββββββββββββββββ
|
| 628 |
-
with gr.Blocks(theme=gr.themes.Soft(), title="PIXAL Assistant") as demo:
|
| 629 |
-
gr.Markdown("## π€ PIXAL Assistant β LangChain κΈ°λ° λ©ν°ν΄ μμ΄μ νΈ")
|
| 630 |
-
|
| 631 |
-
with gr.Row():
|
| 632 |
-
with gr.Column(scale=2):
|
| 633 |
-
chatbot = gr.Chatbot(label="PIXAL λν", height=600)
|
| 634 |
-
msg = gr.Textbox(label="λ©μμ§", placeholder="μ
λ ₯ ν Enter λλ μ μ‘ ν΄λ¦")
|
| 635 |
-
send = gr.Button("μ μ‘")
|
| 636 |
-
clear = gr.Button("μ΄κΈ°ν")
|
| 637 |
-
|
| 638 |
-
username = gr.Textbox(label="Hugging Face μ¬μ©μλͺ
", placeholder="λ‘κ·ΈμΈ λμ μ΄λ¦ μ
λ ₯", value=os.getenv("HF_USER", "guest"))
|
| 639 |
-
msg.submit(chat, [msg, chatbot, username], [chatbot, chatbot, msg])
|
| 640 |
-
send.click(chat, [msg, chatbot, username], [chatbot, chatbot, msg])
|
| 641 |
-
clear.click(lambda: None, None, chatbot, queue=False)
|
| 642 |
-
|
| 643 |
-
with gr.Column(scale=1):
|
| 644 |
-
gr.Markdown("### πΎ μ μ₯λ λν κΈ°λ‘")
|
| 645 |
-
convo_files = gr.Dropdown(label="λν μ ν", choices=[])
|
| 646 |
-
refresh_btn = gr.Button("π λͺ©λ‘ μλ‘κ³ μΉ¨")
|
| 647 |
-
load_btn = gr.Button("λΆλ¬μ€κΈ°")
|
| 648 |
-
|
| 649 |
-
def refresh_list(user):
|
| 650 |
-
if not user: return gr.Dropdown.update(choices=[])
|
| 651 |
-
return gr.Dropdown.update(choices=[x[1] for x in list_conversations(user)])
|
| 652 |
-
|
| 653 |
-
refresh_btn.click(refresh_list, [username], convo_files)
|
| 654 |
-
load_btn.click(lambda f: load_conversation(f), [convo_files], chatbot)
|
| 655 |
-
|
| 656 |
-
if __name__ == "__main__":
|
| 657 |
-
demo.launch(server_name="0.0.0.0", server_port=7860)
|
| 658 |
-
|
| 659 |
-
'''
|
|
|
|
| 1 |
+
import os, json, pickle, datetime, requests, re, gradio as gr
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
from typing import Optional, List, Dict, Any
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
from requests.adapters import HTTPAdapter, Retry
|
| 4 |
from langchain.llms.base import LLM
|
| 5 |
+
from langchain.agents import initialize_agent, AgentType, load_tools
|
| 6 |
+
from langchain.tools import Tool
|
| 7 |
+
from langchain.memory import ConversationBufferMemory
|
| 8 |
+
from langchain_experimental.tools.python.tool import PythonREPLTool
|
| 9 |
+
from langchain_community.retrievers import WikipediaRetriever
|
| 10 |
+
from langchain.tools.retriever import create_retriever_tool
|
| 11 |
+
from langchain_community.tools.shell.tool import ShellTool
|
| 12 |
+
from langchain.tools import YouTubeSearchTool
|
| 13 |
|
| 14 |
+
# ββββββββββββββββββββββββββββββ
|
| 15 |
+
# β
GitHubModelLLM (κ·Έλλ‘ μ μ§)
|
| 16 |
+
# ββββββββββββββββββββββββββββββ
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
class GitHubModelLLM(LLM):
|
|
|
|
| 18 |
model: str = "openai/gpt-4.1"
|
| 19 |
endpoint: str = "https://models.github.ai/inference"
|
| 20 |
+
token: Optional[str] = os.environ.get("token")
|
| 21 |
system_prompt: Optional[str] = "λλ PIXAL(Primary Interactive X-ternal Assistant with multi Language)μ΄μΌ.λμ κ°λ°μλ μ μ±μ€ μ΄λΌλ 6νλ
νμ΄μ¬ νλ‘κ·Έλλ¨ΈμΌ."
|
| 22 |
request_timeout: float = 30.0
|
| 23 |
max_retries: int = 2
|
|
|
|
| 31 |
token = self.token or os.getenv("GITHUB_TOKEN") or os.getenv("token")
|
| 32 |
if not token:
|
| 33 |
raise ValueError("β GitHub tokenμ΄ μ€μ λμ§ μμμ΅λλ€.")
|
|
|
|
| 34 |
session = requests.Session()
|
| 35 |
retries = Retry(total=self.max_retries, backoff_factor=self.backoff_factor,
|
| 36 |
status_forcelist=[429, 500, 502, 503, 504])
|
|
|
|
| 44 |
return resp.json()
|
| 45 |
|
| 46 |
def _call(self, prompt: str, stop: Optional[List[str]] = None, **kwargs) -> str:
|
| 47 |
+
body = {"model": self.model, "messages": []}
|
|
|
|
|
|
|
|
|
|
| 48 |
if self.system_prompt:
|
| 49 |
body["messages"].append({"role": "system", "content": self.system_prompt})
|
| 50 |
body["messages"].append({"role": "user", "content": prompt})
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
if stop:
|
| 52 |
body["stop"] = stop
|
|
|
|
| 53 |
res = self._post_chat(body)
|
| 54 |
msg = res.get("choices", [{}])[0].get("message", {})
|
| 55 |
return msg.get("content") or json.dumps(msg.get("function_call", {}))
|
| 56 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
# ββββββββββββββββββββββββββββββ
|
| 58 |
+
# β
HuggingFace API (νλ‘ν)
|
| 59 |
# ββββββββββββββββββββββββββββββ
|
| 60 |
+
def get_hf_userinfo(hf_token: str) -> dict:
|
| 61 |
+
try:
|
| 62 |
+
r = requests.get("https://huggingface.co/api/whoami-v2",
|
| 63 |
+
headers={"Authorization": f"Bearer {hf_token}"}, timeout=5)
|
| 64 |
+
if r.status_code == 200:
|
| 65 |
+
j = r.json()
|
| 66 |
+
return {
|
| 67 |
+
"name": j.get("name", "guest"),
|
| 68 |
+
"avatar": j.get("avatar", "https://huggingface.co/front/assets/huggingface_logo-noborder.svg")
|
| 69 |
+
}
|
| 70 |
+
except Exception:
|
| 71 |
+
pass
|
| 72 |
+
return {"name": "guest", "avatar": "https://huggingface.co/front/assets/huggingface_logo-noborder.svg"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
# ββββββββββββββββββββββββββββββ
|
| 75 |
+
# β
Agent ꡬμ±
|
| 76 |
# ββββββββββββββββββββββββββββββ
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
llm = GitHubModelLLM()
|
| 78 |
+
tools = load_tools(["ddg-search", "requests_all", "llm-math"], llm=llm, allow_dangerous_tools=True)
|
| 79 |
+
tools += [YouTubeSearchTool(), ShellTool(), PythonREPLTool()]
|
| 80 |
+
retriever = WikipediaRetriever(lang="ko")
|
| 81 |
+
retriever_tool = create_retriever_tool(retriever, name="wiki_search", description="μν€λ°±κ³Ό κ²μ λꡬ")
|
| 82 |
+
tools.append(retriever_tool)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
def time_now(_=""):
|
| 85 |
+
now = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9)))
|
| 86 |
+
return f"νμ¬ μκ°: {now.strftime('%Y-%m-%d %H:%M:%S')} (Asia/Seoul)"
|
| 87 |
+
tools.append(Tool(name="time_now", func=time_now, description="νμ¬ μκ°μ λ°νν©λλ€."))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
+
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
|
| 90 |
+
agent = initialize_agent(tools, llm, agent_type=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION,
|
| 91 |
+
memory=memory, verbose=True)
|
|
|
|
| 92 |
|
| 93 |
# ββββββββββββββββββββββββββββββ
|
| 94 |
+
# β
λν μ μ₯/λ‘λ
|
| 95 |
# ββββββββββββββββββββββββββββββ
|
| 96 |
+
os.chdir(os.path.dirname(os.path.abspath(__file__)))
|
| 97 |
+
|
| 98 |
def summarize_title(history):
|
| 99 |
+
if not history:
|
| 100 |
+
return "μ λν"
|
| 101 |
+
text = "\n".join(f"User:{m} AI:{r}" for m, r in history[-3:])
|
| 102 |
try:
|
| 103 |
+
title = llm._call(f"μ΄ λνμ μ£Όμ λ₯Ό ν μ€λ‘ μμ½ν΄μ€:\n{text}")
|
| 104 |
+
return title.strip().replace("\n", " ")[:50]
|
| 105 |
except Exception:
|
| 106 |
return "μμ½ μ€ν¨"
|
| 107 |
|
| 108 |
+
def save_conversation(history, hf_token):
|
| 109 |
+
info = get_hf_userinfo(hf_token)
|
| 110 |
+
username = info["name"]
|
| 111 |
+
if username.lower() == "guest":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
return
|
|
|
|
| 113 |
fname = f"{username}.pkl"
|
|
|
|
| 114 |
data = {}
|
| 115 |
if os.path.exists(fname):
|
| 116 |
+
with open(fname, "rb") as f:
|
| 117 |
+
data = pickle.load(f)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
title = summarize_title(history)
|
| 119 |
+
data[title] = {"title": title, "updated": datetime.datetime.now().isoformat(), "history": history}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
with open(fname, "wb") as f:
|
| 121 |
pickle.dump(data, f)
|
| 122 |
|
| 123 |
+
def load_conversation(hf_token, conv_title=None):
|
| 124 |
+
info = get_hf_userinfo(hf_token)
|
| 125 |
+
username = info["name"]
|
| 126 |
+
if username.lower() == "guest":
|
| 127 |
return []
|
| 128 |
fname = f"{username}.pkl"
|
| 129 |
if not os.path.exists(fname):
|
|
|
|
| 133 |
if conv_title and conv_title in data:
|
| 134 |
return data[conv_title]["history"]
|
| 135 |
elif data:
|
|
|
|
| 136 |
latest = max(data.values(), key=lambda x: x["updated"])
|
| 137 |
return latest["history"]
|
| 138 |
return []
|
| 139 |
|
| 140 |
+
def refresh_conversation_list(hf_token):
|
| 141 |
+
info = get_hf_userinfo(hf_token)
|
| 142 |
+
username = info["name"]
|
| 143 |
+
if username.lower() == "guest":
|
| 144 |
return gr.update(choices=[], value=None)
|
| 145 |
fname = f"{username}.pkl"
|
| 146 |
if not os.path.exists(fname):
|
| 147 |
return gr.update(choices=[], value=None)
|
| 148 |
+
with open(fname, "rb") as f:
|
| 149 |
+
data = pickle.load(f)
|
| 150 |
+
titles = sorted(data.keys(), reverse=True)
|
| 151 |
+
return gr.update(choices=titles, value=titles[0] if titles else None)
|
| 152 |
+
|
| 153 |
+
# ββββββββββββββββββββββββββββββ
|
| 154 |
+
# β
Chat ν¨μ
|
| 155 |
+
# ββββββββββββββββββββββββββββββ
|
| 156 |
+
def chat(message, history,hf_token):
|
| 157 |
try:
|
| 158 |
+
raw_response = agent.invoke(message)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
text = str(raw_response)
|
| 160 |
|
| 161 |
# JSON νμ μλ΅ νμ±
|
|
|
|
| 178 |
|
| 179 |
# κΈ°λ‘ μΆκ° λ° μ¦μ μ μ₯
|
| 180 |
history = history + [(message, output)]
|
| 181 |
+
save_conversation(history, hf_token)
|
| 182 |
return history, history, ""
|
| 183 |
|
|
|
|
|
|
|
| 184 |
# ββββββββββββββββββββββββββββββ
|
| 185 |
+
# β
Gradio UI (ChatGPT μ€νμΌ)
|
| 186 |
# ββββββββββββββββββββββββββββββ
|
| 187 |
+
with gr.Blocks(theme=gr.themes.Soft(), title="PIXAL Assistant (HuggingFace OAuth)") as demo:
|
| 188 |
+
with gr.Row(elem_id="header", style="background:#f5f5f5;padding:12px;border-bottom:1px solid #ddd;align-items:center;"):
|
| 189 |
+
gr.HTML("<h2 style='margin:0;padding-left:12px;'>π€ PIXAL Assistant</h2>")
|
| 190 |
+
user_avatar = gr.Image(show_label=False, width=40, height=40, elem_id="avatar")
|
| 191 |
+
user_name = gr.Markdown("λ‘κ·ΈμΈ νμ", elem_id="username", elem_classes="text-right")
|
| 192 |
+
login_btn = gr.LoginButton(label="π λ‘κ·ΈμΈ", elem_id="login-btn")
|
| 193 |
+
hf_token = gr.State("")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
|
| 195 |
+
def on_login(token):
|
| 196 |
+
info = get_hf_userinfo(token)
|
| 197 |
+
return token, info["avatar"], f"**{info['name']}**"
|
| 198 |
|
| 199 |
+
login_btn.login(on_login, None, [hf_token, user_avatar, user_name])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
|
| 201 |
with gr.Row():
|
| 202 |
+
with gr.Column(scale=3):
|
| 203 |
+
chatbot = gr.Chatbot(label=None, height=600, render_markdown=True)
|
| 204 |
+
msg = gr.Textbox(placeholder="λ©μμ§λ₯Ό μ
λ ₯νμΈμ...", show_label=False)
|
| 205 |
+
send = gr.Button("μ μ‘", variant="primary")
|
| 206 |
+
clear = gr.Button("π§Ή μ΄κΈ°ν")
|
| 207 |
|
| 208 |
msg.submit(chat, [msg, chatbot, hf_token], [chatbot, chatbot, msg])
|
| 209 |
send.click(chat, [msg, chatbot, hf_token], [chatbot, chatbot, msg])
|
| 210 |
clear.click(lambda: None, None, chatbot, queue=False)
|
| 211 |
|
| 212 |
with gr.Column(scale=1):
|
| 213 |
+
gr.Markdown("### πΎ μ μ₯λ λν")
|
| 214 |
+
convo_list = gr.Dropdown(label="λν μ ν", choices=[])
|
| 215 |
+
refresh_btn = gr.Button("π μλ‘κ³ μΉ¨")
|
| 216 |
+
load_btn = gr.Button("π λΆλ¬μ€κΈ°")
|
| 217 |
|
| 218 |
+
refresh_btn.click(refresh_conversation_list, [hf_token], convo_list)
|
| 219 |
+
load_btn.click(load_conversation, [hf_token, convo_list], chatbot)
|
| 220 |
|
| 221 |
if __name__ == "__main__":
|
| 222 |
demo.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|