agent-starter-pack 0.0.1b0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of agent-starter-pack might be problematic. Click here for more details.

Files changed (162) hide show
  1. agent_starter_pack-0.0.1b0.dist-info/METADATA +143 -0
  2. agent_starter_pack-0.0.1b0.dist-info/RECORD +162 -0
  3. agent_starter_pack-0.0.1b0.dist-info/WHEEL +4 -0
  4. agent_starter_pack-0.0.1b0.dist-info/entry_points.txt +2 -0
  5. agent_starter_pack-0.0.1b0.dist-info/licenses/LICENSE +201 -0
  6. agents/agentic_rag_vertexai_search/README.md +22 -0
  7. agents/agentic_rag_vertexai_search/app/agent.py +145 -0
  8. agents/agentic_rag_vertexai_search/app/retrievers.py +79 -0
  9. agents/agentic_rag_vertexai_search/app/templates.py +53 -0
  10. agents/agentic_rag_vertexai_search/notebooks/evaluating_langgraph_agent.ipynb +1561 -0
  11. agents/agentic_rag_vertexai_search/template/.templateconfig.yaml +14 -0
  12. agents/agentic_rag_vertexai_search/tests/integration/test_agent.py +57 -0
  13. agents/crewai_coding_crew/README.md +34 -0
  14. agents/crewai_coding_crew/app/agent.py +86 -0
  15. agents/crewai_coding_crew/app/crew/config/agents.yaml +39 -0
  16. agents/crewai_coding_crew/app/crew/config/tasks.yaml +37 -0
  17. agents/crewai_coding_crew/app/crew/crew.py +71 -0
  18. agents/crewai_coding_crew/notebooks/evaluating_crewai_agent.ipynb +1571 -0
  19. agents/crewai_coding_crew/notebooks/evaluating_langgraph_agent.ipynb +1561 -0
  20. agents/crewai_coding_crew/template/.templateconfig.yaml +12 -0
  21. agents/crewai_coding_crew/tests/integration/test_agent.py +47 -0
  22. agents/langgraph_base_react/README.md +9 -0
  23. agents/langgraph_base_react/app/agent.py +73 -0
  24. agents/langgraph_base_react/notebooks/evaluating_langgraph_agent.ipynb +1561 -0
  25. agents/langgraph_base_react/template/.templateconfig.yaml +13 -0
  26. agents/langgraph_base_react/tests/integration/test_agent.py +48 -0
  27. agents/multimodal_live_api/README.md +50 -0
  28. agents/multimodal_live_api/app/agent.py +86 -0
  29. agents/multimodal_live_api/app/server.py +193 -0
  30. agents/multimodal_live_api/app/templates.py +51 -0
  31. agents/multimodal_live_api/app/vector_store.py +55 -0
  32. agents/multimodal_live_api/template/.templateconfig.yaml +15 -0
  33. agents/multimodal_live_api/tests/integration/test_server_e2e.py +254 -0
  34. agents/multimodal_live_api/tests/load_test/load_test.py +40 -0
  35. agents/multimodal_live_api/tests/unit/test_server.py +143 -0
  36. src/base_template/.gitignore +197 -0
  37. src/base_template/Makefile +37 -0
  38. src/base_template/README.md +91 -0
  39. src/base_template/app/utils/tracing.py +143 -0
  40. src/base_template/app/utils/typing.py +115 -0
  41. src/base_template/deployment/README.md +123 -0
  42. src/base_template/deployment/cd/deploy-to-prod.yaml +98 -0
  43. src/base_template/deployment/cd/staging.yaml +215 -0
  44. src/base_template/deployment/ci/pr_checks.yaml +51 -0
  45. src/base_template/deployment/terraform/apis.tf +34 -0
  46. src/base_template/deployment/terraform/build_triggers.tf +122 -0
  47. src/base_template/deployment/terraform/dev/apis.tf +42 -0
  48. src/base_template/deployment/terraform/dev/iam.tf +90 -0
  49. src/base_template/deployment/terraform/dev/log_sinks.tf +66 -0
  50. src/base_template/deployment/terraform/dev/providers.tf +29 -0
  51. src/base_template/deployment/terraform/dev/storage.tf +76 -0
  52. src/base_template/deployment/terraform/dev/variables.tf +126 -0
  53. src/base_template/deployment/terraform/dev/vars/env.tfvars +21 -0
  54. src/base_template/deployment/terraform/iam.tf +130 -0
  55. src/base_template/deployment/terraform/locals.tf +50 -0
  56. src/base_template/deployment/terraform/log_sinks.tf +72 -0
  57. src/base_template/deployment/terraform/providers.tf +35 -0
  58. src/base_template/deployment/terraform/service_accounts.tf +42 -0
  59. src/base_template/deployment/terraform/storage.tf +100 -0
  60. src/base_template/deployment/terraform/variables.tf +202 -0
  61. src/base_template/deployment/terraform/vars/env.tfvars +43 -0
  62. src/base_template/pyproject.toml +113 -0
  63. src/base_template/tests/unit/test_utils/test_tracing_exporter.py +140 -0
  64. src/cli/commands/create.py +534 -0
  65. src/cli/commands/setup_cicd.py +730 -0
  66. src/cli/main.py +35 -0
  67. src/cli/utils/__init__.py +35 -0
  68. src/cli/utils/cicd.py +662 -0
  69. src/cli/utils/gcp.py +120 -0
  70. src/cli/utils/logging.py +51 -0
  71. src/cli/utils/template.py +644 -0
  72. src/data_ingestion/README.md +79 -0
  73. src/data_ingestion/data_ingestion_pipeline/components/ingest_data.py +175 -0
  74. src/data_ingestion/data_ingestion_pipeline/components/process_data.py +321 -0
  75. src/data_ingestion/data_ingestion_pipeline/pipeline.py +58 -0
  76. src/data_ingestion/data_ingestion_pipeline/submit_pipeline.py +184 -0
  77. src/data_ingestion/pyproject.toml +17 -0
  78. src/data_ingestion/uv.lock +999 -0
  79. src/deployment_targets/agent_engine/app/agent_engine_app.py +238 -0
  80. src/deployment_targets/agent_engine/app/utils/gcs.py +42 -0
  81. src/deployment_targets/agent_engine/deployment_metadata.json +4 -0
  82. src/deployment_targets/agent_engine/notebooks/intro_reasoning_engine.ipynb +869 -0
  83. src/deployment_targets/agent_engine/tests/integration/test_agent_engine_app.py +120 -0
  84. src/deployment_targets/agent_engine/tests/load_test/.results/.placeholder +0 -0
  85. src/deployment_targets/agent_engine/tests/load_test/.results/report.html +264 -0
  86. src/deployment_targets/agent_engine/tests/load_test/.results/results_exceptions.csv +1 -0
  87. src/deployment_targets/agent_engine/tests/load_test/.results/results_failures.csv +1 -0
  88. src/deployment_targets/agent_engine/tests/load_test/.results/results_stats.csv +3 -0
  89. src/deployment_targets/agent_engine/tests/load_test/.results/results_stats_history.csv +22 -0
  90. src/deployment_targets/agent_engine/tests/load_test/README.md +42 -0
  91. src/deployment_targets/agent_engine/tests/load_test/load_test.py +100 -0
  92. src/deployment_targets/agent_engine/tests/unit/test_dummy.py +22 -0
  93. src/deployment_targets/cloud_run/Dockerfile +29 -0
  94. src/deployment_targets/cloud_run/app/server.py +128 -0
  95. src/deployment_targets/cloud_run/deployment/terraform/artifact_registry.tf +22 -0
  96. src/deployment_targets/cloud_run/deployment/terraform/dev/service_accounts.tf +20 -0
  97. src/deployment_targets/cloud_run/tests/integration/test_server_e2e.py +192 -0
  98. src/deployment_targets/cloud_run/tests/load_test/.results/.placeholder +0 -0
  99. src/deployment_targets/cloud_run/tests/load_test/README.md +79 -0
  100. src/deployment_targets/cloud_run/tests/load_test/load_test.py +85 -0
  101. src/deployment_targets/cloud_run/tests/unit/test_server.py +142 -0
  102. src/deployment_targets/cloud_run/uv.lock +6952 -0
  103. src/frontends/live_api_react/frontend/package-lock.json +19405 -0
  104. src/frontends/live_api_react/frontend/package.json +56 -0
  105. src/frontends/live_api_react/frontend/public/favicon.ico +0 -0
  106. src/frontends/live_api_react/frontend/public/index.html +62 -0
  107. src/frontends/live_api_react/frontend/public/robots.txt +3 -0
  108. src/frontends/live_api_react/frontend/src/App.scss +189 -0
  109. src/frontends/live_api_react/frontend/src/App.test.tsx +25 -0
  110. src/frontends/live_api_react/frontend/src/App.tsx +205 -0
  111. src/frontends/live_api_react/frontend/src/components/audio-pulse/AudioPulse.tsx +64 -0
  112. src/frontends/live_api_react/frontend/src/components/audio-pulse/audio-pulse.scss +68 -0
  113. src/frontends/live_api_react/frontend/src/components/control-tray/ControlTray.tsx +217 -0
  114. src/frontends/live_api_react/frontend/src/components/control-tray/control-tray.scss +201 -0
  115. src/frontends/live_api_react/frontend/src/components/logger/Logger.tsx +241 -0
  116. src/frontends/live_api_react/frontend/src/components/logger/logger.scss +133 -0
  117. src/frontends/live_api_react/frontend/src/components/logger/mock-logs.ts +151 -0
  118. src/frontends/live_api_react/frontend/src/components/side-panel/SidePanel.tsx +161 -0
  119. src/frontends/live_api_react/frontend/src/components/side-panel/side-panel.scss +285 -0
  120. src/frontends/live_api_react/frontend/src/contexts/LiveAPIContext.tsx +48 -0
  121. src/frontends/live_api_react/frontend/src/hooks/use-live-api.ts +115 -0
  122. src/frontends/live_api_react/frontend/src/hooks/use-media-stream-mux.ts +23 -0
  123. src/frontends/live_api_react/frontend/src/hooks/use-screen-capture.ts +72 -0
  124. src/frontends/live_api_react/frontend/src/hooks/use-webcam.ts +69 -0
  125. src/frontends/live_api_react/frontend/src/index.css +28 -0
  126. src/frontends/live_api_react/frontend/src/index.tsx +35 -0
  127. src/frontends/live_api_react/frontend/src/multimodal-live-types.ts +242 -0
  128. src/frontends/live_api_react/frontend/src/react-app-env.d.ts +17 -0
  129. src/frontends/live_api_react/frontend/src/reportWebVitals.ts +31 -0
  130. src/frontends/live_api_react/frontend/src/setupTests.ts +21 -0
  131. src/frontends/live_api_react/frontend/src/utils/audio-recorder.ts +111 -0
  132. src/frontends/live_api_react/frontend/src/utils/audio-streamer.ts +270 -0
  133. src/frontends/live_api_react/frontend/src/utils/audioworklet-registry.ts +43 -0
  134. src/frontends/live_api_react/frontend/src/utils/multimodal-live-client.ts +329 -0
  135. src/frontends/live_api_react/frontend/src/utils/store-logger.ts +64 -0
  136. src/frontends/live_api_react/frontend/src/utils/utils.ts +86 -0
  137. src/frontends/live_api_react/frontend/src/utils/worklets/audio-processing.ts +73 -0
  138. src/frontends/live_api_react/frontend/src/utils/worklets/vol-meter.ts +65 -0
  139. src/frontends/live_api_react/frontend/tsconfig.json +25 -0
  140. src/frontends/streamlit/frontend/side_bar.py +213 -0
  141. src/frontends/streamlit/frontend/streamlit_app.py +263 -0
  142. src/frontends/streamlit/frontend/style/app_markdown.py +37 -0
  143. src/frontends/streamlit/frontend/utils/chat_utils.py +67 -0
  144. src/frontends/streamlit/frontend/utils/local_chat_history.py +125 -0
  145. src/frontends/streamlit/frontend/utils/message_editing.py +59 -0
  146. src/frontends/streamlit/frontend/utils/multimodal_utils.py +217 -0
  147. src/frontends/streamlit/frontend/utils/stream_handler.py +282 -0
  148. src/frontends/streamlit/frontend/utils/title_summary.py +77 -0
  149. src/resources/containers/data_processing/Dockerfile +25 -0
  150. src/resources/locks/uv-agentic_rag_vertexai_search-agent_engine.lock +4684 -0
  151. src/resources/locks/uv-agentic_rag_vertexai_search-cloud_run.lock +5799 -0
  152. src/resources/locks/uv-crewai_coding_crew-agent_engine.lock +5509 -0
  153. src/resources/locks/uv-crewai_coding_crew-cloud_run.lock +6688 -0
  154. src/resources/locks/uv-langgraph_base_react-agent_engine.lock +4595 -0
  155. src/resources/locks/uv-langgraph_base_react-cloud_run.lock +5710 -0
  156. src/resources/locks/uv-multimodal_live_api-cloud_run.lock +5665 -0
  157. src/resources/setup_cicd/cicd_variables.tf +36 -0
  158. src/resources/setup_cicd/github.tf +85 -0
  159. src/resources/setup_cicd/providers.tf +39 -0
  160. src/utils/generate_locks.py +135 -0
  161. src/utils/lock_utils.py +82 -0
  162. src/utils/watch_and_rebuild.py +190 -0
