baiam-agents-builder 0.1.0__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.
- agents_builder/__init__.py +82 -0
- agents_builder/constants.py +1 -0
- agents_builder/eval/__init__.py +72 -0
- agents_builder/eval/annotator.py +48 -0
- agents_builder/eval/exceptions.py +10 -0
- agents_builder/eval/settings.py +20 -0
- agents_builder/eval/utils.py +8 -0
- agents_builder/exceptions.py +19 -0
- agents_builder/langgraph/__init__.py +46 -0
- agents_builder/llm/__init__.py +19 -0
- agents_builder/llm/exceptions.py +18 -0
- agents_builder/llm/factory.py +44 -0
- agents_builder/llm/llm.py +46 -0
- agents_builder/llm/settings.py +33 -0
- agents_builder/mixins.py +60 -0
- agents_builder/py.typed +0 -0
- agents_builder/settings.py +14 -0
- agents_builder/utils.py +45 -0
- baiam_agents_builder-0.1.0.dist-info/METADATA +106 -0
- baiam_agents_builder-0.1.0.dist-info/RECORD +21 -0
- baiam_agents_builder-0.1.0.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import logging
|
|
3
|
+
from abc import ABC, abstractmethod
|
|
4
|
+
from datetime import datetime
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from langchain_core.tools import BaseTool
|
|
8
|
+
from langgraph.graph.state import CompiledStateGraph
|
|
9
|
+
|
|
10
|
+
from agents_builder.exceptions import (
|
|
11
|
+
MCPNotConfiguredError,
|
|
12
|
+
MCPToolNotFoundError,
|
|
13
|
+
)
|
|
14
|
+
from agents_builder.llm.factory import LLMFactory
|
|
15
|
+
from agents_builder.mixins import FromConfigMixin
|
|
16
|
+
from agents_builder.settings import AgentSettings
|
|
17
|
+
from agents_builder.utils import _cached_mcp_tools, load_class
|
|
18
|
+
|
|
19
|
+
_logger = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Agent[TConfig: AgentSettings](FromConfigMixin[TConfig], ABC):
|
|
23
|
+
"""A configured agent with a lazy graph, LLM factory, and cached MCP tools."""
|
|
24
|
+
|
|
25
|
+
def __init__(self, config: TConfig) -> None:
|
|
26
|
+
self.config = config
|
|
27
|
+
self._graph: CompiledStateGraph | None = None
|
|
28
|
+
self.init_components()
|
|
29
|
+
_logger.info("Agent initialized")
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def graph(self) -> CompiledStateGraph:
|
|
33
|
+
if self._graph is None:
|
|
34
|
+
_logger.info("Graph not initialized → building graph")
|
|
35
|
+
self._graph = self.build_graph()
|
|
36
|
+
return self._graph
|
|
37
|
+
|
|
38
|
+
async def load_tool(self, mcp_name: str, key: str) -> BaseTool:
|
|
39
|
+
if key in self._tools_by_name:
|
|
40
|
+
return self._tools_by_name[key]
|
|
41
|
+
async with self._tool_lock:
|
|
42
|
+
if key in self._tools_by_name:
|
|
43
|
+
return self._tools_by_name[key]
|
|
44
|
+
mcp = next(
|
|
45
|
+
(m for m in self.config.mcps if m.name == mcp_name),
|
|
46
|
+
None,
|
|
47
|
+
)
|
|
48
|
+
if mcp is None:
|
|
49
|
+
raise MCPNotConfiguredError(tool_key=key)
|
|
50
|
+
tools = await _cached_mcp_tools(
|
|
51
|
+
mcps_fingerprint=f"{mcp.name}:{mcp.url}",
|
|
52
|
+
mcps_config=[mcp],
|
|
53
|
+
)
|
|
54
|
+
for tool in tools:
|
|
55
|
+
self._tools_by_name[tool.name] = tool
|
|
56
|
+
if key not in self._tools_by_name:
|
|
57
|
+
raise MCPToolNotFoundError(
|
|
58
|
+
tool_key=key,
|
|
59
|
+
mcp_name=mcp.name,
|
|
60
|
+
available=list(self._tools_by_name.keys()),
|
|
61
|
+
)
|
|
62
|
+
return self._tools_by_name[key]
|
|
63
|
+
|
|
64
|
+
def init_components(self) -> None:
|
|
65
|
+
self.llm_factory: LLMFactory = load_class(self.config.llm_factory.module_path).from_config(
|
|
66
|
+
self.config.llm_factory
|
|
67
|
+
)
|
|
68
|
+
self._tools_by_name: dict[str, BaseTool] = {}
|
|
69
|
+
self._tool_lock = asyncio.Lock()
|
|
70
|
+
_logger.info("Agent created")
|
|
71
|
+
|
|
72
|
+
def push(self, path: str | None = None) -> None:
|
|
73
|
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
|
74
|
+
agent_name = self.__class__.__name__
|
|
75
|
+
filename = f"{agent_name}_graph_{timestamp}.png"
|
|
76
|
+
full_path: Path = Path(path) / filename if path else Path(".") / filename
|
|
77
|
+
png_bytes = self.graph.get_graph().draw_mermaid_png()
|
|
78
|
+
full_path.write_bytes(png_bytes)
|
|
79
|
+
_logger.info(f"Graph saved locally at {full_path}")
|
|
80
|
+
|
|
81
|
+
@abstractmethod
|
|
82
|
+
def build_graph(self) -> CompiledStateGraph: ...
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
CONFIG_PATH = "/config/config.yaml"
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from abc import ABC, abstractmethod
|
|
4
|
+
from collections.abc import Mapping, Sequence
|
|
5
|
+
from typing import Any, Literal
|
|
6
|
+
|
|
7
|
+
from opentelemetry.trace import Status, StatusCode
|
|
8
|
+
from opentelemetry.trace.span import Span
|
|
9
|
+
|
|
10
|
+
from agents_builder import FromConfigMixin
|
|
11
|
+
from agents_builder.eval.exceptions import MissingSpanError
|
|
12
|
+
from agents_builder.eval.settings import TraceAnnotatorSettings
|
|
13
|
+
|
|
14
|
+
AttributeValue = str | bool | int | float | Sequence[str] | Sequence[bool] | Sequence[int] | Sequence[float]
|
|
15
|
+
Attributes = Mapping[str, AttributeValue] | None
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class TraceAnnotator[TConfig: TraceAnnotatorSettings](FromConfigMixin[TConfig], ABC):
|
|
19
|
+
def __init__(self, config: TConfig) -> None:
|
|
20
|
+
super().__init__(config)
|
|
21
|
+
self._span: Span | None = None
|
|
22
|
+
|
|
23
|
+
@property
|
|
24
|
+
def span(self) -> Span | None:
|
|
25
|
+
return self._span
|
|
26
|
+
|
|
27
|
+
def set_span(self, span: Span) -> None:
|
|
28
|
+
self._span = span
|
|
29
|
+
|
|
30
|
+
@abstractmethod
|
|
31
|
+
def annotate(
|
|
32
|
+
self,
|
|
33
|
+
*,
|
|
34
|
+
annotation_name: str,
|
|
35
|
+
annotator_kind: Literal["LLM", "CODE", "HUMAN"],
|
|
36
|
+
label: str | None,
|
|
37
|
+
score: float | None,
|
|
38
|
+
explanation: str | None = None,
|
|
39
|
+
metadata: dict[str, Any] | None = None,
|
|
40
|
+
identifier: str | None = None,
|
|
41
|
+
) -> None:
|
|
42
|
+
raise NotImplementedError
|
|
43
|
+
|
|
44
|
+
def ensure_span(self) -> Span:
|
|
45
|
+
span = self.span
|
|
46
|
+
if span is None:
|
|
47
|
+
raise MissingSpanError()
|
|
48
|
+
return span
|
|
49
|
+
|
|
50
|
+
def set_attribute(self, key: str, value: AttributeValue) -> None:
|
|
51
|
+
self.ensure_span().set_attribute(key, value)
|
|
52
|
+
|
|
53
|
+
def set_attributes(self, attributes: Mapping[str, AttributeValue]) -> None:
|
|
54
|
+
self.ensure_span().set_attributes(attributes)
|
|
55
|
+
|
|
56
|
+
def set_status(
|
|
57
|
+
self,
|
|
58
|
+
status: Status | StatusCode,
|
|
59
|
+
description: str | None = None,
|
|
60
|
+
) -> None:
|
|
61
|
+
self.ensure_span().set_status(status=status, description=description)
|
|
62
|
+
|
|
63
|
+
def record_exception(
|
|
64
|
+
self,
|
|
65
|
+
exception: BaseException,
|
|
66
|
+
attributes: Attributes = None,
|
|
67
|
+
timestamp: int | None = None,
|
|
68
|
+
escaped: bool = False,
|
|
69
|
+
) -> None:
|
|
70
|
+
self.ensure_span().record_exception(
|
|
71
|
+
exception=exception, attributes=attributes, timestamp=timestamp, escaped=escaped
|
|
72
|
+
)
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any, Literal
|
|
4
|
+
|
|
5
|
+
from opentelemetry.trace import format_span_id
|
|
6
|
+
from phoenix.client import Client
|
|
7
|
+
from phoenix.otel import register
|
|
8
|
+
|
|
9
|
+
from agents_builder.eval import TraceAnnotator
|
|
10
|
+
from agents_builder.eval.exceptions import MissingSpanError
|
|
11
|
+
from agents_builder.eval.settings import PhoenixTraceAnnotatorSettings
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class PhoenixTraceAnnotator(TraceAnnotator[PhoenixTraceAnnotatorSettings]):
|
|
15
|
+
def __init__(self, config: PhoenixTraceAnnotatorSettings) -> None:
|
|
16
|
+
super().__init__(config)
|
|
17
|
+
self._client = Client(base_url=self.config.base_url)
|
|
18
|
+
self.tracer_provider = register(
|
|
19
|
+
auto_instrument=True,
|
|
20
|
+
project_name=self.config.project_name,
|
|
21
|
+
endpoint=f"{self.config.base_url}/v1/traces",
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
def annotate(
|
|
25
|
+
self,
|
|
26
|
+
*,
|
|
27
|
+
annotation_name: str,
|
|
28
|
+
annotator_kind: Literal["LLM", "CODE", "HUMAN"],
|
|
29
|
+
label: str | None,
|
|
30
|
+
score: float | None,
|
|
31
|
+
explanation: str | None = None,
|
|
32
|
+
metadata: dict[str, Any] | None = None,
|
|
33
|
+
identifier: str | None = None,
|
|
34
|
+
) -> None:
|
|
35
|
+
if self.span is None:
|
|
36
|
+
raise MissingSpanError()
|
|
37
|
+
|
|
38
|
+
span_id = format_span_id(self.span.get_span_context().span_id)
|
|
39
|
+
self._client.spans.add_span_annotation(
|
|
40
|
+
span_id=span_id,
|
|
41
|
+
annotation_name=annotation_name,
|
|
42
|
+
annotator_kind=annotator_kind,
|
|
43
|
+
label=label,
|
|
44
|
+
score=score,
|
|
45
|
+
explanation=explanation,
|
|
46
|
+
metadata=metadata,
|
|
47
|
+
identifier=identifier,
|
|
48
|
+
)
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
from agents_builder.exceptions import AgentsBuilderError
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class ObservabilityError(AgentsBuilderError):
|
|
5
|
+
"""Errors related to tracing, logging, and observability"""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class MissingSpanError(ObservabilityError):
|
|
9
|
+
def __init__(self):
|
|
10
|
+
super().__init__("No active span found. Did you forget to start a trace?")
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
from pydantic import field_validator
|
|
2
|
+
|
|
3
|
+
from agents_builder.eval.utils import get_commit_hash
|
|
4
|
+
from agents_builder.mixins import FromConfigMixinSettings
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class TraceAnnotatorSettings(FromConfigMixinSettings):
|
|
8
|
+
pass
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class PhoenixTraceAnnotatorSettings(TraceAnnotatorSettings):
|
|
12
|
+
module_path: str = "agents_builder.eval.annotator.PhoenixTraceAnnotator"
|
|
13
|
+
base_url: str
|
|
14
|
+
project_name: str
|
|
15
|
+
|
|
16
|
+
@field_validator("project_name")
|
|
17
|
+
@classmethod
|
|
18
|
+
def add_suffix(cls, project_name: str) -> str:
|
|
19
|
+
git_commit_sha = get_commit_hash()
|
|
20
|
+
return f"{project_name}_{git_commit_sha}" if git_commit_sha else project_name
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import subprocess # nosec B404
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def get_commit_hash() -> str | None:
|
|
5
|
+
result = subprocess.run(["git", "rev-parse", "HEAD"], capture_output=True, text=True, check=False) # nosec B603, B607
|
|
6
|
+
if result.returncode:
|
|
7
|
+
return None
|
|
8
|
+
return result.stdout.strip() or None
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
class AgentsBuilderError(Exception):
|
|
2
|
+
"""Base exception for the package"""
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class MCPError(AgentsBuilderError):
|
|
6
|
+
pass
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class MCPNotConfiguredError(MCPError):
|
|
10
|
+
def __init__(self, tool_key: str):
|
|
11
|
+
super().__init__(f"No MCP configured for tool '{tool_key}'")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class MCPToolNotFoundError(MCPError):
|
|
15
|
+
def __init__(self, tool_key: str, mcp_name: str, available: list[str]):
|
|
16
|
+
super().__init__(f"Tool '{tool_key}' not found in MCP '{mcp_name}'. Available: {available}")
|
|
17
|
+
self.tool_key = tool_key
|
|
18
|
+
self.mcp_name = mcp_name
|
|
19
|
+
self.available = available
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
from langchain_core.language_models.chat_models import BaseChatModel
|
|
5
|
+
from langchain_core.messages import BaseMessage, HumanMessage, SystemMessage
|
|
6
|
+
from langchain_core.runnables import Runnable
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Prompt[TState](ABC):
|
|
10
|
+
SYSTEM_MESSAGE: str
|
|
11
|
+
|
|
12
|
+
@classmethod
|
|
13
|
+
@abstractmethod
|
|
14
|
+
def format_prompt(cls, state: TState) -> str: ...
|
|
15
|
+
|
|
16
|
+
@classmethod
|
|
17
|
+
def render(cls, state: TState) -> list[BaseMessage]:
|
|
18
|
+
if not cls.SYSTEM_MESSAGE:
|
|
19
|
+
raise NotImplementedError(f"{cls.__name__} must define SYSTEM_MESSAGE")
|
|
20
|
+
return [SystemMessage(content=cls.SYSTEM_MESSAGE), HumanMessage(content=cls.format_prompt(state))]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Node[TState]:
|
|
24
|
+
def __init__(self, name: str) -> None:
|
|
25
|
+
self.name = name
|
|
26
|
+
|
|
27
|
+
async def __call__(self, state: TState) -> Any:
|
|
28
|
+
raise NotImplementedError
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class RouterNode[TState](Node[TState]):
|
|
32
|
+
async def __call__(self, state: TState) -> str:
|
|
33
|
+
raise NotImplementedError
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class LLMNode[TState](Node[TState]):
|
|
37
|
+
def __init__(
|
|
38
|
+
self,
|
|
39
|
+
name: str,
|
|
40
|
+
model: BaseChatModel,
|
|
41
|
+
prompt: type[Prompt[TState]],
|
|
42
|
+
structured_output: dict[str, Any] | type | None = None,
|
|
43
|
+
) -> None:
|
|
44
|
+
super().__init__(name)
|
|
45
|
+
self.runnable: Runnable = model.with_structured_output(structured_output) if structured_output else model
|
|
46
|
+
self.prompt = prompt
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
from typing import Self
|
|
3
|
+
|
|
4
|
+
from langchain_core.language_models.chat_models import BaseChatModel
|
|
5
|
+
|
|
6
|
+
from agents_builder.llm.exceptions import StreamingNotSupportedError
|
|
7
|
+
from agents_builder.llm.settings import LLMSettings
|
|
8
|
+
from agents_builder.mixins import FromConfigMixin
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class LLM[TConfig: LLMSettings](FromConfigMixin[TConfig], ABC):
|
|
12
|
+
def __init__(self, config: TConfig):
|
|
13
|
+
super().__init__(config)
|
|
14
|
+
|
|
15
|
+
@abstractmethod
|
|
16
|
+
def to_langchain(self) -> BaseChatModel: ...
|
|
17
|
+
|
|
18
|
+
def with_streaming(self, streaming: bool = True) -> Self:
|
|
19
|
+
raise StreamingNotSupportedError("Streaming not supported for this LLM")
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from agents_builder.exceptions import AgentsBuilderError
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class LLMError(AgentsBuilderError):
|
|
5
|
+
pass
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class InvalidLLMRoleError(LLMError):
|
|
9
|
+
def __init__(self, role: str, available: list[str]):
|
|
10
|
+
super().__init__(f"LLM role '{role}' not defined. Available roles: {available}")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class InvalidLLMClassError(LLMError):
|
|
14
|
+
pass
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class StreamingNotSupportedError(LLMError):
|
|
18
|
+
pass
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
from agents_builder.llm import LLM
|
|
5
|
+
from agents_builder.llm.exceptions import InvalidLLMClassError, InvalidLLMRoleError
|
|
6
|
+
from agents_builder.llm.settings import LLMFactorySettings
|
|
7
|
+
from agents_builder.mixins import FromConfigMixin
|
|
8
|
+
from agents_builder.utils import load_class
|
|
9
|
+
|
|
10
|
+
_logger = logging.getLogger(__name__)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class LLMFactory(FromConfigMixin[LLMFactorySettings]):
|
|
14
|
+
def __init__(self, config: LLMFactorySettings):
|
|
15
|
+
super().__init__(config)
|
|
16
|
+
self._models: dict[str, LLM[Any]] = {}
|
|
17
|
+
_logger.info(f"LLMFactory initialized with roles: {list(self.config.roles.keys())}")
|
|
18
|
+
|
|
19
|
+
def get(self, role: str) -> LLM[Any]:
|
|
20
|
+
self._validate_role(role)
|
|
21
|
+
if role in self._models:
|
|
22
|
+
return self._models[role]
|
|
23
|
+
model = self._build_model(role)
|
|
24
|
+
self._models[role] = model
|
|
25
|
+
_logger.info(f"LLMFactory initialized role '{role}' successfully")
|
|
26
|
+
return model
|
|
27
|
+
|
|
28
|
+
def _validate_role(self, role: str) -> None:
|
|
29
|
+
if role not in self.config.roles:
|
|
30
|
+
available = list(self.config.roles.keys())
|
|
31
|
+
_logger.error(f"Invalid LLM role '{role}'. Available roles: {available}")
|
|
32
|
+
raise InvalidLLMRoleError(role, available)
|
|
33
|
+
_logger.debug(f"Validated LLM role '{role}'")
|
|
34
|
+
|
|
35
|
+
def _build_model(self, role: str) -> LLM[Any]:
|
|
36
|
+
role_config = self.config.roles[role]
|
|
37
|
+
llm_class = load_class(role_config.module_path)
|
|
38
|
+
if not isinstance(llm_class, type) or not issubclass(llm_class, LLM):
|
|
39
|
+
_logger.error(f"Loaded class '{role_config.module_path}' is not a subclass of LLM. Got: {llm_class}")
|
|
40
|
+
raise InvalidLLMClassError(
|
|
41
|
+
f"Loaded class '{role_config.module_path}' is not a subclass of LLM. Got: {llm_class}"
|
|
42
|
+
)
|
|
43
|
+
llm_instance = llm_class.from_config(role_config)
|
|
44
|
+
return llm_instance
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from typing import Self
|
|
3
|
+
|
|
4
|
+
from langchain_core.language_models.chat_models import BaseChatModel
|
|
5
|
+
from langchain_ollama import ChatOllama
|
|
6
|
+
from langchain_openrouter import ChatOpenRouter
|
|
7
|
+
|
|
8
|
+
from agents_builder.llm import LLM
|
|
9
|
+
from agents_builder.llm.settings import OllamaLLMSettings, OpenRouterLLMSettings
|
|
10
|
+
|
|
11
|
+
_logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class OllamaLLM(LLM[OllamaLLMSettings]):
|
|
15
|
+
def __init__(self, config: OllamaLLMSettings):
|
|
16
|
+
super().__init__(config)
|
|
17
|
+
|
|
18
|
+
def to_langchain(self) -> BaseChatModel:
|
|
19
|
+
model = ChatOllama(model=self.config.model, base_url=self.config.base_url)
|
|
20
|
+
_logger.info(f"Chat model ready: {self.config.model}")
|
|
21
|
+
return model
|
|
22
|
+
|
|
23
|
+
def with_streaming(self, streaming: bool = True) -> Self:
|
|
24
|
+
# Ollama streams based on call method (astream), not config
|
|
25
|
+
return self
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class OpenRouterLLM(LLM[OpenRouterLLMSettings]):
|
|
29
|
+
def __init__(self, config: OpenRouterLLMSettings):
|
|
30
|
+
super().__init__(config)
|
|
31
|
+
self.streaming = False
|
|
32
|
+
|
|
33
|
+
def with_streaming(self, streaming: bool = True) -> Self:
|
|
34
|
+
self.streaming = streaming
|
|
35
|
+
return self
|
|
36
|
+
|
|
37
|
+
def to_langchain(self) -> BaseChatModel:
|
|
38
|
+
_logger.info(f"Initializing OpenRouter model: {self.config.model}")
|
|
39
|
+
model = ChatOpenRouter(
|
|
40
|
+
model=self.config.model,
|
|
41
|
+
model_kwargs=self.config.model_kwargs,
|
|
42
|
+
openrouter_provider=self.config.provider, # raw dict
|
|
43
|
+
streaming=self.streaming,
|
|
44
|
+
)
|
|
45
|
+
_logger.info(f"OpenRouter Chat model ready: {self.config.model}")
|
|
46
|
+
return model
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
from typing import Annotated, Any, Literal
|
|
2
|
+
|
|
3
|
+
from pydantic import Field
|
|
4
|
+
|
|
5
|
+
from agents_builder.mixins import FromConfigMixinSettings
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class LLMSettings(FromConfigMixinSettings):
|
|
9
|
+
model: str
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class OllamaLLMSettings(LLMSettings):
|
|
13
|
+
module_path: str = "agents_builder.llm.llm.OllamaLLM"
|
|
14
|
+
kind: Literal["ollama"]
|
|
15
|
+
base_url: str
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class OpenRouterLLMSettings(LLMSettings):
|
|
19
|
+
module_path: str = "agents_builder.llm.llm.OpenRouterLLM"
|
|
20
|
+
kind: Literal["openrouter"]
|
|
21
|
+
model_kwargs: dict[str, Any]
|
|
22
|
+
provider: dict[str, Any] | None
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
AnyLLMSettings = Annotated[
|
|
26
|
+
OllamaLLMSettings | OpenRouterLLMSettings,
|
|
27
|
+
Field(discriminator="kind"),
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class LLMFactorySettings(FromConfigMixinSettings):
|
|
32
|
+
module_path: str = "agents_builder.llm.factory.LLMFactory"
|
|
33
|
+
roles: dict[str, AnyLLMSettings]
|
agents_builder/mixins.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
from typing import Any, Self, get_args
|
|
2
|
+
|
|
3
|
+
from pydantic_settings import (
|
|
4
|
+
BaseSettings,
|
|
5
|
+
PydanticBaseSettingsSource,
|
|
6
|
+
SettingsConfigDict,
|
|
7
|
+
YamlConfigSettingsSource,
|
|
8
|
+
)
|
|
9
|
+
|
|
10
|
+
from agents_builder.constants import CONFIG_PATH
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class FromConfigMixinSettings(BaseSettings):
|
|
14
|
+
module_path: str
|
|
15
|
+
model_config = SettingsConfigDict(
|
|
16
|
+
yaml_file=CONFIG_PATH,
|
|
17
|
+
extra="ignore",
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
@classmethod
|
|
21
|
+
def settings_customise_sources(
|
|
22
|
+
cls,
|
|
23
|
+
settings_cls: type[BaseSettings],
|
|
24
|
+
init_settings: PydanticBaseSettingsSource,
|
|
25
|
+
env_settings: PydanticBaseSettingsSource,
|
|
26
|
+
dotenv_settings: PydanticBaseSettingsSource,
|
|
27
|
+
file_secret_settings: PydanticBaseSettingsSource,
|
|
28
|
+
) -> tuple[PydanticBaseSettingsSource, ...]:
|
|
29
|
+
return (
|
|
30
|
+
init_settings,
|
|
31
|
+
YamlConfigSettingsSource(settings_cls),
|
|
32
|
+
env_settings,
|
|
33
|
+
dotenv_settings,
|
|
34
|
+
file_secret_settings,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class FromConfigMixin[TConfig: FromConfigMixinSettings]:
|
|
39
|
+
def __init__(self, config: TConfig) -> None:
|
|
40
|
+
self.config = config
|
|
41
|
+
|
|
42
|
+
@classmethod
|
|
43
|
+
def get_config_class(cls) -> type[TConfig]:
|
|
44
|
+
return get_args(cls.__orig_bases__[0])[0] # ty: ignore[missing-attribute]
|
|
45
|
+
|
|
46
|
+
@classmethod
|
|
47
|
+
def from_config(
|
|
48
|
+
cls,
|
|
49
|
+
config: TConfig,
|
|
50
|
+
) -> Self:
|
|
51
|
+
return cls(config)
|
|
52
|
+
|
|
53
|
+
@classmethod
|
|
54
|
+
def from_kwargs(cls, **kwargs: Any) -> Self:
|
|
55
|
+
"""
|
|
56
|
+
Load runtime object using Pydantic Settings resolution:
|
|
57
|
+
init > yaml > env > dotenv > secrets
|
|
58
|
+
"""
|
|
59
|
+
settings = cls.get_config_class()(**kwargs)
|
|
60
|
+
return cls.from_config(settings)
|
agents_builder/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
from pydantic_settings import BaseSettings
|
|
2
|
+
|
|
3
|
+
from agents_builder.llm.settings import LLMFactorySettings
|
|
4
|
+
from agents_builder.mixins import FromConfigMixinSettings
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class MCPServerSettings(BaseSettings):
|
|
8
|
+
name: str
|
|
9
|
+
url: str
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class AgentSettings(FromConfigMixinSettings):
|
|
13
|
+
llm_factory: LLMFactorySettings
|
|
14
|
+
mcps: list[MCPServerSettings]
|
agents_builder/utils.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import importlib
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from langchain_core.tools import BaseTool
|
|
6
|
+
from langchain_mcp_adapters.client import MultiServerMCPClient
|
|
7
|
+
|
|
8
|
+
from agents_builder.settings import MCPServerSettings
|
|
9
|
+
|
|
10
|
+
_mcp_tools_cache: dict[str, list[BaseTool]] = {}
|
|
11
|
+
_mcp_tools_lock = asyncio.Lock()
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def load_class(path: str) -> Any:
|
|
15
|
+
module_path, class_name = path.rsplit(".", 1)
|
|
16
|
+
module = importlib.import_module(module_path)
|
|
17
|
+
return getattr(module, class_name)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
async def _cached_mcp_tools(
|
|
21
|
+
mcps_fingerprint: str,
|
|
22
|
+
mcps_config: list[MCPServerSettings],
|
|
23
|
+
) -> list[BaseTool]:
|
|
24
|
+
# Fast path (already cached)
|
|
25
|
+
if mcps_fingerprint in _mcp_tools_cache:
|
|
26
|
+
return _mcp_tools_cache[mcps_fingerprint]
|
|
27
|
+
|
|
28
|
+
async with _mcp_tools_lock:
|
|
29
|
+
# Double-check inside lock
|
|
30
|
+
if mcps_fingerprint in _mcp_tools_cache:
|
|
31
|
+
return _mcp_tools_cache[mcps_fingerprint]
|
|
32
|
+
|
|
33
|
+
client = MultiServerMCPClient(
|
|
34
|
+
{ # ty: ignore[invalid-argument-type]
|
|
35
|
+
mcp.name: {
|
|
36
|
+
"transport": "http",
|
|
37
|
+
"url": mcp.url,
|
|
38
|
+
}
|
|
39
|
+
for mcp in mcps_config
|
|
40
|
+
}
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
tools = await client.get_tools()
|
|
44
|
+
_mcp_tools_cache[mcps_fingerprint] = tools
|
|
45
|
+
return tools
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: baiam-agents-builder
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Typed agent primitives and tracing for Baiam Agent
|
|
5
|
+
Requires-Python: <3.13,>=3.12
|
|
6
|
+
Requires-Dist: arize-phoenix-client<3.0.0,>=2.6.0
|
|
7
|
+
Requires-Dist: arize-phoenix-otel==0.13.1
|
|
8
|
+
Requires-Dist: langchain-core<2.0.0,>=1.8.4
|
|
9
|
+
Requires-Dist: langchain-mcp-adapters<0.4.0,>=0.3.2
|
|
10
|
+
Requires-Dist: langchain-ollama<2.0.0,>=1.1.0
|
|
11
|
+
Requires-Dist: langchain-openrouter<0.4.0,>=0.3.0
|
|
12
|
+
Requires-Dist: langgraph<1.3.0,>=1.2.24
|
|
13
|
+
Requires-Dist: opentelemetry-api<2.0.0,>=1.37.0
|
|
14
|
+
Requires-Dist: pydantic-settings<3.0.0,>=2.12.0
|
|
15
|
+
Requires-Dist: pydantic<3.0.0,>=2.12.5
|
|
16
|
+
Requires-Dist: pyyaml<7.0.0,>=6.0.2
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
|
|
19
|
+
# baiam-agents-builder
|
|
20
|
+
|
|
21
|
+
Typed agent primitives and tracing for Baiam Agent. Distribution name:
|
|
22
|
+
`baiam-agents-builder`; Python import namespace: `agents_builder`.
|
|
23
|
+
|
|
24
|
+
This is a separate project starting at version `0.1.0`, with a fresh Git history.
|
|
25
|
+
It retains the code needed by the current Baiam Agent checkout, plus the MCP and
|
|
26
|
+
Ollama features retained explicitly for future use.
|
|
27
|
+
|
|
28
|
+
## Included API
|
|
29
|
+
|
|
30
|
+
- `Agent`: configuration, cached LLM factory, lazy graph construction,
|
|
31
|
+
`load_tool()` with MCP caching, and `push()` to save a graph image.
|
|
32
|
+
- `Prompt`, `Node`, `RouterNode`, and `LLMNode`: primitives for Baiam's own nodes.
|
|
33
|
+
- `LLM`, `LLMFactory`, `OpenRouterLLM`, and `OllamaLLM`, with validated settings.
|
|
34
|
+
- `FromConfigMixin`: `from_config()`, `from_kwargs()`, and `get_config_class()`.
|
|
35
|
+
- `TraceAnnotator` and `PhoenixTraceAnnotator`, including Git revision labels.
|
|
36
|
+
|
|
37
|
+
The old retrieval nodes/states, deletion strategies, message/context helpers,
|
|
38
|
+
agent/node evaluation frameworks, and unused type aliases are excluded.
|
|
39
|
+
Baiam keeps its own evaluation runners, assertions, and trajectories.
|
|
40
|
+
|
|
41
|
+
The package uses `langchain-core` directly. OpenEvals belongs to Baiam's own
|
|
42
|
+
evaluation code and is not a runtime dependency here.
|
|
43
|
+
|
|
44
|
+
## Use from Baiam Agent
|
|
45
|
+
|
|
46
|
+
In the sibling `baiam-agent` checkout:
|
|
47
|
+
|
|
48
|
+
```sh
|
|
49
|
+
uv remove agents-builder
|
|
50
|
+
uv add --editable ../baiam-agents-builder
|
|
51
|
+
uv add 'openevals>=0.2.0,<1.0.0'
|
|
52
|
+
make ci
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Existing `agents_builder` imports and YAML module paths remain valid. Replace the
|
|
56
|
+
old distribution rather than installing both: they provide the same Python
|
|
57
|
+
namespace. For deployment, publish this distribution and replace the local path
|
|
58
|
+
with a version constraint on `baiam-agents-builder`.
|
|
59
|
+
|
|
60
|
+
Configuration precedence remains explicit constructor values, YAML at
|
|
61
|
+
`/config/config.yaml`, environment variables, dotenv, then secrets. Baiam also
|
|
62
|
+
provides its own YAML loading through `load_component()` and agent settings.
|
|
63
|
+
|
|
64
|
+
## Development
|
|
65
|
+
|
|
66
|
+
Requires Python 3.12 and [uv](https://docs.astral.sh/uv/).
|
|
67
|
+
|
|
68
|
+
```sh
|
|
69
|
+
uv lock
|
|
70
|
+
make dev-install
|
|
71
|
+
make ci
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Use `make help` to list the available development commands.
|
|
75
|
+
|
|
76
|
+
`make ci` checks lint and formatting, types, security, tests with at least 95%
|
|
77
|
+
branch-aware coverage, and both source and wheel builds. Tests cover graph
|
|
78
|
+
execution, MCP caching, configuration, provider construction, and tracing. They
|
|
79
|
+
do not contact live Ollama, OpenRouter, MCP, or Phoenix services.
|
|
80
|
+
|
|
81
|
+
## CI and publishing
|
|
82
|
+
|
|
83
|
+
The GitLab pipeline uses the same Makefile targets as local development. It runs
|
|
84
|
+
for merge requests, the default branch, and protected tags. Set the GitLab
|
|
85
|
+
default branch to `dev` when connecting this repository. Codecov upload runs only
|
|
86
|
+
when `CODECOV_TOKEN` is configured.
|
|
87
|
+
|
|
88
|
+
Publishing is manual; CI builds artifacts without publishing a release. After
|
|
89
|
+
confirming that the distribution name is available on PyPI and the token account
|
|
90
|
+
can publish it, run:
|
|
91
|
+
|
|
92
|
+
```sh
|
|
93
|
+
read -rsp 'PyPI token: ' UV_PUBLISH_TOKEN
|
|
94
|
+
echo
|
|
95
|
+
export UV_PUBLISH_TOKEN
|
|
96
|
+
./scripts/publish.sh 0.1.1
|
|
97
|
+
unset UV_PUBLISH_TOKEN
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
The script updates the version in `pyproject.toml` and `uv.lock`, builds into
|
|
101
|
+
`dist/<version>/`, and publishes only that version's wheel and source distribution.
|
|
102
|
+
Run `make ci` before publishing, then commit the version files after a successful
|
|
103
|
+
release.
|
|
104
|
+
|
|
105
|
+
This reduced package is derived from the local `agents-builder` codebase. The
|
|
106
|
+
original project and the Baiam Agent checkout are not modified by its creation.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
agents_builder/__init__.py,sha256=i0-YtVRBoEy01TMtXrELpfGDpRymunKMsQFo2-HApXA,3003
|
|
2
|
+
agents_builder/constants.py,sha256=FdGnKzE1xL6E2zhPIPmzwEBqjjYRZFZUEPhAhDhz3_E,36
|
|
3
|
+
agents_builder/exceptions.py,sha256=u5zouGRrLTC-ZVTEje-H3izrgUgrFB5_YArXSn8zjt0,592
|
|
4
|
+
agents_builder/mixins.py,sha256=jQeMW1f-TMIc3_f18rd9msULw5FKfTtoDXH7peJ1FG8,1659
|
|
5
|
+
agents_builder/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
agents_builder/settings.py,sha256=f0wDzyGLe4vkTBS4Ko_1YMTK4JsEiU_MuJLjTKmi8wk,347
|
|
7
|
+
agents_builder/utils.py,sha256=BBYpFaJSBh3NiHegeel_yeV3ihQSxVomBvMOBCaE99M,1285
|
|
8
|
+
agents_builder/eval/__init__.py,sha256=G4GnFzW8t0v2ntQxC60qBXx3t8x75oX5wGiamb24xnI,2263
|
|
9
|
+
agents_builder/eval/annotator.py,sha256=tIlhILwbD_nEX4VxSVynPbGiMIe9cHYTs1VAT7l6kBU,1596
|
|
10
|
+
agents_builder/eval/exceptions.py,sha256=isnHW54vCpHuD4HFKgF9LxtMbk6_8LaFaJw_sn3r-zs,322
|
|
11
|
+
agents_builder/eval/settings.py,sha256=kHFXhTkiSw7q7SagdJ3KL7fCauTs3TaAki7Bhsz3QBQ,631
|
|
12
|
+
agents_builder/eval/utils.py,sha256=oCirFV3W8DzHZZ8D8MWmrwmjjEsu0KaQw19KFt7OZd4,281
|
|
13
|
+
agents_builder/langgraph/__init__.py,sha256=CFDVd8OyuPavdUQ2l9BULwhWOAHKRgTLX8CIFlBbGtc,1414
|
|
14
|
+
agents_builder/llm/__init__.py,sha256=ylnKX8wRIEAxfyxbQgExLFT0DvEiwQmKs_P8pLPzM-0,656
|
|
15
|
+
agents_builder/llm/exceptions.py,sha256=GJ9OvCHCg3YT7rATdD0q5-niFbh-ybHWgtwWH967Up4,393
|
|
16
|
+
agents_builder/llm/factory.py,sha256=B_8kZwo8ASdAc3OC-dJB65JbbOfXxPm6f-7ByIeKL_A,1882
|
|
17
|
+
agents_builder/llm/llm.py,sha256=PQAAP8HeDG459r0kdZ08HPIhAIbJjiv-74N_SopQ6I0,1583
|
|
18
|
+
agents_builder/llm/settings.py,sha256=Bv4YOzd3oyQ5QfVMqlp1Hq17MbtBsHqRncB_sq15qd8,807
|
|
19
|
+
baiam_agents_builder-0.1.0.dist-info/METADATA,sha256=K9krk8gO48HK5CfEf1gv9K9styncUdvhD64O2Py5rhA,4112
|
|
20
|
+
baiam_agents_builder-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
21
|
+
baiam_agents_builder-0.1.0.dist-info/RECORD,,
|