google-agents-cli-extensions 1.14.2__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.
Files changed (107) hide show
  1. core/claude/README.md +35 -0
  2. core/claude/template/.agents/skills/agents-cli-claude/SKILL.md +106 -0
  3. core/claude/template/.agents/skills/agents-cli-claude/references/claude.md +386 -0
  4. core/claude/template/.agents/skills/agents-cli-claude/references/migrate-claude-agent.md +318 -0
  5. core/claude/template/.agents/skills/agents-cli-claude/references/migrate-from-aws.md +132 -0
  6. core/claude/template/.dockerignore +28 -0
  7. core/claude/template/.env +18 -0
  8. core/claude/template/.env.example +17 -0
  9. core/claude/template/.template/templateconfig.yaml +31 -0
  10. core/claude/template/AGENTS.md +33 -0
  11. core/claude/template/Dockerfile +55 -0
  12. core/claude/template/agent_config/README.md +9 -0
  13. core/claude/template/agents-cli-extension.yaml +49 -0
  14. core/claude/template/app/__init__.py +15 -0
  15. core/claude/template/app/agent.py +49 -0
  16. core/claude/template/app/app_utils/a2a.py +245 -0
  17. core/claude/template/app/app_utils/bq_analytics/__init__.py +124 -0
  18. core/claude/template/app/app_utils/bq_analytics/recorder.py +593 -0
  19. core/claude/template/app/app_utils/bq_analytics/redaction.py +209 -0
  20. core/claude/template/app/app_utils/bq_analytics/schema.py +394 -0
  21. core/claude/template/app/app_utils/bq_analytics/tables.py +104 -0
  22. core/claude/template/app/app_utils/bq_analytics/uploader.py +188 -0
  23. core/claude/template/app/app_utils/claude.py +297 -0
  24. core/claude/template/app/app_utils/completions.py +225 -0
  25. core/claude/template/app/app_utils/conversation.py +29 -0
  26. core/claude/template/app/app_utils/memory_bank.py +308 -0
  27. core/claude/template/app/app_utils/project_settings.py +91 -0
  28. core/claude/template/app/app_utils/reasoning_engine.py +237 -0
  29. core/claude/template/app/app_utils/remote_agents.py +349 -0
  30. core/claude/template/app/app_utils/remote_auth.py +159 -0
  31. core/claude/template/app/app_utils/replies.py +143 -0
  32. core/claude/template/app/app_utils/session_store.py +174 -0
  33. core/claude/template/app/app_utils/settings.py +24 -0
  34. core/claude/template/app/app_utils/telemetry/__init__.py +114 -0
  35. core/claude/template/app/app_utils/telemetry/call_counts.py +44 -0
  36. core/claude/template/app/app_utils/telemetry/cli_relay.py +266 -0
  37. core/claude/template/app/app_utils/telemetry/config.py +133 -0
  38. core/claude/template/app/app_utils/telemetry/logs.py +175 -0
  39. core/claude/template/app/app_utils/telemetry/metrics.py +270 -0
  40. core/claude/template/app/app_utils/telemetry/request_flush.py +104 -0
  41. core/claude/template/app/app_utils/telemetry/subagent_spans.py +80 -0
  42. core/claude/template/app/app_utils/telemetry/traces.py +166 -0
  43. core/claude/template/app/app_utils/turn_events.py +463 -0
  44. core/claude/template/app/app_utils/turn_options.py +219 -0
  45. core/claude/template/app/app_utils/workspaces.py +65 -0
  46. core/claude/template/app/fast_api_app.py +71 -0
  47. core/claude/template/app/feature_tools.py +27 -0
  48. core/claude/template/pyproject.toml +100 -0
  49. core/claude/template/scripts/eval_generate.py +340 -0
  50. core/claude/template/scripts/publish.py +66 -0
  51. core/claude/template/scripts/run.py +85 -0
  52. core/claude/template/scripts/unsupported.py +48 -0
  53. core/claude/template/tests/eval/datasets/basic-dataset.json +31 -0
  54. core/claude/template/tests/eval/eval_config.yaml +17 -0
  55. core/claude/template/tests/eval/response_quality.py +60 -0
  56. core/claude/template/tests/integration/test_server_e2e.py +168 -0
  57. core/claude/template/tests/load_test/.results/.placeholder +0 -0
  58. core/claude/template/tests/load_test/README.md +24 -0
  59. core/claude/template/tests/load_test/load_test.py +118 -0
  60. core/claude/template/tests/unit/conftest.py +63 -0
  61. core/claude/template/tests/unit/helpers.py +32 -0
  62. core/claude/template/tests/unit/test_a2a.py +432 -0
  63. core/claude/template/tests/unit/test_bq_analytics.py +928 -0
  64. core/claude/template/tests/unit/test_bq_redaction.py +89 -0
  65. core/claude/template/tests/unit/test_claude.py +825 -0
  66. core/claude/template/tests/unit/test_completions.py +369 -0
  67. core/claude/template/tests/unit/test_fast_api_app.py +59 -0
  68. core/claude/template/tests/unit/test_feature_tools.py +55 -0
  69. core/claude/template/tests/unit/test_memory_bank.py +625 -0
  70. core/claude/template/tests/unit/test_reasoning_engine.py +295 -0
  71. core/claude/template/tests/unit/test_remote_agents.py +517 -0
  72. core/claude/template/tests/unit/test_telemetry.py +991 -0
  73. core/claude/template/tests/unit/test_turn_events.py +309 -0
  74. core/claude/template/tests/unit/test_turn_options.py +394 -0
  75. core/claude/template/uv.lock +3029 -0
  76. core/langchain/README.md +54 -0
  77. core/langchain/template/.agents/skills/agents-cli-langchain/SKILL.md +84 -0
  78. core/langchain/template/.agents/skills/agents-cli-langchain/references/langchain.md +120 -0
  79. core/langchain/template/.agents/skills/agents-cli-langchain/references/samples.md +42 -0
  80. core/langchain/template/.template/templateconfig.yaml +32 -0
  81. core/langchain/template/AGENTS.md +35 -0
  82. core/langchain/template/agents-cli-extension.yaml +54 -0
  83. core/langchain/template/app/__init__.py +19 -0
  84. core/langchain/template/app/agent.py +61 -0
  85. core/langchain/template/app/app_utils/a2a.py +176 -0
  86. core/langchain/template/app/app_utils/content.py +37 -0
  87. core/langchain/template/app/app_utils/telemetry.py +154 -0
  88. core/langchain/template/app/fast_api_app.py +68 -0
  89. core/langchain/template/langgraph.json +7 -0
  90. core/langchain/template/pyproject.toml +102 -0
  91. core/langchain/template/scripts/_content.py +40 -0
  92. core/langchain/template/scripts/eval_generate.py +202 -0
  93. core/langchain/template/scripts/publish.py +59 -0
  94. core/langchain/template/scripts/run.py +59 -0
  95. core/langchain/template/scripts/unsupported.py +48 -0
  96. core/langchain/template/tests/eval/datasets/basic-dataset.json +16 -0
  97. core/langchain/template/tests/eval/eval_config.yaml +32 -0
  98. core/langchain/template/tests/eval/response_quality.py +60 -0
  99. core/langchain/template/tests/integration/test_server_e2e.py +173 -0
  100. core/langchain/template/tests/load_test/.results/.placeholder +0 -0
  101. core/langchain/template/tests/load_test/README.md +20 -0
  102. core/langchain/template/tests/load_test/load_test.py +82 -0
  103. core/langchain/template/uv.lock +3820 -0
  104. google_agents_cli_extensions-1.14.2.dist-info/METADATA +133 -0
  105. google_agents_cli_extensions-1.14.2.dist-info/RECORD +107 -0
  106. google_agents_cli_extensions-1.14.2.dist-info/WHEEL +4 -0
  107. google_agents_cli_extensions-1.14.2.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,176 @@
1
+ # Copyright 2026 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
+ # https://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
+ """A2A protocol layer: the executor, the agent card, and the routes.
16
+
17
+ `fast_api_app.py` owns the app; this owns what A2A clients see.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import os
23
+ import uuid
24
+
25
+ from a2a.helpers import new_task_from_user_message
26
+ from a2a.server.agent_execution import AgentExecutor, RequestContext
27
+ from a2a.server.events import EventQueue
28
+ from a2a.server.request_handlers import DefaultRequestHandler
29
+ from a2a.server.routes import (
30
+ add_a2a_routes_to_fastapi,
31
+ create_agent_card_routes,
32
+ create_jsonrpc_routes,
33
+ )
34
+ from a2a.server.tasks import InMemoryTaskStore, TaskUpdater
35
+ from a2a.types import AgentCapabilities, AgentCard, AgentInterface, AgentSkill, Part
36
+ from a2a.utils.constants import (
37
+ AGENT_CARD_WELL_KNOWN_PATH,
38
+ PROTOCOL_VERSION_0_3,
39
+ PROTOCOL_VERSION_1_0,
40
+ )
41
+ from fastapi import FastAPI
42
+ from opentelemetry import trace
43
+
44
+ from app.agent import root_agent
45
+ from app.app_utils.content import content_to_text
46
+
47
+
48
+ def advertised_base_url() -> str:
49
+ """Base URL for the agent card: APP_URL, else the host and port we bind."""
50
+ if app_url := os.environ.get("APP_URL"):
51
+ return app_url
52
+ host = os.environ.get("HOST", "127.0.0.1")
53
+ if host in ("0.0.0.0", "::", ""): # what we bind is not what clients dial
54
+ host = "127.0.0.1"
55
+ return f"http://{host}:{os.environ.get('PORT', '8080')}"
56
+
57
+
58
+ _tracer = trace.get_tracer("langchain-agent")
59
+
60
+ # Mount name for the A2A endpoint. Defaults to the project's agent directory
61
+ # ("app") so it matches the `agents-cli run --mode a2a` default (--agent-name).
62
+ A2A_NAME = os.environ.get("A2A_NAME", "app")
63
+ A2A_RPC_PATH = f"/a2a/{A2A_NAME}"
64
+
65
+
66
+ class LangGraphAgentExecutor(AgentExecutor):
67
+ """Bridge the A2A request lifecycle to the compiled LangGraph graph."""
68
+
69
+ async def execute(self, context: RequestContext, event_queue: EventQueue) -> None:
70
+ user_input = context.get_user_input()
71
+ task = context.current_task
72
+ if task is None:
73
+ # First message of a conversation. The Task itself has to reach the
74
+ # queue before any status update, or the server rejects the stream.
75
+ task = new_task_from_user_message(context.message)
76
+ await event_queue.enqueue_event(task)
77
+ updater = TaskUpdater(event_queue, task.id, task.context_id)
78
+ await updater.start_work()
79
+
80
+ # Stream the response as task artifacts (A2A clients read the reply from
81
+ # task artifacts, not the final status message). "messages" mode yields
82
+ # LLM token chunks; "values" mode gives the final state, used as a
83
+ # fallback for graphs whose nodes don't stream tokens (e.g. the echo
84
+ # demo model). The whole turn is wrapped in an `invoke_agent` span.
85
+ artifact_id = uuid.uuid4().hex
86
+ streamed = False
87
+ final_reply = ""
88
+ with _tracer.start_as_current_span("invoke_agent"):
89
+ async for mode, data in root_agent.astream(
90
+ {"messages": [{"role": "user", "content": user_input}]},
91
+ config={"configurable": {"thread_id": task.context_id}},
92
+ stream_mode=["messages", "values"],
93
+ ):
94
+ if mode == "messages":
95
+ chunk, _metadata = data
96
+ text = content_to_text(getattr(chunk, "content", ""))
97
+ if text:
98
+ await updater.add_artifact(
99
+ [Part(text=text)],
100
+ artifact_id=artifact_id,
101
+ name="response",
102
+ append=streamed,
103
+ last_chunk=False,
104
+ )
105
+ streamed = True
106
+ elif mode == "values":
107
+ messages = data.get("messages") if isinstance(data, dict) else None
108
+ if messages:
109
+ final_reply = content_to_text(
110
+ getattr(messages[-1], "content", "")
111
+ )
112
+
113
+ if not streamed and final_reply:
114
+ # Non-streaming node: emit the final reply as a single artifact.
115
+ await updater.add_artifact(
116
+ [Part(text=final_reply)],
117
+ artifact_id=artifact_id,
118
+ name="response",
119
+ )
120
+ await updater.complete()
121
+
122
+ async def cancel(self, context: RequestContext, event_queue: EventQueue) -> None:
123
+ raise NotImplementedError("This agent does not support cancellation.")
124
+
125
+
126
+ def _agent_card() -> AgentCard:
127
+ rpc_url = f"{advertised_base_url()}{A2A_RPC_PATH}"
128
+ return AgentCard(
129
+ name=A2A_NAME,
130
+ description="A LangChain agent served over the A2A protocol.",
131
+ supported_interfaces=[
132
+ AgentInterface(
133
+ url=rpc_url,
134
+ protocol_binding="JSONRPC",
135
+ protocol_version=PROTOCOL_VERSION_1_0,
136
+ ),
137
+ # Gemini's registration validator still requires the 0.3 card shape.
138
+ AgentInterface(
139
+ url=rpc_url,
140
+ protocol_binding="JSONRPC",
141
+ protocol_version=PROTOCOL_VERSION_0_3,
142
+ ),
143
+ ],
144
+ version=os.environ.get("AGENT_VERSION", "0.1.0"),
145
+ default_input_modes=["text/plain"],
146
+ default_output_modes=["text/plain"],
147
+ capabilities=AgentCapabilities(streaming=True),
148
+ skills=[
149
+ AgentSkill(
150
+ id="chat",
151
+ name="chat",
152
+ description="Hold a conversation with the agent.",
153
+ tags=["chat", "langchain"],
154
+ )
155
+ ],
156
+ )
157
+
158
+
159
+ def add_a2a_routes(app: FastAPI) -> None:
160
+ """Mount the JSON-RPC endpoint and the agent card on the app."""
161
+ agent_card = _agent_card()
162
+ request_handler = DefaultRequestHandler(
163
+ agent_executor=LangGraphAgentExecutor(),
164
+ task_store=InMemoryTaskStore(),
165
+ agent_card=agent_card,
166
+ )
167
+ add_a2a_routes_to_fastapi(
168
+ app,
169
+ agent_card_routes=create_agent_card_routes(
170
+ agent_card, card_url=f"{A2A_RPC_PATH}{AGENT_CARD_WELL_KNOWN_PATH}"
171
+ ),
172
+ # v0.3 compat keeps older A2A clients working against the same endpoint.
173
+ jsonrpc_routes=create_jsonrpc_routes(
174
+ request_handler, rpc_url=A2A_RPC_PATH, enable_v0_3_compat=True
175
+ ),
176
+ )
@@ -0,0 +1,37 @@
1
+ # Copyright 2026 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
+ """Normalize LangChain message content to plain text for A2A text parts."""
16
+
17
+ from __future__ import annotations
18
+
19
+
20
+ def content_to_text(content: object) -> str:
21
+ """Return a message's ``content`` as plain text.
22
+
23
+ LangChain 1.x messages carry ``content`` either as a string or as a list of
24
+ content blocks (e.g. ``[{"type": "text", "text": "hi"}]``). An A2A text ``Part``
25
+ requires a string, so flatten the block form here.
26
+ """
27
+ if isinstance(content, str):
28
+ return content
29
+ if isinstance(content, list):
30
+ out: list[str] = []
31
+ for block in content:
32
+ if isinstance(block, dict):
33
+ out.append(str(block.get("text", "")))
34
+ elif isinstance(block, str):
35
+ out.append(block)
36
+ return "".join(out)
37
+ return ""
@@ -0,0 +1,154 @@
1
+ # Copyright 2026 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
+ # https://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
+ """OpenTelemetry setup for the LangChain agent.
16
+
17
+ Exports traces to Cloud Trace and GenAI prompt/response logs to Cloud Logging +
18
+ GCS. ``generate_content`` spans come from the google-genai instrumentor; graph,
19
+ agent, and tool spans from the LangChain instrumentor. With no GCP credentials
20
+ the Cloud exporters are skipped and only in-process instrumentation runs.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import logging
26
+ import os
27
+
28
+ _initialized = False
29
+
30
+
31
+ def _configure_genai_capture() -> None:
32
+ """Set the GenAI prompt/response capture env vars (no-op without a bucket)."""
33
+ bucket = os.environ.get("LOGS_BUCKET_NAME")
34
+ capture = os.environ.get(
35
+ "OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT", "false"
36
+ )
37
+ if not (bucket and capture != "false"):
38
+ logging.info(
39
+ "Prompt-response logging disabled (set LOGS_BUCKET_NAME and "
40
+ "OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=NO_CONTENT to enable)."
41
+ )
42
+ return
43
+ os.environ["OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT"] = "NO_CONTENT"
44
+ os.environ.setdefault("OTEL_INSTRUMENTATION_GENAI_UPLOAD_FORMAT", "jsonl")
45
+ os.environ.setdefault("OTEL_INSTRUMENTATION_GENAI_COMPLETION_HOOK", "upload")
46
+ os.environ.setdefault("OTEL_SEMCONV_STABILITY_OPT_IN", "gen_ai_latest_experimental")
47
+ path = os.environ.get("GENAI_TELEMETRY_PATH", "completions")
48
+ os.environ.setdefault(
49
+ "OTEL_INSTRUMENTATION_GENAI_UPLOAD_BASE_PATH", f"gs://{bucket}/{path}"
50
+ )
51
+
52
+
53
+ def _build_resource():
54
+ """Build the trace/log Resource: service identity + GCP resource attributes."""
55
+ from opentelemetry.sdk.resources import OTELResourceDetector, Resource
56
+
57
+ resource = Resource.create(
58
+ {
59
+ "service.name": os.environ.get("OTEL_SERVICE_NAME", "langchain-agent"),
60
+ "service.version": os.environ.get("COMMIT_SHA", "dev"),
61
+ }
62
+ )
63
+ resource = resource.merge(OTELResourceDetector().detect())
64
+ try:
65
+ from opentelemetry.resourcedetector.gcp_resource_detector import (
66
+ GoogleCloudResourceDetector,
67
+ )
68
+
69
+ resource = resource.merge(
70
+ GoogleCloudResourceDetector(raise_on_error=False).detect()
71
+ )
72
+ except Exception as e: # best-effort; unavailable off-GCP
73
+ logging.debug("GCP resource detection skipped: %s", e)
74
+ return resource
75
+
76
+
77
+ def _setup_cloud_exporters() -> None:
78
+ """Export traces to Cloud Trace and GenAI event logs to Cloud Logging."""
79
+ import google.auth
80
+ from opentelemetry import _logs, trace
81
+ from opentelemetry.exporter.cloud_logging import CloudLoggingExporter
82
+ from opentelemetry.exporter.cloud_trace import CloudTraceSpanExporter
83
+ from opentelemetry.sdk._logs import LoggerProvider
84
+ from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
85
+ from opentelemetry.sdk.trace import TracerProvider
86
+ from opentelemetry.sdk.trace.export import BatchSpanProcessor
87
+
88
+ _, project_id = google.auth.default()
89
+ resource = _build_resource()
90
+
91
+ tracer_provider = TracerProvider(resource=resource)
92
+ tracer_provider.add_span_processor(
93
+ BatchSpanProcessor(CloudTraceSpanExporter(project_id=project_id))
94
+ )
95
+ trace.set_tracer_provider(tracer_provider)
96
+
97
+ logger_provider = LoggerProvider(resource=resource)
98
+ logger_provider.add_log_record_processor(
99
+ BatchLogRecordProcessor(CloudLoggingExporter(project_id=project_id))
100
+ )
101
+ _logs.set_logger_provider(logger_provider)
102
+
103
+
104
+ def _install_instrumentation() -> None:
105
+ """Instrument the google-genai SDK and LangChain/LangGraph execution."""
106
+ try:
107
+ from opentelemetry.instrumentation.google_genai import (
108
+ GoogleGenAiSdkInstrumentor,
109
+ )
110
+
111
+ GoogleGenAiSdkInstrumentor().instrument()
112
+ except Exception as e: # pragma: no cover - optional dependency
113
+ logging.warning("google-genai instrumentation unavailable: %s", e)
114
+ try:
115
+ from opentelemetry.instrumentation.genai.langchain import (
116
+ LangChainInstrumentor,
117
+ )
118
+
119
+ LangChainInstrumentor().instrument()
120
+ except Exception as e: # pragma: no cover - optional dependency
121
+ logging.warning("LangChain instrumentation unavailable: %s", e)
122
+
123
+
124
+ def _cloud_export_enabled() -> bool:
125
+ """Honour the switch ADK reads, so both frameworks turn off the same way.
126
+
127
+ Agent Runtime sets it at deploy time; elsewhere it is absent and export is
128
+ on, which is what the ADK templates do for Cloud Run and GKE.
129
+ """
130
+ value = os.environ.get("GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY")
131
+ return value is None or value.lower() in ("true", "1")
132
+
133
+
134
+ def setup_telemetry() -> None:
135
+ """Configure tracing, GenAI logging, and instrumentation (idempotent)."""
136
+ global _initialized
137
+ if _initialized:
138
+ return
139
+ _initialized = True
140
+
141
+ # gen_ai spans require this experimental semconv opt-in.
142
+ os.environ.setdefault("OTEL_SEMCONV_STABILITY_OPT_IN", "gen_ai_latest_experimental")
143
+ _configure_genai_capture()
144
+ if not _cloud_export_enabled():
145
+ logging.info(
146
+ "Cloud telemetry export disabled by "
147
+ "GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY."
148
+ )
149
+ else:
150
+ try:
151
+ _setup_cloud_exporters()
152
+ except Exception as e: # no GCP creds (local dev): keep instrumentation
153
+ logging.warning("Cloud telemetry export not configured: %s", e)
154
+ _install_instrumentation()
@@ -0,0 +1,68 @@
1
+ # Copyright 2026 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
+ # https://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
+ """FastAPI app serving the agent over the A2A protocol.
16
+
17
+ The agent is exposed through the Agent2Agent (A2A) JSON-RPC surface at
18
+ ``/a2a/{name}``, with its Agent Card at the well-known path. This mirrors the
19
+ contract used by agents-cli's ADK A2A agents, so the deploy entrypoint
20
+ (``uvicorn app.fast_api_app:app``) and ``agents-cli run --mode a2a`` keep
21
+ working unchanged.
22
+
23
+ For the richest *local* LangGraph experience (graph inspection, streaming,
24
+ threads), ``agents-cli playground`` runs ``langgraph dev``, which also serves
25
+ the A2A protocol natively.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import os
31
+ from collections.abc import AsyncIterator
32
+ from contextlib import asynccontextmanager
33
+
34
+ from fastapi import FastAPI
35
+
36
+ from app.app_utils.a2a import add_a2a_routes
37
+ from app.app_utils.telemetry import setup_telemetry
38
+
39
+ # Configure tracing + GenAI logging before the app handles any request.
40
+ setup_telemetry()
41
+
42
+
43
+ @asynccontextmanager
44
+ async def lifespan(app_instance: FastAPI) -> AsyncIterator[None]:
45
+ add_a2a_routes(app_instance)
46
+ yield
47
+
48
+
49
+ app = FastAPI(
50
+ title="langchain-agent",
51
+ description="LangChain agent (A2A protocol)",
52
+ lifespan=lifespan,
53
+ )
54
+
55
+
56
+ @app.get("/health")
57
+ def health() -> dict[str, str]:
58
+ return {"status": "ok"}
59
+
60
+
61
+ if __name__ == "__main__":
62
+ import uvicorn
63
+
64
+ uvicorn.run(
65
+ app,
66
+ host=os.environ.get("HOST", "127.0.0.1"),
67
+ port=int(os.environ.get("PORT", "8080")),
68
+ )
@@ -0,0 +1,7 @@
1
+ {
2
+ "dependencies": ["."],
3
+ "graphs": {
4
+ "agent": "./app/agent.py:root_agent"
5
+ },
6
+ "python_version": "3.12"
7
+ }
@@ -0,0 +1,102 @@
1
+ [project]
2
+ name = "langchain-agent"
3
+ version = "0.1.0"
4
+ description = ""
5
+ authors = [
6
+ {name = "Your Name", email = "your@email.com"},
7
+ ]
8
+ dependencies = [
9
+ "langgraph>=1.0.0,<2.0.0",
10
+ "langchain>=1.0.0,<2.0.0",
11
+ "langchain-core>=1.0.0,<2.0.0",
12
+ "langchain-google-genai>=4.0.0,<5.0.0",
13
+ "langgraph-cli[inmem]>=0.2.10,<1.0.0",
14
+ "python-dotenv>=1.0.0,<2.0.0",
15
+ "fastapi>=0.115.8,<1.0.0",
16
+ "uvicorn~=0.34.0",
17
+ "a2a-sdk[http-server]>=1.0,<2",
18
+ "gcsfs>=2024.11.0",
19
+ "google-cloud-logging>=3.12.0,<4.0.0",
20
+ "google-cloud-aiplatform[evaluation]>=2.2.0,<3.0.0",
21
+ "opentelemetry-instrumentation-google-genai>=1.0b0,<2",
22
+ "opentelemetry-instrumentation-genai-langchain>=1.2b0,<2",
23
+ "opentelemetry-exporter-gcp-trace>=1.6.0,<2.0.0",
24
+ "opentelemetry-exporter-gcp-logging>=0.1.0,<2.0.0",
25
+ "opentelemetry-resourcedetector-gcp>=1.6.0a0,<2",
26
+ ]
27
+ requires-python = ">=3.11,<3.14"
28
+
29
+
30
+ [dependency-groups]
31
+ dev = [
32
+ "pytest>=9.0.2,<10.0.0",
33
+ "pytest-asyncio>=1.0.0,<2.0.0",
34
+ "nest-asyncio>=1.6.0,<2.0.0",
35
+ ]
36
+
37
+ [project.optional-dependencies]
38
+ eval = [
39
+ "google-cloud-aiplatform[evaluation]>=2.2.0,<3.0.0",
40
+ ]
41
+ lint = [
42
+ "ruff>=0.4.6,<1.0.0",
43
+ "ty>=0.0.1a0",
44
+ "codespell>=2.2.0,<3.0.0",
45
+ ]
46
+
47
+ [tool.ruff]
48
+ line-length = 88
49
+ target-version = "py311"
50
+
51
+ [tool.ruff.lint]
52
+ select = [
53
+ "E", # pycodestyle
54
+ "F", # pyflakes
55
+ "W", # pycodestyle warnings
56
+ "I", # isort
57
+ "C", # flake8-comprehensions
58
+ "B", # flake8-bugbear
59
+ "UP", # pyupgrade
60
+ "RUF", # ruff specific rules
61
+ ]
62
+ ignore = ["E501", "C901", "B006"] # ignore line too long, too complex
63
+
64
+ [tool.ruff.lint.isort]
65
+ known-first-party = ["app", "frontend"]
66
+
67
+ [tool.ty]
68
+ # ty is Astral's Rust-based type checker (same team as ruff/uv)
69
+ # See: https://docs.astral.sh/ty/
70
+
71
+ [tool.ty.environment]
72
+ python-version = "3.11"
73
+
74
+ [tool.ty.src]
75
+ exclude = [".venv/**"]
76
+
77
+ [tool.ty.rules]
78
+ unresolved-import = "ignore"
79
+ unresolved-attribute = "ignore"
80
+ invalid-argument-type = "ignore"
81
+ invalid-assignment = "ignore"
82
+ invalid-return-type = "ignore"
83
+ possibly-missing-attribute = "ignore"
84
+ not-subscriptable = "ignore"
85
+ deprecated = "ignore"
86
+
87
+ [tool.codespell]
88
+ ignore-words-list = "rouge"
89
+ skip = "./locust_env/*,uv.lock,.venv,./frontend,**/package-lock.json"
90
+
91
+
92
+ [build-system]
93
+ requires = ["hatchling"]
94
+ build-backend = "hatchling.build"
95
+
96
+
97
+ [tool.pytest.ini_options]
98
+ pythonpath = "."
99
+ asyncio_default_fixture_loop_scope = "function"
100
+
101
+ [tool.hatch.build.targets.wheel]
102
+ packages = ["app"]
@@ -0,0 +1,40 @@
1
+ # Copyright 2026 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
+
16
+ """Message-content normalization shared by the override scripts."""
17
+
18
+ from __future__ import annotations
19
+
20
+
21
+ def content_to_text(content: object) -> str:
22
+ """Flatten LangChain 1.x list content blocks to plain text.
23
+
24
+ A chat model returns `content` either as a string or as a list of blocks
25
+ (`[{"type": "text", "text": "hi"}]`). Printing or writing the list form
26
+ leaks `{'type': ..., 'extras': ...}` noise into `run` output and makes
27
+ `eval grade` reject the trace, so both callers flatten first. The template
28
+ keeps its own copy in `app/app_utils/content.py` for the A2A path, which
29
+ runs inside the user's project rather than here.
30
+ """
31
+ if isinstance(content, str):
32
+ return content
33
+ if isinstance(content, list):
34
+ parts = [
35
+ str(block.get("text", "")) if isinstance(block, dict) else block
36
+ for block in content
37
+ if isinstance(block, (dict, str))
38
+ ]
39
+ return "".join(parts)
40
+ return ""