Andrew Tanny Liem commited on
Commit
a4582fe
·
1 Parent(s): ef5c937

update app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -19
app.py CHANGED
@@ -6,6 +6,7 @@ import gradio as gr
6
  from huggingface_hub import InferenceClient
7
 
8
 
 
9
  HF_MODEL = os.getenv("HF_MODEL", "openai/gpt-oss-20b")
10
 
11
 
@@ -78,28 +79,66 @@ def _oauth_or_env_token(hf_token: gr.OAuthToken | None):
78
  return os.getenv("HF_TOKEN")
79
 
80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  def bot_reply(history: List[Tuple[str, str]], temperature: float = 0.7, top_p: float = 0.95, max_tokens: int = 512, hf_token: gr.OAuthToken = None):
82
  last_user = history[-1][0] if history else ""
83
  messages = _build_messages(history[:-1], last_user)
84
- client = InferenceClient(token=_oauth_or_env_token(hf_token), model=HF_MODEL)
 
85
 
86
  acc = ""
87
- for event in client.chat_completion(
88
- messages,
89
- max_tokens=max_tokens,
90
- stream=True,
91
- temperature=temperature,
92
- top_p=top_p,
93
- ):
94
- token = ""
95
- try:
96
- choices = event.choices
97
- if len(choices) and getattr(choices[0], "delta", None) and choices[0].delta.content:
98
- token = choices[0].delta.content
99
- except Exception:
100
- pass
101
- acc += token
102
- history[-1] = (history[-1][0], acc)
 
 
 
 
 
 
 
 
 
 
 
103
  yield history
104
 
105
 
@@ -108,7 +147,8 @@ def summarize(history: List[Tuple[str, str]], hf_token: gr.OAuthToken = None):
108
  if not transcript.strip():
109
  return {"note": "No conversation yet. Ask Maya some questions first."}
110
 
111
- client = InferenceClient(token=_oauth_or_env_token(hf_token), model=HF_MODEL)
 
112
  messages = [
113
  {"role": "system", "content": SUMMARY_SYSTEM_PROMPT},
114
  {
@@ -120,7 +160,18 @@ def summarize(history: List[Tuple[str, str]], hf_token: gr.OAuthToken = None):
120
  },
121
  ]
122
  # Non-streaming summarize for simplicity
123
- event = client.chat_completion(messages, max_tokens=1024, stream=False, temperature=0.2, top_p=0.95)
 
 
 
 
 
 
 
 
 
 
 
124
  # Extract content
125
  text = "{}"
126
  try:
 
6
  from huggingface_hub import InferenceClient
7
 
8
 
9
+ # Default to GPT-OSS per your preference
10
  HF_MODEL = os.getenv("HF_MODEL", "openai/gpt-oss-20b")
11
 
12
 
 
79
  return os.getenv("HF_TOKEN")
80
 
81
 
82
+ def _provider_for_model(model_id: str) -> str | None:
83
+ # Route provider explicitly when needed
84
+ if model_id.startswith("openai/"):
85
+ return "together"
86
+ return None
87
+
88
+
89
+ def _provider_api_key(model_id: str) -> str | None:
90
+ prov = _provider_for_model(model_id)
91
+ if prov == "together":
92
+ return os.getenv("TOGETHER_API_KEY")
93
+ return None
94
+
95
+
96
+ def _inference_params(hf_token: gr.OAuthToken | None, model_id: str):
97
+ provider = _provider_for_model(model_id)
98
+ api_key = _provider_api_key(model_id)
99
+ # Important: when using external providers (e.g., Together), do NOT pass HF OAuth/token,
100
+ # otherwise the router attempts a delegated call and may 403.
101
+ if provider:
102
+ token = None
103
+ else:
104
+ token = _oauth_or_env_token(hf_token)
105
+ return token, provider, api_key
106
+
107
+
108
  def bot_reply(history: List[Tuple[str, str]], temperature: float = 0.7, top_p: float = 0.95, max_tokens: int = 512, hf_token: gr.OAuthToken = None):
109
  last_user = history[-1][0] if history else ""
110
  messages = _build_messages(history[:-1], last_user)
111
+ token, provider, api_key = _inference_params(hf_token, HF_MODEL)
112
+ client = InferenceClient(token=token, model=HF_MODEL)
113
 
114
  acc = ""
115
+ try:
116
+ for event in client.chat_completion(
117
+ messages,
118
+ max_tokens=max_tokens,
119
+ stream=True,
120
+ temperature=temperature,
121
+ top_p=top_p,
122
+ provider=provider,
123
+ api_key=api_key,
124
+ ):
125
+ token = ""
126
+ try:
127
+ choices = event.choices
128
+ if len(choices) and getattr(choices[0], "delta", None) and choices[0].delta.content:
129
+ token = choices[0].delta.content
130
+ except Exception:
131
+ pass
132
+ acc += token
133
+ history[-1] = (history[-1][0], acc)
134
+ yield history
135
+ except Exception as e:
136
+ err = (
137
+ f"[Model error] {type(e).__name__}: {e}.\n"
138
+ "Tip: Click Sign in or set HF_TOKEN.\n"
139
+ "You can also set HF_MODEL to an HF-hosted chat model, e.g. 'meta-llama/Meta-Llama-3-8B-Instruct' or 'HuggingFaceH4/zephyr-7b-beta'."
140
+ )
141
+ history[-1] = (history[-1][0], err)
142
  yield history
143
 
144
 
 
147
  if not transcript.strip():
148
  return {"note": "No conversation yet. Ask Maya some questions first."}
149
 
150
+ token, provider, api_key = _inference_params(hf_token, HF_MODEL)
151
+ client = InferenceClient(token=token, model=HF_MODEL)
152
  messages = [
153
  {"role": "system", "content": SUMMARY_SYSTEM_PROMPT},
154
  {
 
160
  },
161
  ]
162
  # Non-streaming summarize for simplicity
163
+ try:
164
+ event = client.chat_completion(
165
+ messages,
166
+ max_tokens=1024,
167
+ stream=False,
168
+ temperature=0.2,
169
+ top_p=0.95,
170
+ provider=provider,
171
+ api_key=api_key,
172
+ )
173
+ except Exception as e:
174
+ return {"error": f"{type(e).__name__}: {e}"}
175
  # Extract content
176
  text = "{}"
177
  try: