fix: corrige autenticação e ciclo de streaming do DeepAgents

This commit is contained in:
alex alves
2026-11-05 16:14:38 -03:00
parent 6f24a02ccc
commit fbbe47d90d
4 changed files with 270 additions and 21 deletions

View File

@@ -16,7 +16,10 @@ Does not manage:
from __future__ import annotations
from collections.abc import AsyncGenerator
import asyncio
import math
from collections.abc import AsyncGenerator, Iterator
from typing import Any
from contextlib import aclosing
from deepagents import create_deep_agent
@@ -41,6 +44,23 @@ de ferramentas que não foram executadas.
"""
def _text_fragments(content: str | list[str | dict[str, Any]]) -> Iterator[str]:
"""Extract text without exposing reasoning, tools or other content blocks."""
if isinstance(content, str):
if content:
yield content
return
for block in content:
if isinstance(block, str):
if block:
yield block
elif isinstance(block, dict) and block.get("type") == "text":
text = block.get("text")
if isinstance(text, str) and text:
yield text
class DeepAgentsAdapter(StreamingAgentAdapter):
def __init__(
self,
@@ -51,6 +71,10 @@ class DeepAgentsAdapter(StreamingAgentAdapter):
max_completion_tokens: int,
timeout_seconds: float,
system_prompt: str = DEFAULT_SYSTEM_PROMPT,
*,
auth_type: str = "INSTANCE_PRINCIPAL",
auth_profile: str = "DEFAULT",
auth_file_location: str = "~/.oci/config",
) -> None:
if not region:
raise ValueError("OCI region is required.")
@@ -61,8 +85,15 @@ class DeepAgentsAdapter(StreamingAgentAdapter):
if not model_id:
raise ValueError("OCI model_id is required.")
if timeout_seconds <= 0:
raise ValueError("timeout_seconds must be positive.")
if (
isinstance(timeout_seconds, bool)
or not isinstance(timeout_seconds, (int, float))
or not math.isfinite(timeout_seconds)
or timeout_seconds <= 0
):
raise ValueError("timeout_seconds must be finite and positive.")
self._stream_event_timeout = float(timeout_seconds)
self.model = ChatOCIGenAI(
model_id=model_id,
@@ -71,7 +102,9 @@ class DeepAgentsAdapter(StreamingAgentAdapter):
f"https://inference.generativeai."
f"{region}.oci.oraclecloud.com"
),
auth_type="INSTANCE_PRINCIPAL",
auth_type=auth_type,
auth_profile=auth_profile,
auth_file_location=auth_file_location,
is_stream=True,
model_kwargs={
"temperature": temperature,
@@ -142,27 +175,30 @@ class DeepAgentsAdapter(StreamingAgentAdapter):
config = self._config(session_id)
async for message, metadata in self.agent.astream(
{
"messages": [
HumanMessage(content=text)
]
},
events = self.agent.astream(
{"messages": [HumanMessage(content=text)]},
config=config,
stream_mode="messages",
):
# Ignore tools and subagent outputs.
if metadata.get("langgraph_node") != "model":
continue
)
async with aclosing(events):
while True:
try:
async with asyncio.timeout(self._stream_event_timeout):
message, metadata = await anext(events)
except StopAsyncIteration:
break
except TimeoutError as exc:
raise TimeoutError(
"Deep Agent timed out waiting for the next stream event."
) from exc
# Ignore tool-call fragments.
if getattr(message, "tool_call_chunks", None):
continue
if metadata.get("langgraph_node") != "model":
continue
if getattr(message, "tool_call_chunks", None):
continue
content = message.content
if isinstance(content, str) and content:
yield content
for fragment in _text_fragments(message.content):
yield fragment
async def aclose(self) -> None: