Josep Pon Farreny commited on
Commit
4a76b1f
Β·
1 Parent(s): 3ea4ef0

feat: Add langgraph chat with bedrock

Browse files
Files changed (4) hide show
  1. app.py +2 -62
  2. pyproject.toml +5 -7
  3. tdagent/grchat.py +202 -0
  4. uv.lock +0 -0
app.py CHANGED
@@ -1,64 +1,4 @@
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
+ from tdagent.grchat import gr_app
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
  if __name__ == "__main__":
4
+ gr_app.launch()
pyproject.toml CHANGED
@@ -13,19 +13,17 @@ requires-python = ">=3.10,<4"
13
  readme = "README.md"
14
  license = ""
15
  dependencies = [
 
16
  "huggingface-hub>=0.32.3",
 
 
17
  ]
18
 
19
  [project.scripts]
20
 
21
 
22
  [dependency-groups]
23
- dev = [
24
- "mypy~=1.14",
25
- "ruff>=0.9,<1",
26
- "pre-commit~=3.4",
27
- "pip-audit>=2.9.0",
28
- ]
29
  test = [
30
  "pytest>=7.4.4,<8",
31
  "pytest-cov>=4.1.0,<5",
@@ -67,7 +65,7 @@ disallow_untyped_decorators = true
67
  warn_redundant_casts = true
68
  warn_unused_ignores = true
69
  exclude = "docs/"
70
- plugins = [] # ["numpy.typing.mypy_plugin", "pydantic.mypy"]
71
 
72
  [[tool.mypy.overrides]]
73
  module = "tests.*"
 
13
  readme = "README.md"
14
  license = ""
15
  dependencies = [
16
+ "gradio[mcp]>=5.32.1",
17
  "huggingface-hub>=0.32.3",
18
+ "langchain-aws>=0.2.24",
19
+ "langgraph>=0.4.7",
20
  ]
21
 
22
  [project.scripts]
23
 
24
 
25
  [dependency-groups]
26
+ dev = ["mypy~=1.14", "ruff>=0.9,<1", "pre-commit~=3.4", "pip-audit>=2.9.0"]
 
 
 
 
 
27
  test = [
28
  "pytest>=7.4.4,<8",
29
  "pytest-cov>=4.1.0,<5",
 
65
  warn_redundant_casts = true
66
  warn_unused_ignores = true
67
  exclude = "docs/"
68
+ plugins = ["pydantic.mypy"] # ["numpy.typing.mypy_plugin"]
69
 
70
  [[tool.mypy.overrides]]
71
  module = "tests.*"
tdagent/grchat.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Mapping
4
+ from types import MappingProxyType
5
+
6
+ import boto3
7
+ import botocore
8
+ import botocore.exceptions
9
+ import gradio as gr
10
+ from langchain_aws import ChatBedrock
11
+ from langchain_core.messages import AIMessage, HumanMessage, SystemMessage
12
+ from langgraph.graph.graph import CompiledGraph
13
+ from langgraph.prebuilt import create_react_agent
14
+
15
+
16
+ #### Constants ####
17
+
18
+ SYSTEM_MESSAGE = SystemMessage(
19
+ "You are a helpful assistant.",
20
+ )
21
+
22
+ GRADIO_ROLE_TO_LG_MESSAGE_TYPE = MappingProxyType(
23
+ {
24
+ "user": HumanMessage,
25
+ "assistant": AIMessage,
26
+ },
27
+ )
28
+
29
+
30
+ #### Shared variables ####
31
+
32
+ llm_agent: CompiledGraph | None = None
33
+
34
+ #### Utility functions ####
35
+
36
+
37
+ def create_bedrock_llm(
38
+ bedrock_model_id: str,
39
+ aws_access_key: str,
40
+ aws_secret_key: str,
41
+ aws_session_token: str,
42
+ aws_region: str,
43
+ ) -> tuple[ChatBedrock | None, str]:
44
+ """Create a LangGraph Bedrock agent."""
45
+ boto3_config = {
46
+ "aws_access_key_id": aws_access_key,
47
+ "aws_secret_access_key": aws_secret_key,
48
+ "aws_session_token": aws_session_token if aws_session_token else None,
49
+ "region_name": aws_region,
50
+ }
51
+
52
+ # Verify credentials
53
+ try:
54
+ sts = boto3.client("sts", **boto3_config)
55
+ sts.get_caller_identity()
56
+ except botocore.exceptions.ClientError as err:
57
+ return None, str(err)
58
+
59
+ try:
60
+ bedrock_client = boto3.client("bedrock-runtime", **boto3_config)
61
+ llm = ChatBedrock(
62
+ model=bedrock_model_id,
63
+ client=bedrock_client,
64
+ model_kwargs={"temperature": 0.7},
65
+ )
66
+ except Exception as e: # noqa: BLE001
67
+ return None, str(e)
68
+
69
+ return llm, ""
70
+
71
+
72
+ #### UI functionality ####
73
+
74
+
75
+ async def gr_connect_to_bedrock(
76
+ model_id: str,
77
+ access_key: str,
78
+ secret_key: str,
79
+ session_token: str,
80
+ region: str,
81
+ ) -> str:
82
+ """Initialize Bedrock agent."""
83
+ global llm_agent # noqa: PLW0603
84
+
85
+ if not access_key or not secret_key:
86
+ return "❌ Please provide both Access Key ID and Secret Access Key"
87
+
88
+ llm, error = create_bedrock_llm(
89
+ model_id,
90
+ access_key.strip(),
91
+ secret_key.strip(),
92
+ session_token.strip(),
93
+ region,
94
+ )
95
+
96
+ if llm is None:
97
+ return f"❌ Connection failed: {error}"
98
+
99
+ llm_agent = create_react_agent(
100
+ model=llm,
101
+ tools=[],
102
+ prompt=SYSTEM_MESSAGE,
103
+ )
104
+
105
+ return "βœ… Successfully connected to AWS Bedrock!"
106
+
107
+
108
+ async def gr_chat_function( # noqa: D103
109
+ message: str,
110
+ history: list[Mapping[str, str]],
111
+ ) -> str:
112
+ if llm_agent is None:
113
+ return "Please configure your credentials first."
114
+
115
+ messages = []
116
+ for hist_msg in history:
117
+ role = hist_msg["role"]
118
+ message_type = GRADIO_ROLE_TO_LG_MESSAGE_TYPE[role]
119
+ messages.append(message_type(content=hist_msg["content"]))
120
+
121
+ messages.append(HumanMessage(content=message))
122
+
123
+ llm_response = await llm_agent.ainvoke(
124
+ {
125
+ "messages": messages,
126
+ },
127
+ )
128
+
129
+ return llm_response["messages"][-1].content
130
+
131
+
132
+ ## UI components ##
133
+
134
+ with gr.Blocks() as gr_app:
135
+ gr.Markdown("# πŸ” Secure Bedrock Chatbot")
136
+
137
+ # Credentials section (collapsible)
138
+ with gr.Accordion("πŸ”‘ Bedrock Configuration", open=True):
139
+ gr.Markdown(
140
+ "**Note**: Credentials are only stored in memory during your session.",
141
+ )
142
+ with gr.Row():
143
+ bedrock_model_id_textbox = gr.Textbox(
144
+ label="Bedrock Model Id",
145
+ value="eu.anthropic.claude-3-5-sonnet-20240620-v1:0",
146
+ )
147
+ with gr.Row():
148
+ aws_access_key_textbox = gr.Textbox(
149
+ label="AWS Access Key ID",
150
+ type="password",
151
+ placeholder="Enter your AWS Access Key ID",
152
+ )
153
+ aws_secret_key_textbox = gr.Textbox(
154
+ label="AWS Secret Access Key",
155
+ type="password",
156
+ placeholder="Enter your AWS Secret Access Key",
157
+ )
158
+ with gr.Row():
159
+ aws_session_token_textbox = gr.Textbox(
160
+ label="AWS Session Token",
161
+ type="password",
162
+ placeholder="Enter your AWS session token",
163
+ )
164
+ with gr.Row():
165
+ aws_region_dropdown = gr.Dropdown(
166
+ label="AWS Region",
167
+ choices=[
168
+ "us-east-1",
169
+ "us-west-2",
170
+ "eu-west-1",
171
+ "eu-central-1",
172
+ "ap-southeast-1",
173
+ ],
174
+ value="eu-west-1",
175
+ )
176
+ connect_btn = gr.Button("πŸ”Œ Connect to Bedrock", variant="primary")
177
+
178
+ status_textbox = gr.Textbox(label="Connection Status", interactive=False)
179
+
180
+ connect_btn.click(
181
+ gr_connect_to_bedrock,
182
+ inputs=[
183
+ bedrock_model_id_textbox,
184
+ aws_access_key_textbox,
185
+ aws_secret_key_textbox,
186
+ aws_session_token_textbox,
187
+ aws_region_dropdown,
188
+ ],
189
+ outputs=[status_textbox],
190
+ )
191
+
192
+ chat_interface = gr.ChatInterface(
193
+ fn=gr_chat_function,
194
+ type="messages",
195
+ examples=[],
196
+ title="Agent with MCP Tools",
197
+ description="This is a simple agent that uses MCP tools.",
198
+ )
199
+
200
+
201
+ if __name__ == "__main__":
202
+ gr_app.launch()
uv.lock CHANGED
The diff for this file is too large to render. See raw diff