|
| 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 | +from __future__ import annotations |
| 16 | + |
| 17 | +import datetime |
| 18 | +import json |
| 19 | +import re |
| 20 | +from typing import Any |
| 21 | +from zoneinfo import ZoneInfo |
| 22 | +from zoneinfo import ZoneInfoNotFoundError |
| 23 | + |
| 24 | +from google.adk.agents.llm_agent import Agent |
| 25 | +from google.adk.models.lite_llm import LiteLlm |
| 26 | +from google.adk.models.lite_llm import LiteLLMClient |
| 27 | + |
| 28 | + |
| 29 | +class InlineJsonToolClient(LiteLLMClient): |
| 30 | + """LiteLLM client that emits inline JSON tool calls for testing.""" |
| 31 | + |
| 32 | + async def acompletion(self, model, messages, tools, **kwargs): |
| 33 | + del tools, kwargs # Only needed for API parity. |
| 34 | + |
| 35 | + tool_message = _find_last_role(messages, role="tool") |
| 36 | + if tool_message: |
| 37 | + tool_summary = _coerce_to_text(tool_message.get("content")) |
| 38 | + return { |
| 39 | + "id": "mock-inline-tool-final-response", |
| 40 | + "model": model, |
| 41 | + "choices": [{ |
| 42 | + "message": { |
| 43 | + "role": "assistant", |
| 44 | + "content": ( |
| 45 | + f"The instrumentation tool responded with: {tool_summary}" |
| 46 | + ), |
| 47 | + }, |
| 48 | + "finish_reason": "stop", |
| 49 | + }], |
| 50 | + "usage": { |
| 51 | + "prompt_tokens": 60, |
| 52 | + "completion_tokens": 12, |
| 53 | + "total_tokens": 72, |
| 54 | + }, |
| 55 | + } |
| 56 | + |
| 57 | + timezone = _extract_timezone(messages) or "Asia/Taipei" |
| 58 | + inline_call = json.dumps( |
| 59 | + { |
| 60 | + "name": "get_current_time", |
| 61 | + "arguments": {"timezone_str": timezone}, |
| 62 | + }, |
| 63 | + separators=(",", ":"), |
| 64 | + ) |
| 65 | + |
| 66 | + return { |
| 67 | + "id": "mock-inline-tool-call", |
| 68 | + "model": model, |
| 69 | + "choices": [{ |
| 70 | + "message": { |
| 71 | + "role": "assistant", |
| 72 | + "content": ( |
| 73 | + f"{inline_call}\nLet me double-check the clock for you." |
| 74 | + ), |
| 75 | + }, |
| 76 | + "finish_reason": "tool_calls", |
| 77 | + }], |
| 78 | + "usage": { |
| 79 | + "prompt_tokens": 45, |
| 80 | + "completion_tokens": 15, |
| 81 | + "total_tokens": 60, |
| 82 | + }, |
| 83 | + } |
| 84 | + |
| 85 | + |
| 86 | +def _find_last_role( |
| 87 | + messages: list[dict[str, Any]], role: str |
| 88 | +) -> dict[str, Any]: |
| 89 | + """Returns the last message with the given role.""" |
| 90 | + for message in reversed(messages): |
| 91 | + if message.get("role") == role: |
| 92 | + return message |
| 93 | + return {} |
| 94 | + |
| 95 | + |
| 96 | +def _coerce_to_text(content: Any) -> str: |
| 97 | + """Best-effort conversion from OpenAI message content to text.""" |
| 98 | + if isinstance(content, str): |
| 99 | + return content |
| 100 | + if isinstance(content, dict): |
| 101 | + return _coerce_to_text(content.get("text")) |
| 102 | + if isinstance(content, list): |
| 103 | + texts = [] |
| 104 | + for part in content: |
| 105 | + if isinstance(part, dict): |
| 106 | + texts.append(part.get("text") or "") |
| 107 | + elif isinstance(part, str): |
| 108 | + texts.append(part) |
| 109 | + return " ".join(text for text in texts if text) |
| 110 | + return "" |
| 111 | + |
| 112 | + |
| 113 | +_TIMEZONE_PATTERN = re.compile(r"([A-Za-z]+/[A-Za-z_]+)") |
| 114 | + |
| 115 | + |
| 116 | +def _extract_timezone(messages: list[dict[str, Any]]) -> str | None: |
| 117 | + """Extracts an IANA timezone string from the last user message.""" |
| 118 | + user_message = _find_last_role(messages, role="user") |
| 119 | + text = _coerce_to_text(user_message.get("content")) |
| 120 | + if not text: |
| 121 | + return None |
| 122 | + match = _TIMEZONE_PATTERN.search(text) |
| 123 | + if match: |
| 124 | + return match.group(1) |
| 125 | + lowered = text.lower() |
| 126 | + if "taipei" in lowered: |
| 127 | + return "Asia/Taipei" |
| 128 | + if "new york" in lowered: |
| 129 | + return "America/New_York" |
| 130 | + if "london" in lowered: |
| 131 | + return "Europe/London" |
| 132 | + if "tokyo" in lowered: |
| 133 | + return "Asia/Tokyo" |
| 134 | + return None |
| 135 | + |
| 136 | + |
| 137 | +def get_current_time(timezone_str: str) -> dict[str, str]: |
| 138 | + """Returns mock current time for the provided timezone.""" |
| 139 | + try: |
| 140 | + tz = ZoneInfo(timezone_str) |
| 141 | + except ZoneInfoNotFoundError as exc: |
| 142 | + return { |
| 143 | + "status": "error", |
| 144 | + "report": f"Unable to parse timezone '{timezone_str}': {exc}", |
| 145 | + } |
| 146 | + now = datetime.datetime.now(tz) |
| 147 | + return { |
| 148 | + "status": "success", |
| 149 | + "report": ( |
| 150 | + f"The current time in {timezone_str} is" |
| 151 | + f" {now.strftime('%Y-%m-%d %H:%M:%S %Z')}." |
| 152 | + ), |
| 153 | + } |
| 154 | + |
| 155 | + |
| 156 | +_mock_model = LiteLlm( |
| 157 | + model="mock/inline-json-tool-calls", |
| 158 | + llm_client=InlineJsonToolClient(), |
| 159 | +) |
| 160 | + |
| 161 | +root_agent = Agent( |
| 162 | + name="litellm_inline_tool_tester", |
| 163 | + model=_mock_model, |
| 164 | + description=( |
| 165 | + "Demonstrates LiteLLM inline JSON tool-call parsing without an external" |
| 166 | + " VLLM deployment." |
| 167 | + ), |
| 168 | + instruction=( |
| 169 | + "You are a deterministic clock assistant. Always call the" |
| 170 | + " get_current_time tool before answering user questions. After the tool" |
| 171 | + " responds, summarize what it returned." |
| 172 | + ), |
| 173 | + tools=[get_current_time], |
| 174 | +) |
0 commit comments