igorpavlov-mgr commited on
Commit
819ca5d
·
verified ·
1 Parent(s): 16a483a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -53
app.py CHANGED
@@ -1,64 +1,66 @@
1
- import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- 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
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
 
26
- messages.append({"role": "user", "content": message})
 
 
27
 
28
- response = ""
 
 
 
 
 
 
 
 
 
 
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
 
39
- response += token
40
- yield response
 
 
 
 
 
 
 
41
 
 
 
 
 
 
 
 
 
 
 
42
 
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
  )
61
 
62
-
63
  if __name__ == "__main__":
64
- demo.launch()
 
 
 
 
 
 
 
 
 
1
 
2
+ import os
3
+ import requests
4
+ from bs4 import BeautifulSoup
5
+ import gradio as gr
6
+ from langchain_cohere import ChatCohere
7
+ from langchain_core.messages import HumanMessage, SystemMessage
8
+ from langfuse import Langfuse
9
+ from langfuse.callback import CallbackHandler
10
+ from langchain.callbacks.manager import CallbackManager
11
 
12
+ # ENV VARS must be set in Hugging Face Space settings for API key and Langfuse
13
+ api_key = os.environ.get("COHERE_API_KEY")
14
+ langfuse_public_key = os.environ.get("LANGFUSE_PUBLIC_KEY")
15
+ langfuse_secret_key = os.environ.get("LANGFUSE_SECRET_KEY")
 
16
 
17
+ os.environ["LANGFUSE_PUBLIC_KEY"] = langfuse_public_key
18
+ os.environ["LANGFUSE_SECRET_KEY"] = langfuse_secret_key
19
+ os.environ["LANGFUSE_HOST"] = "https://cloud.langfuse.com"
20
 
21
+ # Load policy content from Cohere Docs
22
+ def fetch_policy():
23
+ url = "https://docs.cohere.com/docs/cohere-labs-acceptable-use-policy"
24
+ try:
25
+ response = requests.get(url, timeout=10)
26
+ response.raise_for_status()
27
+ soup = BeautifulSoup(response.text, "html.parser")
28
+ content_div = soup.find("div", class_="markdown") or soup.find("main") or soup
29
+ return content_div.get_text(separator="\n").strip()[:1500]
30
+ except Exception as e:
31
+ return "⚠️ Failed to retrieve policy. " + str(e)
32
 
33
+ context = fetch_policy()
 
 
 
 
 
 
 
34
 
35
+ # Setup Langfuse and LLM
36
+ langfuse_callback = CallbackHandler()
37
+ llm = ChatCohere(
38
+ cohere_api_key=api_key,
39
+ model="command-r-plus",
40
+ callback_manager=CallbackManager([langfuse_callback]),
41
+ verbose=True,
42
+ )
43
+ langfuse = Langfuse()
44
 
45
+ def run_policy_check(query: str):
46
+ trace = langfuse.trace(name="RAG_CommandRPlus_Trace", user_id="huggingface-demo")
47
+ messages = [
48
+ SystemMessage(content=f"This is the policy context from Cohere:\n{context}"),
49
+ HumanMessage(content=query),
50
+ ]
51
+ response = llm.invoke(messages)
52
+ trace.score(name="response_quality", value=1)
53
+ trace.update(status="completed")
54
+ return response.content
55
 
56
+ # Gradio interface
57
+ demo = gr.Interface(
58
+ fn=run_policy_check,
59
+ inputs=gr.Textbox(label="Ask a question about acceptable use of Command R+", lines=3),
60
+ outputs=gr.Textbox(label="Cohere Command R+ Answer"),
61
+ title="Policy QA with Cohere Command R+",
62
+ description="This agent retrieves the Cohere Acceptable Use Policy and answers your ethical use-case questions using LangChain + Command R+.",
 
 
 
 
 
 
 
 
 
 
63
  )
64
 
 
65
  if __name__ == "__main__":
66
+ demo.launch()