Update app.py
Browse files123453 unmodified lines91011121314151617181920212223242526272829303132333435363738394041424323 unmodified lines67686970import gradio as grfrom huggingface_hub import InferenceClientdef respond(3 unmodified linesmax_tokens,temperature,top_p,hf_token: gr.OAuthToken,):"""For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference"""client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")messages = [{"role": "system", "content": system_message}]messages.extend(history)messages.append({"role": "user", "content": message})response = ""for message in client.chat_completion(messages,max_tokens=max_tokens,stream=True,temperature=temperature,top_p=top_p,):choices = message.choicestoken = ""if len(choices) and choices[0].delta.content:token = choices[0].delta.contentresponse += tokenyield response"""23 unmodified linesif __name__ == "__main__":demo.launch()12345673 unmodified lines1112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676823 unmodified lines92939495import gradio as grimport requests # NEW: for calling the n8n webhookWEBHOOK_URL = "PUT YOUR URL HERE"def respond(3 unmodified linesmax_tokens,temperature,top_p,hf_token: gr.OAuthToken, # still here so LoginButton works, but not used for auth downstream):"""This function sends the chat state to an n8n webhook and streamsback the response text.Expected n8n behaviour:- Receive JSON with fields: message, history, system_message, max_tokens, temperature, top_p, user- Return either:{ "reply": "<assistant reply text>" }or any JSON with a text-like field, or plain text."""payload = {"message": message,"history": history,"system_message": system_message,"max_tokens": max_tokens,"temperature": temperature,"top_p": top_p,# optional: pass along HF user info if you want to use it in n8n"user": getattr(hf_token, "username", None) if hf_token is not None else None,}try:response = requests.post(WEBHOOK_URL, json=payload, timeout=120)response.raise_for_status()except Exception as e:error_text = f"Error contacting backend: {e}"# stream the error as a single messageyield error_textreturn# Try to parse JSON, but fall back to raw text if neededtry:data = response.json()reply = (data.get("reply")or data.get("message")or data.get("content")or data.get("text"))if reply is None:reply = str(data)except Exception:reply = response.text# Stream reply token-by-token (character-by-character) to Gradioaccumulated = ""for ch in reply:accumulated += chyield accumulated"""23 unmodified linesif __name__ == "__main__":demo.queue().launch()
app.py+49-24