baxin commited on
Commit
87671ab
·
1 Parent(s): 9523069

update api key stuff

Browse files
Files changed (1) hide show
  1. app.py +105 -43
app.py CHANGED
@@ -1,7 +1,20 @@
1
  import streamlit as st
2
  from cerebras.cloud.sdk import Cerebras
3
  import openai
4
- from prompt import RECIPE_BASE_PROMPT
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
  # Set page configuration
7
  st.set_page_config(page_icon="🤖", layout="wide", page_title="Recipe Infographic Prompt Generator")
@@ -16,7 +29,7 @@ def icon(emoji: str):
16
 
17
 
18
  # Display header
19
- icon("🧠")
20
  st.title("ChatBot with Cerebras API")
21
  st.subheader("Deploying Cerebras on Streamlit", divider="orange", anchor=False)
22
 
@@ -26,13 +39,30 @@ models = {
26
  "llama-3.3-70b": {"name": "Llama-3.3-70b", "tokens": 8192, "developer": "Meta"}
27
  }
28
 
29
- BASE_URL = "http://localhost:8000/v1"
 
 
 
 
 
 
 
 
30
 
31
- # Sidebar configuration
32
  with st.sidebar:
33
  st.title("Settings")
34
- st.markdown("### :red[Enter your Cerebras API Key below]")
35
- api_key = st.text_input("Cerebras API Key:", type="password")
 
 
 
 
 
 
 
 
 
36
 
37
  # Model selection
38
  model_option = st.selectbox(
@@ -44,18 +74,22 @@ with st.sidebar:
44
 
45
  # Max tokens slider
46
  max_tokens_range = models[model_option]["tokens"]
 
 
47
  max_tokens = st.slider(
48
  "Max Tokens:",
49
  min_value=512,
50
  max_value=max_tokens_range,
51
- value=max_tokens_range,
52
  step=512,
53
  help="Select the maximum number of tokens (words) for the model's response."
54
  )
55
 
56
  use_optillm = st.toggle("Use Optillm", value=False)
57
 
58
- # Check for API key before proceeding
 
 
59
  if not api_key:
60
  st.markdown("""
61
  ## Cerebras API x Streamlit Demo!
@@ -63,42 +97,51 @@ if not api_key:
63
  This simple chatbot app demonstrates how to use Cerebras with Streamlit.
64
 
65
  To get started:
66
- 1. :red[Enter your Cerebras API Key in the sidebar.]
67
- 2. Chat away, powered by Cerebras.
68
  """)
69
- st.stop()
70
-
71
- # Initialize Cerebras client
72
- # client = Cerebras(api_key=api_key)
73
-
74
- if use_optillm:
75
- client = openai.OpenAI(
76
- base_url="http://localhost:8000/v1",
77
- api_key=api_key
78
- )
79
- else:
80
- client = Cerebras(api_key=api_key)
81
-
82
-
83
- # Chat history management
 
 
 
 
 
 
 
 
 
 
 
84
  if "messages" not in st.session_state:
85
  st.session_state.messages = []
86
 
87
  if "selected_model" not in st.session_state:
88
  st.session_state.selected_model = None
89
 
90
- # Clear history if model changes
91
  if st.session_state.selected_model != model_option:
92
  st.session_state.messages = []
93
  st.session_state.selected_model = model_option
94
 
95
- # Display chat messages
96
  for message in st.session_state.messages:
97
  avatar = '🤖' if message["role"] == "assistant" else '🦔'
98
  with st.chat_message(message["role"], avatar=avatar):
99
  st.markdown(message["content"])
100
 
101
- # Chat input and processing
102
  if prompt := st.chat_input("Enter your prompt here..."):
103
  st.session_state.messages.append({"role": "user", "content": prompt})
104
 
@@ -106,28 +149,47 @@ if prompt := st.chat_input("Enter your prompt here..."):
106
  st.markdown(prompt)
107
 
108
  try:
109
- # Create empty container for streaming response
110
  with st.chat_message("assistant", avatar="🤖"):
111
  response_placeholder = st.empty()
112
  full_response = ""
113
 
114
- # Stream the response
115
- for chunk in client.chat.completions.create(
116
- model=model_option,
117
- messages=[
118
- {"role": "system", "content": RECIPE_BASE_PROMPT},
119
- {"role": "user", "content": prompt}],
120
- max_tokens=max_tokens,
121
- stream=True, # Ensure Cerebras API supports streaming
122
- # base_url=BASE_URL
123
- ):
124
- if chunk.choices[0].delta.content:
125
- chunk_content = chunk.choices[0].delta.content
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  full_response += chunk_content
127
- response_placeholder.markdown(full_response + "▌")
128
 
129
- # Update the final response without cursor
130
  response_placeholder.markdown(full_response)
 
131
  st.session_state.messages.append(
132
  {"role": "assistant", "content": full_response})
133
 
 
1
  import streamlit as st
2
  from cerebras.cloud.sdk import Cerebras
3
  import openai
4
+ # prompt.py が存在し、RECIPE_BASE_PROMPTが定義されていると仮定
5
+ # もし存在しない場合は、適切に定義してください
6
+ try:
7
+ from prompt import RECIPE_BASE_PROMPT
8
+ except ImportError:
9
+ # テスト用にダミーのプロンプトを設定
10
+ RECIPE_BASE_PROMPT = "You are a helpful recipe assistant."
11
+ print("Warning: 'prompt.py' not found or 'RECIPE_BASE_PROMPT' not defined. Using a default system prompt.")
12
+
13
+ import os
14
+ from dotenv import load_dotenv
15
+
16
+ # .envファイルから環境変数を読み込む
17
+ load_dotenv()
18
 
19
  # Set page configuration
20
  st.set_page_config(page_icon="🤖", layout="wide", page_title="Recipe Infographic Prompt Generator")
 
29
 
30
 
31
  # Display header
32
+ icon("🧠🧑‍🍳")
33
  st.title("ChatBot with Cerebras API")
34
  st.subheader("Deploying Cerebras on Streamlit", divider="orange", anchor=False)
35
 
 
39
  "llama-3.3-70b": {"name": "Llama-3.3-70b", "tokens": 8192, "developer": "Meta"}
40
  }
