MJannik commited on
Commit
bd91e63
·
verified ·
1 Parent(s): ab42154

initial commit

Browse files
Files changed (1) hide show
  1. app.py +109 -0
app.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import json
3
+ import uuid
4
+ from langfuse import Langfuse
5
+ import os
6
+
7
+ os.environ["LANGFUSE_PUBLIC_KEY"] = os.getenv('LANGFUSE_PUBLIC_KEY')
8
+ os.environ["LANGFUSE_SECRET_KEY"] = os.getenv('LANGFUSE_SECRET_KEY')
9
+ os.environ["LANGFUSE_HOST"] = os.getenv('LANGFUSE_HOST')
10
+
11
+ os.environ["OPENAI_API_KEY"] = os.getenv('OPENAI_API_KEY')
12
+
13
+ langfuse = Langfuse()
14
+
15
+ session_id = None
16
+ def set_new_session_id():
17
+ global session_id
18
+ session_id = str(uuid.uuid4())
19
+
20
+ # Initialize
21
+ set_new_session_id()
22
+
23
+ # Langfuse decorator
24
+ from langfuse.decorators import observe, langfuse_context
25
+ # Optional: automated instrumentation via OpenAI SDK integration
26
+ # See note above regarding alternative implementations
27
+ from langfuse.openai import openai
28
+
29
+ # Global reference for the current trace_id which is used to later add user feedback
30
+ current_trace_id = None
31
+
32
+ # Add decorator here to capture overall timings, input/output, and manipulate trace metadata via `langfuse_context`
33
+ @observe()
34
+ async def create_response(
35
+ prompt: str,
36
+ history,
37
+ ):
38
+ # Save trace id in global var to add feedback later
39
+ global current_trace_id
40
+ current_trace_id = langfuse_context.get_current_trace_id()
41
+
42
+ # Add session_id to Langfuse Trace to enable session tracking
43
+ global session_id
44
+ langfuse_context.update_current_trace(
45
+ name="gradio_demo_chat",
46
+ session_id=session_id,
47
+ input=prompt,
48
+ )
49
+
50
+ # Add prompt to history
51
+ if not history:
52
+ history = [{"role": "system", "content": "You are a friendly chatbot"}]
53
+ history.append({"role": "user", "content": prompt})
54
+ yield history
55
+
56
+ # Get completion via OpenAI SDK
57
+ # Auto-instrumented by Langfuse via the import, see alternative in note above
58
+ response = {"role": "assistant", "content": ""}
59
+ oai_response = openai.chat.completions.create(
60
+ messages=history,
61
+ model="gpt-4o-mini",
62
+ )
63
+ response["content"] = oai_response.choices[0].message.content or ""
64
+
65
+ # Customize trace ouput for better readability in Langfuse Sessions
66
+ langfuse_context.update_current_trace(
67
+ output=response["content"],
68
+ )
69
+
70
+ yield history + [response]
71
+
72
+ async def respond(prompt: str, history):
73
+ async for message in create_response(prompt, history):
74
+ yield message
75
+
76
+ def handle_like(data: gr.LikeData):
77
+ global current_trace_id
78
+ if data.liked:
79
+ langfuse.score(value=1, name="user-feedback", trace_id=current_trace_id)
80
+ else:
81
+ langfuse.score(value=0, name="user-feedback", trace_id=current_trace_id)
82
+
83
+
84
+ async def handle_retry(history, retry_data: gr.RetryData):
85
+ new_history = history[: retry_data.index]
86
+ previous_prompt = history[retry_data.index]["content"]
87
+ async for message in respond(previous_prompt, new_history):
88
+ yield message
89
+
90
+ with gr.Blocks() as demo:
91
+ gr.Markdown("# Chatbot using 🤗 Gradio + 🪢 Langfuse")
92
+ chatbot = gr.Chatbot(
93
+ label="Chat",
94
+ type="messages",
95
+ show_copy_button=True,
96
+ avatar_images=(
97
+ None,
98
+ "https://static.langfuse.com/cookbooks/gradio/hf-logo.png",
99
+ ),
100
+ )
101
+ prompt = gr.Textbox(max_lines=1, label="Chat Message")
102
+ prompt.submit(respond, [prompt, chatbot], [chatbot])
103
+ chatbot.retry(handle_retry, chatbot, [chatbot])
104
+ chatbot.like(handle_like, None, None)
105
+ chatbot.clear(set_new_session_id)
106
+
107
+
108
+ if __name__ == "__main__":
109
+ demo.launch(share=True, debug=True)