|
17 | 17 | import abc |
18 | 18 | import asyncio |
19 | 19 | import base64 |
| 20 | +import dataclasses |
20 | 21 | from importlib import metadata as importlib_metadata |
21 | 22 | import inspect |
22 | 23 | import io |
|
134 | 135 | ClientFactory = None |
135 | 136 | TaskIdParams = None |
136 | 137 | TaskQueryParams = None |
| 138 | +try: |
| 139 | + from autogen.agentchat import chat |
| 140 | + |
| 141 | + AutogenChatResult = chat.ChatResult |
| 142 | +except ImportError: |
| 143 | + AutogenChatResult = Any |
| 144 | +try: |
| 145 | + from autogen.io import run_response |
| 146 | + |
| 147 | + AutogenRunResponse = run_response.RunResponse |
| 148 | +except ImportError: |
| 149 | + AutogenRunResponse = Any |
| 150 | +try: |
| 151 | + from llama_index.core.base.response import schema as llama_index_schema |
| 152 | + from llama_index.core.base.llms import types as llama_index_types |
| 153 | + |
| 154 | + LlamaIndexResponse = llama_index_schema.Response |
| 155 | + LlamaIndexBaseModel = llama_index_schema.BaseModel |
| 156 | + LlamaIndexChatResponse = llama_index_types.ChatResponse |
| 157 | +except ImportError: |
| 158 | + LlamaIndexResponse = Any |
| 159 | + LlamaIndexBaseModel = Any |
| 160 | + LlamaIndexChatResponse = Any |
| 161 | +try: |
| 162 | + import pydantic |
| 163 | + |
| 164 | + BaseModel = pydantic.BaseModel |
| 165 | +except ImportError: |
| 166 | + BaseModel = Any |
| 167 | + |
| 168 | +JsonDict = Dict[str, Any] |
137 | 169 |
|
138 | 170 | _ACTIONS_KEY = "actions" |
139 | 171 | _ACTION_APPEND = "append" |
@@ -1994,3 +2026,235 @@ def _add_telemetry_enablement_env( |
1994 | 2026 | return env_vars |
1995 | 2027 |
|
1996 | 2028 | return env_vars | env_to_add |
| 2029 | + |
| 2030 | + |
| 2031 | +def _dataclass_to_dict_or_raise(obj: Any) -> Dict[str, Any]: |
| 2032 | + """Converts a dataclass to a JSON dictionary.""" |
| 2033 | + if not dataclasses.is_dataclass(obj): |
| 2034 | + raise TypeError(f"Object is not a dataclass: {obj}") |
| 2035 | + return json.loads(json.dumps(dataclasses.asdict(obj))) |
| 2036 | + |
| 2037 | + |
| 2038 | +def _autogen_run_response_protocol_to_dict( |
| 2039 | + obj: AutogenRunResponse, |
| 2040 | +) -> Dict[str, Any]: |
| 2041 | + """Converts an AutogenRunResponse object into a JSON-serializable dictionary.""" |
| 2042 | + if hasattr(obj, "process"): |
| 2043 | + obj.process() |
| 2044 | + last_speaker = None |
| 2045 | + if getattr(obj, "last_speaker", None) is not None: |
| 2046 | + last_speaker = { |
| 2047 | + "name": getattr(obj.last_speaker, "name", None), |
| 2048 | + "description": getattr(obj.last_speaker, "description", None), |
| 2049 | + } |
| 2050 | + cost = None |
| 2051 | + if getattr(obj, "cost", None) is not None: |
| 2052 | + if hasattr(obj.cost, "model_dump_json"): |
| 2053 | + cost = json.loads(obj.cost.model_dump_json()) |
| 2054 | + else: |
| 2055 | + cost = str(obj.cost) |
| 2056 | + result = { |
| 2057 | + "summary": getattr(obj, "summary", None), |
| 2058 | + "messages": list(getattr(obj, "messages", [])), |
| 2059 | + "context_variables": getattr(obj, "context_variables", None), |
| 2060 | + "last_speaker": last_speaker, |
| 2061 | + "cost": cost, |
| 2062 | + } |
| 2063 | + return json.loads(json.dumps(result)) |
| 2064 | + |
| 2065 | + |
| 2066 | +def to_json_serializable_autogen_object( |
| 2067 | + obj: Union[ |
| 2068 | + AutogenChatResult, |
| 2069 | + AutogenRunResponse, |
| 2070 | + ], |
| 2071 | +) -> Dict[str, Any]: |
| 2072 | + """Converts an Autogen object to a JSON serializable object.""" |
| 2073 | + if isinstance(obj, AutogenChatResult): |
| 2074 | + return _dataclass_to_dict_or_raise(obj) |
| 2075 | + return _autogen_run_response_protocol_to_dict(obj) |
| 2076 | + |
| 2077 | + |
| 2078 | +def _llama_index_response_to_dict(obj: LlamaIndexResponse) -> Any: |
| 2079 | + response = {} |
| 2080 | + if hasattr(obj, "response"): |
| 2081 | + response["response"] = obj.response |
| 2082 | + if hasattr(obj, "source_nodes"): |
| 2083 | + response["source_nodes"] = [node.model_dump_json() for node in obj.source_nodes] |
| 2084 | + if hasattr(obj, "metadata"): |
| 2085 | + response["metadata"] = obj.metadata |
| 2086 | + return json.loads(json.dumps(response)) |
| 2087 | + |
| 2088 | + |
| 2089 | +def _llama_index_chat_response_to_dict(obj: LlamaIndexChatResponse) -> Any: |
| 2090 | + return json.loads(obj.message.model_dump_json()) |
| 2091 | + |
| 2092 | + |
| 2093 | +def _llama_index_base_model_to_dict(obj: LlamaIndexBaseModel) -> Any: |
| 2094 | + return json.loads(obj.model_dump_json()) |
| 2095 | + |
| 2096 | + |
| 2097 | +def to_json_serializable_llama_index_object( |
| 2098 | + obj: Union[ |
| 2099 | + LlamaIndexResponse, |
| 2100 | + LlamaIndexBaseModel, |
| 2101 | + LlamaIndexChatResponse, |
| 2102 | + Sequence[LlamaIndexBaseModel], |
| 2103 | + ], |
| 2104 | +) -> Union[str, Dict[str, Any], Sequence[Union[str, Dict[str, Any]]]]: |
| 2105 | + """Converts a LlamaIndexResponse to a JSON serializable object.""" |
| 2106 | + if isinstance(obj, LlamaIndexResponse): |
| 2107 | + return _llama_index_response_to_dict(obj) |
| 2108 | + if isinstance(obj, LlamaIndexChatResponse): |
| 2109 | + return _llama_index_chat_response_to_dict(obj) |
| 2110 | + if isinstance(obj, Sequence): |
| 2111 | + seq_result = [] |
| 2112 | + for item in obj: |
| 2113 | + if isinstance(item, LlamaIndexBaseModel): |
| 2114 | + seq_result.append(_llama_index_base_model_to_dict(item)) |
| 2115 | + continue |
| 2116 | + seq_result.append(str(item)) |
| 2117 | + return seq_result |
| 2118 | + if isinstance(obj, LlamaIndexBaseModel): |
| 2119 | + return _llama_index_base_model_to_dict(obj) |
| 2120 | + return str(obj) |
| 2121 | + |
| 2122 | + |
| 2123 | +def is_noop_or_proxy_tracer_provider(tracer_provider) -> bool: |
| 2124 | + """Returns True if the tracer_provider is Proxy or NoOp.""" |
| 2125 | + opentelemetry = _import_opentelemetry_or_warn() |
| 2126 | + if not opentelemetry: |
| 2127 | + return False |
| 2128 | + ProxyTracerProvider = opentelemetry.trace.ProxyTracerProvider |
| 2129 | + NoOpTracerProvider = opentelemetry.trace.NoOpTracerProvider |
| 2130 | + return isinstance(tracer_provider, (NoOpTracerProvider, ProxyTracerProvider)) |
| 2131 | + |
| 2132 | + |
| 2133 | +def dump_event_for_json(event: BaseModel) -> Dict[str, Any]: |
| 2134 | + """Dumps an ADK event to a JSON-serializable dictionary.""" |
| 2135 | + return json.loads(event.model_dump_json(exclude_none=True)) |
| 2136 | + |
| 2137 | + |
| 2138 | +def _import_opentelemetry_or_warn() -> Optional[types.ModuleType]: |
| 2139 | + """Tries to import the opentelemetry module.""" |
| 2140 | + try: |
| 2141 | + import opentelemetry |
| 2142 | + |
| 2143 | + return opentelemetry |
| 2144 | + except ImportError: |
| 2145 | + logger.warning( |
| 2146 | + "opentelemetry-api is not installed. Please call " |
| 2147 | + "'pip install google-cloud-aiplatform[agent_engines]'." |
| 2148 | + ) |
| 2149 | + return None |
| 2150 | + |
| 2151 | + |
| 2152 | +def _import_opentelemetry_sdk_trace_or_warn() -> Optional[types.ModuleType]: |
| 2153 | + """Tries to import the opentelemetry.sdk.trace module.""" |
| 2154 | + try: |
| 2155 | + import opentelemetry.sdk.trace |
| 2156 | + |
| 2157 | + return opentelemetry.sdk.trace |
| 2158 | + except ImportError: |
| 2159 | + logger.warning( |
| 2160 | + "opentelemetry-sdk is not installed. Please call " |
| 2161 | + "'pip install google-cloud-aiplatform[agent_engines]'." |
| 2162 | + ) |
| 2163 | + return None |
| 2164 | + |
| 2165 | + |
| 2166 | +def _import_cloud_trace_v2_or_warn() -> Optional[types.ModuleType]: |
| 2167 | + """Tries to import the google.cloud.trace_v2 module.""" |
| 2168 | + try: |
| 2169 | + import google.cloud.trace_v2 |
| 2170 | + |
| 2171 | + return google.cloud.trace_v2 |
| 2172 | + except ImportError: |
| 2173 | + logger.warning( |
| 2174 | + "google-cloud-trace is not installed. Please call " |
| 2175 | + "'pip install google-cloud-aiplatform[agent_engines]'." |
| 2176 | + ) |
| 2177 | + return None |
| 2178 | + |
| 2179 | + |
| 2180 | +def _import_cloud_trace_exporter_or_warn() -> Optional[types.ModuleType]: |
| 2181 | + """Tries to import the opentelemetry.exporter.cloud_trace module.""" |
| 2182 | + try: |
| 2183 | + import opentelemetry.exporter.cloud_trace |
| 2184 | + |
| 2185 | + return opentelemetry.exporter.cloud_trace |
| 2186 | + except ImportError: |
| 2187 | + logger.warning( |
| 2188 | + "opentelemetry-exporter-gcp-trace is not installed. Please " |
| 2189 | + "call 'pip install google-cloud-aiplatform[agent_engines]'." |
| 2190 | + ) |
| 2191 | + return None |
| 2192 | + |
| 2193 | + |
| 2194 | +def _import_openinference_langchain_or_warn() -> Optional[types.ModuleType]: |
| 2195 | + """Tries to import the openinference.instrumentation.langchain module.""" |
| 2196 | + try: |
| 2197 | + import openinference.instrumentation.langchain |
| 2198 | + |
| 2199 | + return openinference.instrumentation.langchain |
| 2200 | + except ImportError: |
| 2201 | + logger.warning( |
| 2202 | + "openinference-instrumentation-langchain is not installed. Please " |
| 2203 | + "call 'pip install google-cloud-aiplatform[langchain]'." |
| 2204 | + ) |
| 2205 | + return None |
| 2206 | + |
| 2207 | + |
| 2208 | +def _import_openinference_autogen_or_warn() -> Optional[types.ModuleType]: |
| 2209 | + """Tries to import the openinference.instrumentation.autogen module.""" |
| 2210 | + try: |
| 2211 | + import openinference.instrumentation.autogen |
| 2212 | + |
| 2213 | + return openinference.instrumentation.autogen |
| 2214 | + except ImportError: |
| 2215 | + logger.warning( |
| 2216 | + "openinference-instrumentation-autogen is not installed. Please " |
| 2217 | + "call 'pip install google-cloud-aiplatform[ag2]'." |
| 2218 | + ) |
| 2219 | + return None |
| 2220 | + |
| 2221 | + |
| 2222 | +def _import_openinference_llama_index_or_warn() -> Optional[types.ModuleType]: |
| 2223 | + """Tries to import the openinference.instrumentation.llama_index module.""" |
| 2224 | + try: |
| 2225 | + import openinference.instrumentation.llama_index # noqa:F401 |
| 2226 | + |
| 2227 | + return openinference.instrumentation.llama_index |
| 2228 | + except ImportError: |
| 2229 | + logger.warning( |
| 2230 | + "openinference-instrumentation-llama_index is not installed. Please " |
| 2231 | + "call 'pip install google-cloud-aiplatform[llama_index]'." |
| 2232 | + ) |
| 2233 | + return None |
| 2234 | + |
| 2235 | + |
| 2236 | +def _import_nest_asyncio_or_warn() -> Optional[types.ModuleType]: |
| 2237 | + """Tries to import the nest_asyncio module.""" |
| 2238 | + try: |
| 2239 | + import nest_asyncio |
| 2240 | + |
| 2241 | + return nest_asyncio |
| 2242 | + except ImportError: |
| 2243 | + logger.warning( |
| 2244 | + "nest_asyncio is not installed. Please call: `pip install nest-asyncio`" |
| 2245 | + ) |
| 2246 | + return None |
| 2247 | + |
| 2248 | + |
| 2249 | +def _import_autogen_tools_or_warn() -> Optional[types.ModuleType]: |
| 2250 | + """Tries to import the autogen.tools module.""" |
| 2251 | + try: |
| 2252 | + from autogen import tools |
| 2253 | + |
| 2254 | + return tools |
| 2255 | + except ImportError: |
| 2256 | + logger.warning( |
| 2257 | + "autogen.tools is not installed. Please " |
| 2258 | + "call `pip install google-cloud-aiplatform[ag2]`." |
| 2259 | + ) |
| 2260 | + return None |
0 commit comments