41
 
42
+ BASE_URL = "http://localhost:8000/v1" # Optillmが使用する場合のベースURL
43
+
44
+ # --- APIキーの処理 ---
45
+ # 環境変数からAPIキーを取得試行
46
+ api_key_from_env = os.getenv("CEREBRAS_API_KEY")
47
+ # APIキー入力フィールドを表示する必要があるかどうかのフラグ
48
+ show_api_key_input = not bool(api_key_from_env)
49
+ # アプリケーションで使用する最終的なAPIキー変数
50
+ api_key = None
51
 
52
+ # --- サイドバーの設定 ---
53
  with st.sidebar:
54
  st.title("Settings")
55
+
56
+ if show_api_key_input:
57
+ # 環境変数にキーがない場合、入力フィールドを表示
58
+ st.markdown("### :red[Enter your Cerebras API Key below]")
59
+ api_key_input = st.text_input("Cerebras API Key:", type="password", key="api_key_input_field")
60
+ if api_key_input:
61
+ api_key = api_key_input # 入力されたキーを使用
62
+ else:
63
+ # 環境変数にキーがある場合、それを使用
64
+ api_key = api_key_from_env
65
+ st.success("✓ API Key loaded from environment") # 任意:ロードされたことを通知
66
 
67
  # Model selection
