File size: 2,316 Bytes
a438cae 3fd974b a438cae 3fd974b a438cae 3fd974b a438cae 3fd974b a438cae 3fd974b a438cae 3fd974b a438cae |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
import logging
from typing import List, TypeVar, Optional
from langchain_core.messages import AnyMessage, BaseMessage, SystemMessage
from pydantic import BaseModel
from langchain_core.tools import BaseTool
from langchain_openai import ChatOpenAI
OutStruct = TypeVar(name="OutStruct", bound=BaseModel)
class AgentBlueprint:
def __init__(
self,
agent_name: str,
*,
system_prompt: str = "",
tools: List[BaseTool] = None,
description: str = "",
base_url: Optional[str] = None,
llm: ChatOpenAI,
):
self.agent_name = agent_name
self.system_prompt = system_prompt
self.llm = llm
self.agent_description = description
if tools:
self.llm = self.llm.bind_tools(tools)
self.tools = {tool.name: tool for tool in tools}
self.logger = logging.getLogger(self.__class__.__name__)
def __set_system_prompt(self, messages: List[AnyMessage]):
if self.system_prompt:
return [SystemMessage(content=self.system_prompt)] + messages
return messages
def call_agent(self, messages: List[AnyMessage]) -> BaseMessage:
response = self.llm.with_retry(stop_after_attempt=2).invoke(
input=self.__set_system_prompt(messages)
)
response.name = self.agent_name
return response
async def acall_agent(self, messages: List[AnyMessage]) -> BaseMessage:
response = await self.llm.with_retry(stop_after_attempt=2).ainvoke(
input=self.__set_system_prompt(messages)
)
response.name = self.agent_name
return response
def call_agent_structured(
self, messages: List[AnyMessage], clazz: OutStruct
) -> OutStruct:
response = (
self.llm.with_structured_output(clazz)
.with_retry(stop_after_attempt=2)
.invoke(input=self.__set_system_prompt(messages))
)
return response
async def acall_agent_structured(
self, messages: List[AnyMessage], clazz: OutStruct
) -> OutStruct:
response = (
await self.llm.with_structured_output(clazz)
.with_retry(stop_after_attempt=2)
.ainvoke(input=self.__set_system_prompt(messages))
)
return response
|