@@ -0,0 +1,213 @@
1
+ # Copyright 2025 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # ruff: noqa: RUF015
16
+ import json
17
+ import os
18
+ import uuid
19
+ from typing import Any
20
+
21
+ from frontend.utils.chat_utils import save_chat
22
+ from frontend.utils.multimodal_utils import (
23
+ HELP_GCS_CHECKBOX,
24
+ HELP_MESSAGE_MULTIMODALITY,
25
+ upload_files_to_gcs,
26
+ )
27
+
28
+ EMPTY_CHAT_NAME = "Empty chat"
29
+ NUM_CHAT_IN_RECENT = 3
30
+ DEFAULT_BASE_URL = "http://localhost:8000/"
31
+
32
+ DEFAULT_REMOTE_AGENT_ENGINE_ID = "N/A"
33
+ if os.path.exists("deployment_metadata.json"):
34
+ with open("deployment_metadata.json") as f:
35
+ DEFAULT_REMOTE_AGENT_ENGINE_ID = json.load(f)["remote_agent_engine_id"]
36
+ DEFAULT_AGENT_CALLABLE_PATH = "app.agent_engine_app.AgentEngineApp"
37
+
38
+
39
+ class SideBar:
40
+ """Manages the sidebar components of the Streamlit application."""
41
+
42
+ def __init__(self, st: Any) -> None:
43
+ """
44
+ Initialize the SideBar.
45
+
46
+ Args:
47
+ st (Any): The Streamlit object for rendering UI components.
48
+ """
49
+ self.st = st
50
+
51
+ def init_side_bar(self) -> None:
52
+ """Initialize and render the sidebar components."""
53
+ with self.st.sidebar:
54
+ default_agent_type = (
55
+ "Remote URL" if os.path.exists("Dockerfile") else "Local Agent"
56
+ )
57
+ use_agent_path = self.st.selectbox(
58
+ "Select Agent Type",
59
+ ["Local Agent", "Remote Engine ID", "Remote URL"],
60
+ index=["Local Agent", "Remote Engine ID", "Remote URL"].index(
61
+ default_agent_type
62
+ ),
63
+ )
64
+
65
+ if use_agent_path == "Local Agent":
66
+ self.agent_callable_path = self.st.text_input(
67
+ label="Agent Callable Path",
68
+ value=os.environ.get(
69
+ "AGENT_CALLABLE_PATH", DEFAULT_AGENT_CALLABLE_PATH
70
+ ),
71
+ )
72
+ self.remote_agent_engine_id = None
73
+ self.url_input_field = None
74
+ self.should_authenticate_request = False
75
+ elif use_agent_path == "Remote Engine ID":
76
+ self.remote_agent_engine_id = self.st.text_input(
77
+ label="Remote Agent Engine ID",
78
+ value=os.environ.get(
79
+ "REMOTE_AGENT_ENGINE_ID", DEFAULT_REMOTE_AGENT_ENGINE_ID
80
+ ),
81
+ )
82
+ self.agent_callable_path = None
83
+ self.url_input_field = None
84
+ self.should_authenticate_request = False
85
+ else:
86
+ self.url_input_field = self.st.text_input(
87
+ label="Service URL",
88
+ value=os.environ.get("SERVICE_URL", DEFAULT_BASE_URL),
89
+ )
90
+ self.should_authenticate_request = self.st.checkbox(
91
+ label="Authenticate request",
92
+ value=False,
93
+ help="If checked, any request to the server will contain an"
94
+ "Identity token to allow authentication. "
95
+ "See the Cloud Run documentation to know more about authentication:"
96
+ "https://cloud.google.com/run/docs/authenticating/service-to-service",
97
+ )
98
+ self.agent_callable_path = None
99
+ self.remote_agent_engine_id = None
100
+
101
+ col1, col2, col3 = self.st.columns(3)
102
+ with col1:
103
+ if self.st.button("+ New chat"):
104
+ if (
105
+ len(
106
+ self.st.session_state.user_chats[
107
+ self.st.session_state["session_id"]
108
+ ]["messages"]
109
+ )
110
+ > 0
111
+ ):
112
+ self.st.session_state.run_id = None
113
+
114
+ self.st.session_state["session_id"] = str(uuid.uuid4())
115
+ self.st.session_state.session_db.get_session(
116
+ session_id=self.st.session_state["session_id"],
117
+ )
118
+ self.st.session_state.user_chats[
119
+ self.st.session_state["session_id"]
120
+ ] = {
121
+ "title": EMPTY_CHAT_NAME,
122
+ "messages": [],
123
+ }
124
+
125
+ with col2:
126
+ if self.st.button("Delete chat"):
127
+ self.st.session_state.run_id = None
128
+ self.st.session_state.session_db.clear()
129
+ self.st.session_state.user_chats.pop(
130
+ self.st.session_state["session_id"]
131
+ )
132
+ if len(self.st.session_state.user_chats) > 0:
133
+ chat_id = list(self.st.session_state.user_chats.keys())[0]
134
+ self.st.session_state["session_id"] = chat_id
135
+ self.st.session_state.session_db.get_session(
136
+ session_id=self.st.session_state["session_id"],
137
+ )
138
+ else:
139
+ self.st.session_state["session_id"] = str(uuid.uuid4())
140
+ self.st.session_state.user_chats[
141
+ self.st.session_state["session_id"]
142
+ ] = {
143
+ "title": EMPTY_CHAT_NAME,
144
+ "messages": [],
145
+ }
146
+ with col3:
147
+ if self.st.button("Save chat"):
148
+ save_chat(self.st)
149
+
150
+ self.st.subheader("Recent") # Style the heading
151
+
152
+ all_chats = list(reversed(self.st.session_state.user_chats.items()))
153
+ for chat_id, chat in all_chats[:NUM_CHAT_IN_RECENT]:
154
+ if self.st.button(chat["title"], key=chat_id):
155
+ self.st.session_state.run_id = None
156
+ self.st.session_state["session_id"] = chat_id
157
+ self.st.session_state.session_db.get_session(
158
+ session_id=self.st.session_state["session_id"],
159
+ )
160
+
161
+ with self.st.expander("Other chats"):
162
+ for chat_id, chat in all_chats[NUM_CHAT_IN_RECENT:]:
163
+ if self.st.button(chat["title"], key=chat_id):
164
+ self.st.session_state.run_id = None
165
+ self.st.session_state["session_id"] = chat_id
166
+ self.st.session_state.session_db.get_session(
167
+ session_id=self.st.session_state["session_id"],
168
+ )
169
+
170
+ self.st.divider()
171
+ self.st.header("Upload files from local")
172
+ bucket_name = self.st.text_input(
173
+ label="GCS Bucket for upload",
174
+ value=os.environ.get("BUCKET_NAME", "gs://your-bucket-name"),
175
+ )
176
+ if "checkbox_state" not in self.st.session_state:
177
+ self.st.session_state.checkbox_state = True
178
+
179
+ self.st.session_state.checkbox_state = self.st.checkbox(
180
+ "Upload to GCS first (suggested)", value=False, help=HELP_GCS_CHECKBOX
181
+ )
182
+
183
+ self.uploaded_files = self.st.file_uploader(
184
+ label="Send files from local",
185
+ accept_multiple_files=True,
186
+ key=f"uploader_images_{self.st.session_state.uploader_key}",
187
+ type=[
188
+ "png",
189
+ "jpg",
190
+ "jpeg",
191
+ "txt",
192
+ "docx",
193
+ "pdf",
194
+ "rtf",
195
+ "csv",
196
+ "tsv",
197
+ "xlsx",
198
+ ],
199
+ )
200
+ if self.uploaded_files and self.st.session_state.checkbox_state:
201
+ upload_files_to_gcs(self.st, bucket_name, self.uploaded_files)
202
+
203
+ self.st.divider()
204
+
205
+ self.st.header("Upload files from GCS")
206
+ self.gcs_uris = self.st.text_area(
207
+ "GCS uris (comma-separated)",
208
+ value=self.st.session_state["gcs_uris_to_be_sent"],
209
+ key=f"upload_text_area_{self.st.session_state.uploader_key}",
210
+ help=HELP_MESSAGE_MULTIMODALITY,
211
+ )
212
+
213
+ self.st.caption(f"Note: {HELP_MESSAGE_MULTIMODALITY}")
@@ -0,0 +1,263 @@
1
+ # Copyright 2025 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # mypy: disable-error-code="arg-type"
16
+ import json
17
+ import uuid
18
+ from collections.abc import Sequence
19
+ from functools import partial
20
+ from typing import Any
21
+
22
+ import streamlit as st
23
+ from langchain_core.messages import HumanMessage
24
+ from streamlit_feedback import streamlit_feedback
25
+
26
+ from frontend.side_bar import SideBar
27
+ from frontend.style.app_markdown import MARKDOWN_STR
28
+ from frontend.utils.local_chat_history import LocalChatMessageHistory
29
+ from frontend.utils.message_editing import MessageEditing
30
+ from frontend.utils.multimodal_utils import format_content, get_parts_from_files
31
+ from frontend.utils.stream_handler import Client, StreamHandler, get_chain_response
32
+
33
+ USER = "my_user"
34
+ EMPTY_CHAT_NAME = "Empty chat"
35
+
36
+
37
+ def setup_page() -> None:
38
+ """Configure the Streamlit page settings."""
39
+ st.set_page_config(
40
+ page_title="Playground",
41
+ layout="wide",
42
+ initial_sidebar_state="auto",
43
+ menu_items=None,
44
+ )
45
+ st.title("Playground")
46
+ st.markdown(MARKDOWN_STR, unsafe_allow_html=True)
47
+
48
+
49
+ def initialize_session_state() -> None:
50
+ """Initialize the session state with default values."""
51
+ if "user_chats" not in st.session_state:
52
+ st.session_state["session_id"] = str(uuid.uuid4())
53
+ st.session_state.uploader_key = 0
54
+ st.session_state.run_id = None
55
+ st.session_state.user_id = USER
56
+ st.session_state["gcs_uris_to_be_sent"] = ""
57
+ st.session_state.modified_prompt = None
58
+ st.session_state.session_db = LocalChatMessageHistory(
59
+ session_id=st.session_state["session_id"],
60
+ user_id=st.session_state["user_id"],
61
+ )
62
+ st.session_state.user_chats = (
63
+ st.session_state.session_db.get_all_conversations()
64
+ )
65
+ st.session_state.user_chats[st.session_state["session_id"]] = {
66
+ "title": EMPTY_CHAT_NAME,
67
+ "messages": [],
68
+ }
69
+
70
+
71
+ def display_messages() -> None:
72
+ """Display all messages in the current chat session."""
73
+ messages = st.session_state.user_chats[st.session_state["session_id"]]["messages"]
74
+ tool_calls_map = {} # Map tool_call_id to tool call input
75
+
76
+ for i, message in enumerate(messages):
77
+ if message["type"] in ["ai", "human"] and message["content"]:
78
+ display_chat_message(message, i)
79
+ elif message.get("tool_calls"):
80
+ # Store each tool call input mapped by its ID
81
+ for tool_call in message["tool_calls"]:
82
+ tool_calls_map[tool_call["id"]] = tool_call
83
+ elif message["type"] == "tool":
84
+ # Look up the corresponding tool call input by ID
85
+ tool_call_id = message["tool_call_id"]
86
+ if tool_call_id in tool_calls_map:
87
+ display_tool_output(tool_calls_map[tool_call_id], message)
88
+ else:
89
+ st.error(f"Could not find tool call input for ID: {tool_call_id}")
90
+ else:
91
+ st.error(f"Unexpected message type: {message['type']}")
92
+ st.write("Full messages list:", messages)
93
+ raise ValueError(f"Unexpected message type: {message['type']}")
94
+
95
+
96
+ def display_chat_message(message: dict[str, Any], index: int) -> None:
97
+ """Display a single chat message with edit, refresh, and delete options."""
98
+ chat_message = st.chat_message(message["type"])
99
+ with chat_message:
100
+ st.markdown(format_content(message["content"]), unsafe_allow_html=True)
101
+ col1, col2, col3 = st.columns([2, 2, 94])
102
+ display_message_buttons(message, index, col1, col2, col3)
103
+
104
+
105
+ def display_message_buttons(
106
+ message: dict[str, Any], index: int, col1: Any, col2: Any, col3: Any
107
+ ) -> None:
108
+ """Display edit, refresh, and delete buttons for a chat message."""
109
+ edit_button = f"{index}_edit"
110
+ refresh_button = f"{index}_refresh"
111
+ delete_button = f"{index}_delete"
112
+ content = (
113
+ message["content"]
114
+ if isinstance(message["content"], str)
115
+ else message["content"][-1]["text"]
116
+ )
117
+
118
+ with col1:
119
+ st.button(label="✎", key=edit_button, type="primary")
120
+ if message["type"] == "human":
121
+ with col2:
122
+ st.button(
123
+ label="⟳",
124
+ key=refresh_button,
125
+ type="primary",
126
+ on_click=partial(MessageEditing.refresh_message, st, index, content),
127
+ )
128
+ with col3:
129
+ st.button(
130
+ label="X",
131
+ key=delete_button,
132
+ type="primary",
133
+ on_click=partial(MessageEditing.delete_message, st, index),
134
+ )
135
+
136
+ if st.session_state[edit_button]:
137
+ st.text_area(
138
+ "Edit your message:",
139
+ value=content,
140
+ key=f"edit_box_{index}",
141
+ on_change=partial(MessageEditing.edit_message, st, index, message["type"]),
142
+ )
143
+
144
+
145
+ def display_tool_output(
146
+ tool_call_input: dict[str, Any], tool_call_output: dict[str, Any]
147
+ ) -> None:
148
+ """Display the input and output of a tool call in an expander."""
149
+ tool_expander = st.expander(label="Tool Calls:", expanded=False)
150
+ with tool_expander:
151
+ msg = (
152
+ f"\n\nEnding tool: `{tool_call_input}` with\n **args:**\n"
153
+ f"```\n{json.dumps(tool_call_input, indent=2)}\n```\n"
154
+ f"\n\n**output:**\n "
155
+ f"```\n{json.dumps(tool_call_output, indent=2)}\n```"
156
+ )
157
+ st.markdown(msg, unsafe_allow_html=True)
158
+
159
+
160
+ def handle_user_input(side_bar: SideBar) -> None:
161
+ """Process user input, generate AI response, and update chat history."""
162
+ prompt = st.chat_input() or st.session_state.modified_prompt
163
+ if prompt:
164
+ st.session_state.modified_prompt = None
165
+ parts = get_parts_from_files(
166
+ upload_gcs_checkbox=st.session_state.checkbox_state,
167
+ uploaded_files=side_bar.uploaded_files,
168
+ gcs_uris=side_bar.gcs_uris,
169
+ )
170
+ st.session_state["gcs_uris_to_be_sent"] = ""
171
+ parts.append({"type": "text", "text": prompt})
172
+ st.session_state.user_chats[st.session_state["session_id"]]["messages"].append(
173
+ HumanMessage(content=parts).model_dump()
174
+ )
175
+
176
+ display_user_input(parts)
177
+ generate_ai_response(
178
+ remote_agent_engine_id=side_bar.remote_agent_engine_id,
179
+ agent_callable_path=side_bar.agent_callable_path,
180
+ url=side_bar.url_input_field,
181
+ authenticate_request=side_bar.should_authenticate_request,
182
+ )
183
+ update_chat_title()
184
+ if len(parts) > 1:
185
+ st.session_state.uploader_key += 1
186
+ st.rerun()
187
+
188
+
189
+ def display_user_input(parts: Sequence[dict[str, Any]]) -> None:
190
+ """Display the user's input in the chat interface."""
191
+ human_message = st.chat_message("human")
192
+ with human_message:
193
+ existing_user_input = format_content(parts)
194
+ st.markdown(existing_user_input, unsafe_allow_html=True)
195
+
196
+
197
+ def generate_ai_response(
198
+ remote_agent_engine_id: str | None = None,
199
+ agent_callable_path: str | None = None,
200
+ url: str | None = None,
201
+ authenticate_request: bool = False,
202
+ ) -> None:
203
+ """Generate and display the AI's response to the user's input."""
204
+ ai_message = st.chat_message("ai")
205
+ with ai_message:
206
+ status = st.status("Generating answer🤖")
207
+ stream_handler = StreamHandler(st=st)
208
+ client = Client(
209
+ remote_agent_engine_id=remote_agent_engine_id,
210
+ agent_callable_path=agent_callable_path,
211
+ url=url,
212
+ authenticate_request=authenticate_request,
213
+ )
214
+ get_chain_response(st=st, client=client, stream_handler=stream_handler)
215
+ status.update(label="Finished!", state="complete", expanded=False)
216
+
217
+
218
+ def update_chat_title() -> None:
219
+ """Update the chat title if it's currently empty."""
220
+ if (
221
+ st.session_state.user_chats[st.session_state["session_id"]]["title"]
222
+ == EMPTY_CHAT_NAME
223
+ ):
224
+ st.session_state.session_db.set_title(
225
+ st.session_state.user_chats[st.session_state["session_id"]]
226
+ )
227
+ st.session_state.session_db.upsert_session(
228
+ st.session_state.user_chats[st.session_state["session_id"]]
229
+ )
230
+
231
+
232
+ def display_feedback(side_bar: SideBar) -> None:
233
+ """Display a feedback component and log the feedback if provided."""
234
+ if st.session_state.run_id is not None:
235
+ feedback = streamlit_feedback(
236
+ feedback_type="faces",
237
+ optional_text_label="[Optional] Please provide an explanation",
238
+ key=f"feedback-{st.session_state.run_id}",
239
+ )
240
+ if feedback is not None:
241
+ client = Client(
242
+ agent_callable_path=side_bar.agent_callable_path,
243
+ remote_agent_engine_id=side_bar.remote_agent_engine_id,
244
+ )
245
+ client.log_feedback(
246
+ feedback_dict=feedback,
247
+ run_id=st.session_state.run_id,
248
+ )
249
+
250
+
251
+ def main() -> None:
252
+ """Main function to set up and run the Streamlit app."""
253
+ setup_page()
254
+ initialize_session_state()
255
+ side_bar = SideBar(st=st)
256
+ side_bar.init_side_bar()
257
+ display_messages()
258
+ handle_user_input(side_bar=side_bar)
259
+ display_feedback(side_bar=side_bar)
260
+
261
+
262
+ if __name__ == "__main__":
263
+ main()
@@ -0,0 +1,37 @@
1
+ # Copyright 2025 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ MARKDOWN_STR = """
16
+ <style>
17
+ button[kind="primary"] {
18
+ background: none!important;
19
+ border: 0;
20
+ padding: 20!important;
21
+ color: grey !important;
22
+ text-decoration: none;
23
+ cursor: pointer;
24
+ border: none !important;
25
+ # float: right;
26
+ }
27
+ button[kind="primary"]:hover {
28
+ text-decoration: none;
29
+ color: white !important;
30
+ }
31
+ button[kind="primary"]:focus {
32
+ outline: none !important;
33
+ box-shadow: none !important;
34
+ color: !important;
35
+ }
36
+ </style>
37
+ """
@@ -0,0 +1,67 @@
1
+ # Copyright 2025 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import os
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ import yaml
20
+
21
+ SAVED_CHAT_PATH = str(os.getcwd()) + "/.saved_chats"
22
+
23
+
24
+ def clean_text(text: str) -> str:
25
+ """Preprocess the input text by removing leading and trailing newlines."""
26
+ if not text:
27
+ return text
28
+
29
+ if text.startswith("\n"):
30
+ text = text[1:]
31
+ if text.endswith("\n"):
32
+ text = text[:-1]
33
+ return text
34
+
35
+
36
+ def sanitize_messages(
37
+ messages: list[dict[str, str | list[dict[str, str]]]],
38
+ ) -> list[dict[str, str | list[dict[str, str]]]]:
39
+ """Preprocess and fix the content of messages."""
40
+ for message in messages:
41
+ if isinstance(message["content"], list):
42
+ for part in message["content"]:
43
+ if part["type"] == "text":
44
+ part["text"] = clean_text(part["text"])
45
+ else:
46
+ message["content"] = clean_text(message["content"])
47
+ return messages
48
+
49
+
50
+ def save_chat(st: Any) -> None:
51
+ """Save the current chat session to a YAML file."""
52
+ Path(SAVED_CHAT_PATH).mkdir(parents=True, exist_ok=True)
53
+ session_id = st.session_state["session_id"]
54
+ session = st.session_state.user_chats[session_id]
55
+ messages = session.get("messages", [])
56
+ if len(messages) > 0:
57
+ session["messages"] = sanitize_messages(session["messages"])
58
+ filename = f"{session_id}.yaml"
59
+ with open(Path(SAVED_CHAT_PATH) / filename, "w") as file:
60
+ yaml.dump(
61
+ [session],
62
+ file,
63
+ allow_unicode=True,
64
+ default_flow_style=False,
65
+ encoding="utf-8",
66
+ )
67
+ st.toast(f"Chat saved to path: ↓ {Path(SAVED_CHAT_PATH) / filename}")