68
  model_option = st.selectbox(
 
74
 
75
  # Max tokens slider
76
  max_tokens_range = models[model_option]["tokens"]
77
+ # デフォルト値を最大値ではなく、より一般的な値に設定(例:2048)
78
+ default_tokens = min(2048, max_tokens_range)
79
  max_tokens = st.slider(
80
  "Max Tokens:",
81
  min_value=512,
82
  max_value=max_tokens_range,
83
+ value=default_tokens, # 修正:デフォルト値を設定
84
  step=512,
85
  help="Select the maximum number of tokens (words) for the model's response."
86
  )
87
 
88
  use_optillm = st.toggle("Use Optillm", value=False)
89
 
90
+ # --- メインアプリケーションロジック ---
91
+
92
+ # APIキーが最終的に利用可能かチェック (サイドバーの処理後)
93
  if not api_key:
94
  st.markdown("""
95
  ## Cerebras API x Streamlit Demo!
 
97
  This simple chatbot app demonstrates how to use Cerebras with Streamlit.
98
 
99
  To get started:
 
 
100
  """)
101
+ if show_api_key_input:
102
+ # サイドバー入力が表示されている場合
103
+ st.warning("1. :red[Enter your Cerebras API Key in the sidebar.]")
104
+ else:
105
+ # 環境変数から読み込むべきだったが、見つからなかった/空だった場合
106
+ st.error("1. :red[CEREBRAS_API_KEY environment variable not found or empty.] Please set it in your environment (e.g., in a .env file).")
107
+ st.markdown("2. Chat away, powered by Cerebras.")
108
+ st.stop() # APIキーがない場合はここで停止
109
+
110
+ # APIキーが利用可能な場合のみクライアントを初期化
111
+ try:
112
+ if use_optillm:
113
+ client = openai.OpenAI(
114
+ base_url=BASE_URL, # Optillmがlocalhostを使用する場合
115
+ api_key=api_key
116
+ )
117
+ else:
118
+ # Cerebras SDKがapi_keyだけで初期化可能か確認
119
+ # SDKのバージョンや使い方によってはendpoint等の追加設定が必要な場合あり
120
+ client = Cerebras(api_key=api_key)
121
+ # st.success("API Client Initialized.") # 任意:初期化成功メッセージ
122
+ except Exception as e:
123
+ st.error(f"Failed to initialize API client: {str(e)}", icon="🚨")
124
+ st.stop() # クライアント初期化失敗時も停止
125
+
126
+ # --- チャット履歴管理 ---
127
  if "messages" not in st.session_state:
128
  st.session_state.messages = []
129
 
130
  if "selected_model" not in st.session_state:
131
  st.session_state.selected_model = None
132
 
133
+ # モデルが変更されたら履歴をクリア
134
  if st.session_state.selected_model != model_option:
135
  st.session_state.messages = []
136
  st.session_state.selected_model = model_option
137
 
138
+ # チャットメッセージを表示
139
  for message in st.session_state.messages:
140
  avatar = '🤖' if message["role"] == "assistant" else '🦔'
141
  with st.chat_message(message["role"], avatar=avatar):
142
  st.markdown(message["content"])
143
 
144
+ # --- チャット入力と処理 ---
145
  if prompt := st.chat_input("Enter your prompt here..."):
146
  st.session_state.messages.append({"role": "user", "content": prompt})
147
 
 
149
  st.markdown(prompt)
150
 
151
  try:
 
152
  with st.chat_message("assistant", avatar="🤖"):
153
  response_placeholder = st.empty()
154
  full_response = ""
155
 
156
+ # APIに送信するメッセージリストを作成 (システムプロンプト + ユーザープロンプト)
157
+ # 必要に応じて過去の会話履歴も加えることができます
158
+ # 例: messages_for_api = [{"role": "system", "content": RECIPE_BASE_PROMPT}] + st.session_state.messages[-N:] + [{"role": "user", "content": prompt}]
159
+ messages_for_api=[
160
+ {"role": "system", "content": RECIPE_BASE_PROMPT},
161
+ {"role": "user", "content": prompt} # 最新のプロンプトのみ送信する場合
162
+ # 全履歴を送信する場合:
163
+ # *st.session_state.messages
164
+ ]
165
+
166
+
167
+ # ストリーミングで応答を取得
168
+ # Cerebras SDK と OpenAI SDK で引数名や構造が同じか確認
169
+ stream_kwargs = {
170
+ "model": model_option,
171
+ "messages": messages_for_api,
172
+ "max_tokens": max_tokens,
173
+ "stream": True,
174
+ }
175
+ # Optillm (OpenAI互換) と Cerebras SDK のcreateメソッドの互換性を確認
176
+ response_stream = client.chat.completions.create(**stream_kwargs)
177
+
178
+ for chunk in response_stream:
179
+ # chunkの構造がSDKによって異なる可能性を考慮
180
+ chunk_content = ""
181
+ # OpenAI SDK / Cerebras SDK (OpenAI互換の場合) の一般的な構造
182
+ if hasattr(chunk, 'choices') and chunk.choices and hasattr(chunk.choices[0], 'delta') and chunk.choices[0].delta and hasattr(chunk.choices[0].delta, 'content'):
183
+ # contentがNoneの場合も考慮
184
+ chunk_content = chunk.choices[0].delta.content or ""
185
+
186
+ if chunk_content:
187
  full_response += chunk_content
188
+ response_placeholder.markdown(full_response + "▌") # カーソル表示
189
 
190
+ # 最終的な応答を表示(カーソルなし)
191
  response_placeholder.markdown(full_response)
192
+ # アシスタントの応答を履歴に追加
193
  st.session_state.messages.append(
194
  {"role": "assistant", "content": full_response})
195