KingZack commited on
Commit
60e794c
·
1 Parent(s): 747b9f1

updating with requests and hfh

Browse files
Files changed (2) hide show
  1. app.py +67 -47
  2. requirements.txt +1 -0
app.py CHANGED
@@ -1,58 +1,78 @@
1
  """
2
- Hugging Face Space entrypoint: Gradio UI + requests to OpenAI Chat Completions.
3
-
4
- Secrets: Space → Settings → Variables and secrets → add secret OPENAI_API_KEY.
5
- Do not put API keys in code or in git; HF injects secrets as environment variables.
6
  """
7
 
8
  import os
9
 
10
  import gradio as gr
11
  import requests
 
12
 
13
- import gradio as gr
 
14
 
15
- def greet(name):
16
- return "Hello " + name + "!!"
17
 
18
- demo = gr.Interface(fn=greet, inputs="text", outputs="text")
19
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
- # # Chat Completions HTTP API (same thing the official Python SDK calls under the hood).
22
- # URL = "https://api.openai.com/v1/chat/completions"
23
-
24
-
25
- # def ask(question: str) -> str:
26
- # # HF Spaces: add OPENAI_API_KEY under Space Settings Variables and secrets.
27
- # key = os.environ.get("OPENAI_API_KEY", "").strip()
28
- # if not key:
29
- # return "Missing secret: add OPENAI_API_KEY in this Space’s Settings → Variables and secrets, then restart if needed."
30
-
31
- # # Plain HTTP: Bearer token + JSON body. Easy to show students in Network tab / docs.
32
- # resp = requests.post(
33
- # URL,
34
- # headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"},
35
- # json={
36
- # "model": "gpt-4o-mini",
37
- # "messages": [{"role": "user", "content": question}],
38
- # },
39
- # timeout=120,
40
- # )
41
- # try:
42
- # resp.raise_for_status()
43
- # except requests.HTTPError:
44
- # return f"HTTP {resp.status_code}: {resp.text[:500]}"
45
-
46
- # data = resp.json()
47
- # return data["choices"][0]["message"]["content"]
48
-
49
-
50
- # demo = gr.Interface(
51
- # fn=ask,
52
- # inputs=gr.Textbox(label="Question", lines=3),
53
- # outputs=gr.Textbox(label="Answer", lines=12),
54
- # title="Ask OpenAI (via requests)",
55
- # )
56
-
57
- # if __name__ == "__main__":
58
- # demo.launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", 7860)))
 
1
  """
2
+ Gradio Space: ask OpenAI Chat Completions in two boring ways — raw HTTP (`requests`)
3
+ and Hugging Face (`huggingface_hub.InferenceClient`). Put OPENAI_API_KEY in Space secrets.
 
 
4
  """
5
 
6
  import os
7
 
8
  import gradio as gr
9
  import requests
10
+ from huggingface_hub import InferenceClient
11
 
12
+ # Pick any model name your OpenAI key is allowed to call.
13
+ MODEL = "gpt-5-nano"
14
 
 
 
15
 
16
+ def ask_with_requests(question: str) -> str:
17
+ """
18
+ Path 1: build the HTTP request yourself.
19
+
20
+ - URL + JSON body match OpenAI's REST docs for Chat Completions.
21
+ - `Authorization: Bearer …` is how OpenAI expects the API key.
22
+ """
23
+ key = os.environ["OPENAI_API_KEY"]
24
+
25
+ response = requests.post(
26
+ "https://api.openai.com/v1/chat/completions",
27
+ headers={
28
+ "Authorization": f"Bearer {key}",
29
+ "Content-Type": "application/json",
30
+ },
31
+ json={
32
+ "model": MODEL,
33
+ "messages": [{"role": "user", "content": question}],
34
+ },
35
+ timeout=120,
36
+ )
37
+ response.raise_for_status()
38
+ data = response.json()
39
+ return data["choices"][0]["message"]["content"]
40
+
41
 
42
+ def ask_with_huggingface_hub(question: str) -> str:
43
+ """
44
+ Path 2: let `huggingface_hub` speak OpenAI-style Chat Completions.
45
+
46
+ `InferenceClient.chat.completions.create(...)` is documented to follow the same idea as
47
+ OpenAI's SDK; here we aim it at OpenAI by setting `base_url` to OpenAI's `/v1` root.
48
+ """
49
+ client = InferenceClient(
50
+ base_url="https://api.openai.com/v1",
51
+ api_key=os.environ["OPENAI_API_KEY"],
52
+ )
53
+
54
+ completion = client.chat.completions.create(
55
+ model=MODEL,
56
+ messages=[{"role": "user", "content": question}],
57
+ )
58
+ return completion.choices[0].message.content
59
+
60
+
61
+ demo = gr.TabbedInterface(
62
+ [
63
+ gr.Interface(
64
+ fn=ask_with_requests,
65
+ inputs=gr.Textbox(label="Question", lines=3),
66
+ outputs=gr.Textbox(label="Answer", lines=12),
67
+ ),
68
+ gr.Interface(
69
+ fn=ask_with_huggingface_hub,
70
+ inputs=gr.Textbox(label="Question", lines=3),
71
+ outputs=gr.Textbox(label="Answer", lines=12),
72
+ ),
73
+ ],
74
+ tab_names=["requests", "huggingface_hub"],
75
+ title="Ask OpenAI (two simple clients)",
76
+ )
77
+
78
+ demo.launch()
 
requirements.txt CHANGED
@@ -1,2 +1,3 @@
1
  gradio
2
  requests
 
 
1
  gradio
2
  requests
3
+ huggingface_hub>=0.26.0