에이전트 인스턴스화 및 Aidputil 패키지 사용
다음 샘플은 aidputil 패키지로 에이전트를 만들고 사용하는 방법을 보여줍니다.
from aidputils.agents.toolkit.agent_helper import invoke, get_client
from aidputils.agents.toolkit.configs import OCIAIConf
from langchain_core.tools import StructuredTool
from langgraph.prebuilt import create_react_agent
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage
from langchain_community.chat_models.oci_generative_ai import ChatOCIGenAI
import logging
import json
logger = logging.getLogger('muse_agent_flow')
checkpointer = globals().get("checkpointer", None)
########## Guardrails Configuration ################
guardrails_config = {
"name" : "Default Guardrails",
"description" : "Default empty guardrails configuration",
"policies" : [ ]
}
########## End Guardrails Configuration ############
########## Start Generated code for Agent Flow ################
##### Start Tool configuration for blog_idea_tool
##### Start PROMPT Tool configuration
blog_idea_tool_def = {
"llm": {
"model_id" : "<your-model-id>",
"model_provider" : "cohere",
"compartment_id" : "<your-compartment-ocid>",
"endpoint" : "https://inference.generativeai.<oci-region>.oci.oraclecloud.com",
"auth_type" : "SECURITY_TOKEN",
"auth_profile" : "DEFAULT",
"model_args" : {
"temperature" : 1,
"max_tokens" : 600,
"frequency_penalty" : 0,
"presence_penalty" : 0,
"top_k" : 0,
"top_p" : 0.75
}
}, "prompt_template": """
You are a master blog strategist.
Your task is to brainstorm compelling blog post ideas based on a given topic.
For the given {topic}, generate 5 unique blog post titles.
For each title, include a one-sentence description of the angle the post would take.
Present the output as a numbered list.
"""
}
blog_idea_tool_params = [ {
"name" : "topic",
"type" : "string",
"description" : "The central theme or subject for which to generate blog ideas."
} ]
blog_idea_tool_dict = {
"name": "blog_idea_tool",
"description": "Use this tool to generate several distinct and engaging blog post titles and concepts based on a topic ",
"tool_class": "PromptTool",
"conf": blog_idea_tool_def,
"params": blog_idea_tool_params
}
blog_idea_tool = create_langgraph_tool(blog_idea_tool_dict)
##### End PROMPT Tool configuration
# Set tool_var_name = blog_idea_tool
# set ns.tool_var_list = [blog_idea_tool]
##### End Tool configuration for Blog idea tool
##### End Tool configuration
##### Start tool List#############
tools_agent1 = [blog_idea_tool]
##### End tool List#############
########## Generated code for OCI Gen AI LLM
model_args = {
"temperature" : 0.8,
"max_tokens" : 500,
"frequency_penalty" : 0,
"presence_penalty" : 0,
"top_p" : 1.0,
"top_k" : 0
}
llm_conf = OCIAIConf(model_provider='cohere',
compartment_id='<your-compartment-ocid>',
auth_type='SECURITY_TOKEN',
auth_profile='DEFAULT',
model_args=model_args,
endpoint='https://inference.generativeai.<oci-region>.oci.oraclecloud.com',
model_id='<your-model-id>')
## Agent class definition
class MuseAgentFlow:
def __init__(self) -> None:
self.agent = None
def setup(self) -> None:
# TODO: Handle other kinds of llms, for example openAI or gemini
oci_llm = init_oci_llm(llm_conf)
system_prompt = """
**Task:**
For the given {topic}, generate 5 unique blog post titles. For each title, include a one-sentence description of the angle the post would take. Present the output as a numbered list.
**Example Input:**
topic: "AI in marketing"
**Example Output:**
1. **Title:** "Beyond the Hype: 3 Practical Ways to Use AI in Your Marketing Today"
* **Angle:** This post will focus on simple, actionable AI tools that small businesses can implement immediately.
2. **Title:** "Is AI Coming for Your Marketing Job? A Realistic Look at the Future"
* * **Angle:** This post will explore how AI will change marketing roles, not just replace them, focusing on new skills.
3. **Title:** "We Let an AI Write Our Marketing Emails for a Week. Here's What Happened."
* * **Angle:** A case-study style post detailing the results of an interesting experiment.
4. **Title:** "The Ethics of AI Marketing: Are You Crossing a Line with Personalization?"
* **Angle:** A thought-leadership piece that discusses the important ethical considerations of using AI.
5. **Title:** "How to Personalize at Scale: A Guide to AI-Powered Customer Journeys"
* **Angle:** A tactical guide on using AI to create highly personalized marketing campaigns.
"""
try:
if checkpointer:
self.agent =create_react_agent(model=oci_llm, tools=tools_agent1, prompt=system_prompt, debug=True, checkpointer= checkpointer)
else:
self.agent = self.agent = create_react_agent(model=oci_llm, tools=tools_agent1, prompt=system_prompt, debug=True)
except Exception as e:
# Fallback compile without checkpointer if wiring fails
self.agent = create_react_agent(model=oci_llm, tools=tools_agent1, prompt=system_prompt, debug=True)
logger.warning(f"Checkpointer could not be initialized {e}")
logger.info(f"Setup for agent completed {self.agent}")
async def invoke(self, user_query: str, **kwargs):
try:
return await self.agent.invoke(input=user_query, **kwargs)
except Exception as e:
logger.error(f"Exception while calling invoke {e}")
def init_oci_llm(llm_conf: OCIAIConf):
chat = ChatOCIGenAI(
model_id='<your-model-id>',
provider='cohere',
service_endpoint='https://inference.generativeai.<oci-region>.oci.oraclecloud.com',
compartment_id='<your-compartment-ocid>',
client=get_client(llm_conf=llm_conf),
model_kwargs=model_args
)
return chat
def create_langgraph_tool(tool):
def tool_fn(**kwargs):
# Example implementation: you would use utils.call_tool_by_name/tool runner, etc.
return f"Executed {tool['name']} with inputs: {kwargs}"
return StructuredTool.from_function(
func=tool_fn,
name=tool['name'],
description=tool['description'],
args_schema=None, # Build a pydantic schema if detailed validation required
infer_schema=False
)