Authors: Julia Wiesinger, Patrick Marlow and Vladimir Vuskovic 저자: 저자: 줄리아 비싱어, 패트릭 말로우, 블라디미르 부스코비치
Google
Acknowledgements 감사
Reviewers and Contributors 검토자 및 기여자Evan Huang 에반 황Emily XueOlcan Sercinoglu 올칸 세르시노글루Sebastian Riedel 세바스찬 리델Satinder Baveja 사틴더 바베야Antonio Gulli 안토니오 굴리Anant Nawalgaria 아난트 나왈가리아Curators and Editors 큐레이터 및 편집자Antonio Gulli 안토니오 굴리Anant Nawalgaria 아난트 나왈가리아Grace Mollison 그레이스 몰리슨Technical Writer 테크니컬 라이터Joey Haymaker 조이 헤이메이커Designer 디자이너Michael Lanning 마이클 래닝
Table of contents 목차
Introduction … 4 소개 ... 4
What is an agent? … 5 에이전트란 무엇인가요? ... 5
The model … 6 모델 ... 6
The tools … 7 도구 ... 7
The orchestration layer … 7 오케스트레이션 레이어 ... 7
Agents vs. models … 8 상담원 대 모델 ... 8
Cognitive architectures: How agents operate … 8 인지 아키텍처: 에이전트 작동 방식 ... 8
Tools: Our keys to the outside world … 12 도구: 도구: 외부 세계로 가는 열쇠 ... 12
Extensions … 13 확장 기능 ... 13
Sample Extensions … 15 샘플 확장... 15
Functions … 18 기능 ... 18
Use cases … 21 사용 사례 ... 21
Function sample code … 24 함수 샘플 코드 ... 24
Data stores … 27 데이터 저장소 ... 27
Implementation and application … 28 구현 및 적용 ... 28
Tools recap … 32 도구 요약 ... 32
Enhancing model performance with targeted learning … 33 목표 학습으로 모델 성능 향상 ... 33
Agent quick start with LangChain … 35 LangChain으로 에이전트 빠른 시작 ... 35
Production applications with Vertex AI agents … 38 버텍스 AI 에이전트를 사용한 프로덕션 애플리케이션 ... 38
Summary … 40 요약 ... 40
Endnotes … 42 각주 ... 42
This combination of reasoning, logic, and access to external information that are all connected to a Generative Al model invokes the concept of an agent. 이러한 추론, 논리, 외부 정보에 대한 액세스의 조합은 모두 제너레이티브 알 모델에 연결되어 에이전트라는 개념을 불러옵니다.
Introduction 소개
Humans are fantastic at messy pattern recognition tasks. However, they often rely on tools - like books, Google Search, or a calculator - to supplement their prior knowledge before arriving at a conclusion. Just like humans, Generative AI models can be trained to use tools to access real-time information or suggest a real-world action. For example, a model can leverage a database retrieval tool to access specific information, like a customer’s purchase history, so it can generate tailored shopping recommendations. Alternatively, based on a user’s query, a model can make various API calls to send an email response to a colleague or complete a financial transaction on your behalf. To do so, the model must not only have access to a set of external tools, it needs the ability to plan and execute any task in a selfdirected fashion. This combination of reasoning, logic, and access to external information that are all connected to a Generative Al model invokes the concept of an agent, or a program that extends beyond the standalone capabilities of a Generative AI model. This whitepaper dives into all these and associated aspects in more detail. 인간은 복잡한 패턴 인식 작업에 능숙합니다. 하지만 결론에 도달하기 전에 사전 지식을 보완하기 위해 책, Google 검색 또는 계산기와 같은 도구에 의존하는 경우가 많습니다. 인간과 마찬가지로 제너레이티브 AI 모델도 도구를 사용하여 실시간 정보에 액세스하거나 실제 행동을 제안하도록 학습시킬 수 있습니다. 예를 들어, 모델은 데이터베이스 검색 도구를 활용하여 고객의 구매 내역과 같은 특정 정보에 액세스하여 맞춤형 쇼핑 추천을 생성할 수 있습니다. 또는 사용자의 쿼리를 기반으로 모델이 다양한 API 호출을 수행하여 동료에게 이메일 응답을 보내거나 사용자를 대신하여 금융 거래를 완료할 수 있습니다. 이를 위해서는 모델이 일련의 외부 도구에 액세스할 수 있어야 할 뿐만 아니라 자기 주도적인 방식으로 모든 작업을 계획하고 실행할 수 있는 능력이 필요합니다. 이러한 추론, 논리, 외부 정보에 대한 액세스의 조합은 모두 생성형 Al 모델에 연결되어 에이전트 또는 생성형 AI 모델의 독립형 기능을 뛰어넘는 프로그램이라는 개념을 불러일으킵니다. 이 백서에서는 이러한 모든 측면과 관련 측면에 대해 자세히 설명합니다.
What is an agent? 에이전트란 무엇인가요?
In its most fundamental form, a Generative AI agent can be defined as an application that attempts to achieve a goal by observing the world and acting upon it using the tools that it has at its disposal. Agents are autonomous and can act independently of human intervention, especially when provided with proper goals or objectives they are meant to achieve. Agents can also be proactive in their approach to reaching their goals. Even in the absence of explicit instruction sets from a human, an agent can reason about what it should do next to achieve its ultimate goal. While the notion of agents in AI is quite general and powerful, this whitepaper focuses on the specific types of agents that Generative AI models are capable of building at the time of publication. 가장 기본적인 형태인 생성형 AI 에이전트는 세상을 관찰하고 주어진 도구를 사용하여 행동함으로써 목표를 달성하려는 애플리케이션으로 정의할 수 있습니다. 에이전트는 자율적이며 특히 달성해야 할 적절한 목표나 목적이 주어지면 사람의 개입 없이도 독립적으로 행동할 수 있습니다. 또한 에이전트는 목표 달성을 위해 능동적으로 대처할 수 있습니다. 에이전트는 인간의 명시적인 지침이 없더라도 궁극적인 목표를 달성하기 위해 다음에 수행해야 할 작업을 추론할 수 있습니다. AI에서 에이전트의 개념은 매우 일반적이고 강력하지만, 이 백서는 발행 시점에 제너레이티브 AI 모델이 구축할 수 있는 특정 유형의 에이전트에 초점을 맞추고 있습니다.
In order to understand the inner workings of an agent, let’s first introduce the foundational components that drive the agent’s behavior, actions, and decision making. The combination of these components can be described as a cognitive architecture, and there are many such architectures that can be achieved by the mixing and matching of these components. Focusing on the core functionalities, there are three essential components in an agent’s cognitive architecture as shown in Figure 1. 에이전트의 내부 작동을 이해하기 위해 먼저 에이전트의 행동, 작업 및 의사 결정을 주도하는 기본 구성 요소를 소개해 보겠습니다. 이러한 구성 요소의 조합을 인지 아키텍처라고 할 수 있으며, 이러한 구성 요소의 혼합과 조합을 통해 달성할 수 있는 아키텍처는 여러 가지가 있습니다. 핵심 기능을 중심으로 에이전트의 인지 아키텍처에는 그림 1과 같이 세 가지 필수 구성 요소가 있습니다.
Figure 1. General agent architecture and components 그림 1. 일반 에이전트 아키텍처 및 구성 요소
The model 모델
In the scope of an agent, a model refers to the language model (LM) that will be utilized as the centralized decision maker for agent processes. The model used by an agent can be one or multiple LM’s of any size (small / large) that are capable of following instruction based reasoning and logic frameworks, like ReAct, Chain-of-Thought, or Tree-of-Thoughts. Models can be general purpose, multimodal or fine-tuned based on the needs of your specific agent architecture. For best production results, you should leverage a model that best fits your desired end application and, ideally, has been trained on data signatures associated with the tools that you plan to use in the cognitive architecture. It’s important to note that the model is typically not trained with the specific configuration settings (i.e. tool choices, orchestration/ reasoning setup) of the agent. However, it’s possible to further refine the model for the agent’s tasks by providing it with examples that showcase the agent’s capabilities, including instances of the agent using specific tools or reasoning steps in various contexts. 에이전트의 범위에서 모델은 에이전트 프로세스의 중앙 집중식 의사 결정자로 활용되는 언어 모델(LM)을 의미합니다. 상담원이 사용하는 모델은 ReAct, Chain-of-Thought 또는 Tree-of-Thought와 같은 명령어 기반 추론 및 논리 프레임워크를 따를 수 있는 모든 크기(소형/대형)의 하나 또는 여러 개의 LM이 될 수 있습니다. 모델은 범용, 멀티모달 또는 특정 에이전트 아키텍처의 요구 사항에 따라 미세 조정할 수 있습니다. 최상의 제작 결과를 얻으려면 원하는 최종 애플리케이션에 가장 적합한 모델을 활용해야 하며, 인지 아키텍처에서 사용하려는 도구와 관련된 데이터 서명에 대해 학습된 모델을 사용하는 것이 가장 이상적입니다. 이 모델은 일반적으로 에이전트의 특정 구성 설정(예: 도구 선택, 오케스트레이션/추론 설정)에 대해 학습되지 않는다는 점에 유의해야 합니다. 하지만 다양한 상황에서 특정 툴이나 추론 단계를 사용하는 에이전트의 인스턴스 등 에이전트의 기능을 보여주는 예제를 제공함으로써 에이전트의 작업에 대한 모델을 더욱 세분화할 수 있습니다.
The tools 도구
Foundational models, despite their impressive text and image generation, remain constrained by their inability to interact with the outside world. Tools bridge this gap, empowering agents to interact with external data and services while unlocking a wider range of actions beyond that of the underlying model alone. Tools can take a variety of forms and have varying depths of complexity, but typically align with common web API methods like GET, POST, PATCH, and DELETE. For example, a tool could update customer information in a database or fetch weather data to influence a travel recommendation that the agent is providing to the user. With tools, agents can access and process real-world information. This empowers them to support more specialized systems like retrieval augmented generation (RAG), which significantly extends an agent’s capabilities beyond what the foundational model can achieve on its own. We’ll discuss tools in more detail below, but the most important thing to understand is that tools bridge the gap between the agent’s internal capabilities and the external world, unlocking a broader range of possibilities. 기본 모델은 인상적인 텍스트와 이미지 생성에도 불구하고 외부 세계와 상호 작용할 수 없다는 제약이 있습니다. 도구는 이러한 격차를 해소하여 에이전트가 외부 데이터 및 서비스와 상호 작용할 수 있도록 지원하는 동시에 기본 모델만으로는 할 수 없는 더 광범위한 작업을 수행할 수 있도록 해줍니다. 도구는 다양한 형태와 다양한 복잡성을 가질 수 있지만 일반적으로 GET, POST, PATCH, DELETE와 같은 일반적인 웹 API 메서드와 일치합니다. 예를 들어 도구는 데이터베이스의 고객 정보를 업데이트하거나 날씨 데이터를 가져와 상담원이 사용자에게 제공하는 여행 추천에 영향을 줄 수 있습니다. 툴을 통해 상담원은 실제 정보에 액세스하고 처리할 수 있습니다. 이를 통해 검색 증강 생성(RAG)과 같은 보다 전문적인 시스템을 지원할 수 있으며, 기본 모델 자체에서 달성할 수 있는 것 이상으로 상담원의 역량을 크게 확장할 수 있습니다. 아래에서 툴에 대해 자세히 설명하지만 가장 중요한 것은 툴이 에이전트의 내부 역량과 외부 세계 사이의 격차를 해소하여 더 넓은 범위의 가능성을 열어준다는 점입니다.
The orchestration layer 오케스트레이션 레이어
The orchestration layer describes a cyclical process that governs how the agent takes in information, performs some internal reasoning, and uses that reasoning to inform its next action or decision. In general, this loop will continue until an agent has reached its goal or a stopping point. The complexity of the orchestration layer can vary greatly depending on the agent and task it’s performing. Some loops can be simple calculations with decision rules, while others may contain chained logic, involve additional machine learning algorithms, or implement other probabilistic reasoning techniques. We’ll discuss more about the detailed implementation of the agent orchestration layers in the cognitive architecture section. 오케스트레이션 계층은 에이전트가 정보를 받아들이고, 내부 추론을 수행하고, 그 추론을 사용하여 다음 작업이나 결정을 내리는 방법을 관리하는 주기적인 프로세스를 설명합니다. 일반적으로 이 루프는 에이전트가 목표 또는 중단 지점에 도달할 때까지 계속됩니다. 오케스트레이션 계층의 복잡성은 에이전트와 수행하는 작업에 따라 크게 달라질 수 있습니다. 일부 루프는 의사 결정 규칙이 있는 단순한 계산일 수 있는 반면, 다른 루프는 연쇄 로직을 포함하거나 추가적인 머신 러닝 알고리즘을 포함하거나 기타 확률적 추론 기법을 구현할 수 있습니다. 인지 아키텍처 섹션에서 에이전트 오케스트레이션 계층의 세부 구현에 대해 자세히 설명하겠습니다.
Agents vs. models 상담원 대 모델
To gain a clearer understanding of the distinction between agents and models, consider the following chart: 상담원과 모델의 차이점을 더 명확하게 이해하려면 다음 차트를 참조하세요:
Models 모델
Agents 상담원
지식은 학습 데이터에서 사용할 수 있는 것으로 제한됩니다.
Knowledge is limited to what is available in their
training data.
Knowledge is limited to what is available in their
training data.| Knowledge is limited to what is available in their |
| :--- |
| training data. |
도구를 통한 외부 시스템과의 연결을 통해 지식을 확장합니다.
Knowledge is extended through the connection
with external systems via tools
Knowledge is extended through the connection
with external systems via tools| Knowledge is extended through the connection |
| :--- |
| with external systems via tools |
사용자 쿼리를 기반으로 한 단일 추론/예측. 모델에 명시적으로 구현되지 않는 한, 세션 기록이나 지속적인 컨텍스트는 관리되지 않습니다. (예: 채팅 기록)
Single inference / prediction based on the
user query. Unless explicitly implemented for
the model, there is no management of session
history or continuous context. (i.e. chat history)
Single inference / prediction based on the
user query. Unless explicitly implemented for
the model, there is no management of session
history or continuous context. (i.e. chat history)| Single inference / prediction based on the |
| :--- |
| user query. Unless explicitly implemented for |
| the model, there is no management of session |
| history or continuous context. (i.e. chat history) |
관리되는 세션 기록(즉, 채팅 기록)을 통해 오케스트레이션 계층에서 이루어진 사용자 쿼리와 결정을 기반으로 다중 턴 추론/예측을 할 수 있습니다. 여기서 '턴'은 상호작용하는 시스템과 상담원 간의 상호 작용으로 정의됩니다. (즉, 하나의 수신 이벤트/
Managed session history (i.e. chat history) to
allow for multi turn inference / prediction based
on user queries and decisions made in the
orchestration layer. In this context, a 'turn' is
defined as an interaction between the interacting
system and the agent. (i.e. 1 incoming event/
Managed session history (i.e. chat history) to
allow for multi turn inference / prediction based
on user queries and decisions made in the
orchestration layer. In this context, a 'turn' is
defined as an interaction between the interacting
system and the agent. (i.e. 1 incoming event/| Managed session history (i.e. chat history) to |
| :--- |
| allow for multi turn inference / prediction based |
| on user queries and decisions made in the |
| orchestration layer. In this context, a 'turn' is |
| defined as an interaction between the interacting |
| system and the agent. (i.e. 1 incoming event/ |
query and 1 agent response) 쿼리 및 상담원 응답 1건)
Models Agents
"Knowledge is limited to what is available in their
training data." "Knowledge is extended through the connection
with external systems via tools"
"Single inference / prediction based on the
user query. Unless explicitly implemented for
the model, there is no management of session
history or continuous context. (i.e. chat history)" "Managed session history (i.e. chat history) to
allow for multi turn inference / prediction based
on user queries and decisions made in the
orchestration layer. In this context, a 'turn' is
defined as an interaction between the interacting
system and the agent. (i.e. 1 incoming event/"
query and 1 agent response) | Models | Agents |
| :--- | :--- |
| Knowledge is limited to what is available in their <br> training data. | Knowledge is extended through the connection <br> with external systems via tools |
| Single inference / prediction based on the <br> user query. Unless explicitly implemented for <br> the model, there is no management of session <br> history or continuous context. (i.e. chat history) | Managed session history (i.e. chat history) to <br> allow for multi turn inference / prediction based <br> on user queries and decisions made in the <br> orchestration layer. In this context, a 'turn' is <br> defined as an interaction between the interacting <br> system and the agent. (i.e. 1 incoming event/ |
| query and 1 agent response) | |
||
Cognitive architectures: How agents operate 인지 아키텍처: 상담원 운영 방식
Imagine a chef in a busy kitchen. Their goal is to create delicious dishes for restaurant patrons which involves some cycle of planning, execution, and adjustment. 바쁜 주방에서 일하는 셰프를 상상해 보세요. 그들의 목표는 레스토랑 고객을 위해 맛있는 요리를 만드는 것이며, 이를 위해 계획, 실행, 조정의 주기를 거칩니다.
They gather information, like the patron’s order and what ingredients are in the pantry and refrigerator. 고객의 주문, 식료품 저장실과 냉장고에 어떤 식재료가 있는지 등의 정보를 수집합니다.
They perform some internal reasoning about what dishes and flavor profiles they can create based on the information they have just gathered. 방금 수집한 정보를 바탕으로 어떤 요리와 맛 프로필을 만들 수 있는지 내부적으로 추론합니다.
They take action to create the dish: chopping vegetables, blending spices, searing meat. 야채를 자르고, 향신료를 섞고, 고기를 굽는 등 요리를 만들기 위한 작업을 수행합니다.
At each stage in the process the chef makes adjustments as needed, refining their plan as ingredients are depleted or customer feedback is received, and uses the set of previous outcomes to determine the next plan of action. This cycle of information intake, planning, executing, and adjusting describes a unique cognitive architecture that the chef employs to reach their goal. 셰프는 프로세스의 각 단계에서 필요에 따라 조정하고, 재료가 고갈되거나 고객의 피드백을 받으면 계획을 수정하며, 이전 결과 집합을 사용하여 다음 실행 계획을 결정합니다. 이러한 정보 수집, 계획, 실행, 조정의 주기는 셰프가 목표를 달성하기 위해 사용하는 고유한 인지 아키텍처를 설명합니다.
Just like the chef, agents can use cognitive architectures to reach their end goals by iteratively processing information, making informed decisions, and refining next actions based on previous outputs. At the core of agent cognitive architectures lies the orchestration layer, responsible for maintaining memory, state, reasoning and planning. It uses the rapidly evolving field of prompt engineering and associated frameworks to guide reasoning and planning, enabling the agent to interact more effectively with its environment and complete tasks. Research in the area of prompt engineering frameworks and task planning for language models is rapidly evolving, yielding a variety of promising approaches. While not an exhaustive list, these are a few of the most popular frameworks and reasoning techniques available at the time of this publication: 요리사와 마찬가지로 에이전트는 인지 아키텍처를 사용하여 정보를 반복적으로 처리하고, 정보에 기반한 결정을 내리고, 이전 결과를 바탕으로 다음 작업을 구체화함으로써 최종 목표를 달성할 수 있습니다. 에이전트 인지 아키텍처의 핵심에는 메모리, 상태, 추론 및 계획을 유지하는 오케스트레이션 계층이 있습니다. 이 계층은 빠르게 진화하는 프롬프트 엔지니어링 분야와 관련 프레임워크를 사용하여 추론과 계획을 안내함으로써 에이전트가 환경과 보다 효과적으로 상호 작용하고 작업을 완료할 수 있도록 지원합니다. 언어 모델에 대한 프롬프트 엔지니어링 프레임워크 및 작업 계획 분야의 연구는 빠르게 발전하고 있으며, 다양한 유망한 접근 방식을 제시하고 있습니다. 전체 목록은 아니지만, 이 글을 쓰는 시점에서 가장 인기 있는 프레임워크와 추론 기법 몇 가지를 소개합니다:
ReAct, a prompt engineering framework that provides a thought process strategy for language models to Reason and take action on a user query, with or without in-context examples. ReAct prompting has shown to outperform several SOTA baselines and improve human interoperability and trustworthiness of LLMs. 언어 모델이 사용자 쿼리를 추론하고 조치를 취하기 위한 사고 프로세스 전략을 제공하는 프롬프트 엔지니어링 프레임워크인 ReAct는 문맥에 맞는 예제를 포함하거나 포함하지 않고도 사용자 쿼리를 추론할 수 있습니다. ReAct 프롬프트는 여러 SOTA 기준선을 능가하는 성능을 보였으며, 인간의 상호 운용성과 LLM의 신뢰성을 개선하는 것으로 나타났습니다.
Chain-of-Thought (CoT), a prompt engineering framework that enables reasoning capabilities through intermediate steps. There are various sub-techniques of CoT including self-consistency, active-prompt, and multimodal CoT that each have strengths and weaknesses depending on the specific application. 중간 단계를 통해 추론 기능을 구현하는 신속한 엔지니어링 프레임워크인 CoT(Chain-of-Thought)입니다. CoT에는 자체 일관성, 액티브 프롬프트, 멀티모달 CoT 등 다양한 하위 기술이 있으며, 각 기술은 특정 애플리케이션에 따라 장단점이 있습니다.
Tree-of-thoughts (TOT), a prompt engineering framework that is well suited for exploration or strategic lookahead tasks. It generalizes over chain-of-thought prompting and allows the model to explore various thought chains that serve as intermediate steps for general problem solving with language models. 생각의 나무(TOT)는 탐색 또는 전략적 탐색 작업에 적합한 프롬프트 엔지니어링 프레임워크입니다. 생각의 사슬 프롬프트를 일반화하여 언어 모델을 사용하여 일반적인 문제 해결을 위한 중간 단계 역할을 하는 다양한 생각의 사슬을 탐색할 수 있도록 합니다.
Agents can utilize one of the above reasoning techniques, or many other techniques, to choose the next best action for the given user request. For example, let’s consider an agent that is programmed to use the ReAct framework to choose the correct actions and tools for the user query. The sequence of events might go something like this: 상담원은 위의 추론 기법 중 하나 또는 다른 여러 기법을 활용하여 주어진 사용자 요청에 대한 차선책을 선택할 수 있습니다. 예를 들어 사용자 쿼리에 대해 올바른 작업과 도구를 선택하기 위해 ReAct 프레임워크를 사용하도록 프로그래밍된 상담원을 생각해 봅시다. 이벤트 순서는 다음과 같이 진행될 수 있습니다:
User sends query to the agent 사용자가 상담원에게 쿼리를 보냅니다.
Agent begins the ReAct sequence 에이전트가 ReAct 시퀀스를 시작합니다.
The agent provides a prompt to the model, asking it to generate one of the next ReAct steps and its corresponding output: 에이전트는 모델에 다음 ReAct 단계 중 하나와 해당 출력을 생성하도록 요청하는 프롬프트를 제공합니다:
a. Question: The input question from the user query, provided with the prompt a. 질문: 사용자 쿼리의 입력 질문으로, 다음과 같은 프롬프트와 함께 제공됩니다.
b. Thought: The model’s thoughts about what it should do next 비. 생각: 다음에 해야 할 일에 대한 모델의 생각
c. Action: The model’s decision on what action to take next c. 조치: 다음에 취할 조치에 대한 모델의 결정
i. This is where tool choice can occur i. 여기에서 도구를 선택할 수 있습니다.
ii. For example, an action could be one of [Flights, Search, Code, None], where the first 3 represent a known tool that the model can choose, and the last represents “no tool choice” ii. 예를 들어, 작업은 [항공편, 검색, 코드, 없음] 중 하나이며, 여기서 처음 3개는 모델이 선택할 수 있는 알려진 도구를 나타내고 마지막은 "도구 선택 없음"을 나타냅니다.
d. Action input: The model’s decision on what inputs to provide to the tool (if any) d. 작업 입력: 도구에 어떤 입력을 제공할지에 대한 모델의 결정(있는 경우)
e. Observation: The result of the action / action input sequence e. 관찰: 동작/행동 입력 시퀀스의 결과
i. This thought / action / action input / observation could repeat NN-times as needed i. 이 생각/행동/행동 입력/관찰은 필요에 따라 NN -회 반복될 수 있습니다.
f. Final answer: The model’s final answer to provide to the original user query f. 최종 답변: 원래 사용자 쿼리에 제공할 모델의 최종 답변입니다.
The ReAct loop concludes and a final answer is provided back to the user ReAct 루프가 종료되고 최종 답변이 사용자에게 다시 제공됩니다.
Figure 2. Example agent with ReAct reasoning in the orchestration layer 그림 2. 오케스트레이션 레이어에서 ReAct 추론이 적용된 에이전트 예시
As shown in Figure 2, the model, tools, and agent configuration work together to provide a grounded, concise response back to the user based on the user’s original query. While the model could have guessed at an answer (hallucinated) based on its prior knowledge, it instead used a tool (Flights) to search for real-time external information. This additional information was provided to the model, allowing it to make a more informed decision based on real factual data and to summarize this information back to the user. 그림 2에서 볼 수 있듯이 모델, 도구 및 에이전트 구성이 함께 작동하여 사용자의 원래 쿼리를 기반으로 사용자에게 근거에 입각한 간결한 응답을 제공합니다. 이 모델은 사전 지식을 바탕으로 답을 추측할 수도 있었지만(환각), 대신 도구(항공편)를 사용하여 실시간 외부 정보를 검색했습니다. 이 추가 정보가 모델에 제공되어 모델이 실제 사실 데이터를 기반으로 더 많은 정보에 입각한 결정을 내리고 이 정보를 요약하여 사용자에게 다시 제공할 수 있었습니다.
In summary, the quality of agent responses can be tied directly to the model’s ability to reason and act about these various tasks, including the ability to select the right tools, and how well that tools has been defined. Like a chef crafting a dish with fresh ingredients and attentive to customer feedback, agents rely on sound reasoning and reliable information to deliver optimal results. In the next section, we’ll dive into the various ways agents connect with fresh data. 요약하면 상담원 응답의 품질은 올바른 도구를 선택하는 능력과 해당 도구가 얼마나 잘 정의되어 있는지 등 다양한 작업에 대해 추론하고 행동하는 모델의 능력과 직결될 수 있습니다. 신선한 재료로 요리를 만들고 고객의 피드백에 주의를 기울이는 요리사처럼 상담원은 올바른 추론과 신뢰할 수 있는 정보에 의존하여 최적의 결과를 제공합니다. 다음 섹션에서는 상담원이 새로운 데이터와 연결하는 다양한 방법에 대해 자세히 살펴보겠습니다.
Tools: Our keys to the outside world 도구: 외부 세계로 가는 열쇠
While language models excel at processing information, they lack the ability to directly perceive and influence the real world. This limits their usefulness in situations requiring interaction with external systems or data. This means that, in a sense, a language model is only as good as what it has learned from its training data. But regardless of how much data we throw at a model, they still lack the fundamental ability to interact with the outside world. So how can we empower our models to have real-time, context-aware interaction with external systems? Functions, Extensions, Data Stores and Plugins are all ways to provide this critical capability to the model. 언어 모델은 정보 처리 능력은 뛰어나지만 현실 세계를 직접 인식하고 영향을 미치는 능력은 부족합니다. 따라서 외부 시스템이나 데이터와의 상호작용이 필요한 상황에서는 그 유용성이 제한됩니다. 즉, 어떤 의미에서 언어 모델은 학습 데이터에서 학습한 것만큼만 우수하다는 뜻입니다. 하지만 아무리 많은 데이터를 모델에 투입해도 외부 세계와 상호작용할 수 있는 근본적인 능력은 여전히 부족합니다. 그렇다면 어떻게 하면 모델이 외부 시스템과 실시간으로 컨텍스트를 인식하며 상호 작용할 수 있도록 지원할 수 있을까요? 함수, 확장 기능, 데이터 저장소 및 플러그인은 모두 모델에 이 중요한 기능을 제공하는 방법입니다.
While they go by many names, tools are what create a link between our foundational models and the outside world. This link to external systems and data allows our agent to perform a wider variety of tasks and do so with more accuracy and reliability. For instance, tools can enable agents to adjust smart home settings, update calendars, fetch user information from a database, or send emails based on a specific set of instructions. 다양한 이름으로 불리지만 도구는 기본 모델과 외부 세계를 연결해주는 역할을 합니다. 외부 시스템 및 데이터에 대한 이러한 연결을 통해 상담원은 더욱 다양한 작업을 보다 정확하고 안정적으로 수행할 수 있습니다. 예를 들어 상담원은 도구를 통해 스마트 홈 설정을 조정하고, 캘린더를 업데이트하고, 데이터베이스에서 사용자 정보를 가져오거나, 특정 지침에 따라 이메일을 보낼 수 있습니다.
As of the date of this publication, there are three primary tool types that Google models are able to interact with: Extensions, Functions, and Data Stores. By equipping agents with tools, we unlock a vast potential for them to not only understand the world but also act upon it, opening doors to a myriad of new applications and possibilities. 이 문서 발행일을 기준으로 Google 모델이 상호 작용할 수 있는 세 가지 기본 도구 유형이 있습니다: 확장 프로그램, 함수, 데이터 스토어입니다. Google은 상담원에게 도구를 제공함으로써 세상을 이해하는 것뿐만 아니라 이를 바탕으로 행동할 수 있는 방대한 잠재력을 열어 수많은 새로운 애플리케이션과 가능성의 문을 열어줍니다.
Extensions 확장 기능
The easiest way to understand Extensions is to think of them as bridging the gap between an API and an agent in a standardized way, allowing agents to seamlessly execute APIs regardless of their underlying implementation. Let’s say that you’ve built an agent with a goal of helping users book flights. You know that you want to use the Google Flights API to retrieve flight information, but you’re not sure how you’re going to get your agent to make calls to this API endpoint. 확장 기능을 이해하는 가장 쉬운 방법은 표준화된 방식으로 API와 상담원 사이의 간극을 메워 상담원이 기본 구현에 관계없이 API를 원활하게 실행할 수 있도록 하는 것이라고 생각하면 됩니다. 사용자의 항공편 예약을 돕는 것을 목표로 에이전트를 구축했다고 가정해 보겠습니다. Google 항공편 API를 사용하여 항공편 정보를 검색하고 싶지만 상담원이 이 API 엔드포인트를 어떻게 호출하도록 해야 할지 잘 모르겠습니다.
Figure 3. How do Agents interact with External APIs? 그림 3. 에이전트는 외부 API와 어떻게 상호 작용하나요?
One approach could be to implement custom code that would take the incoming user query, parse the query for relevant information, then make the API call. For example, in a flight booking use case a user might state “I want to book a flight from Austin to Zurich.” In this scenario, our custom code solution would need to extract “Austin” and “Zurich” as relevant entities from the user query before attempting to make the API call. But what happens if the user says “I want to book a flight to Zurich” and never provides a departure city? The API call would fail without the required data and more code would need to be implemented in order to catch edge and corner cases like this. This approach is not scalable and could easily break in any scenario that falls outside of the implemented custom code. 한 가지 접근 방식은 들어오는 사용자 쿼리를 받아 관련 정보를 구문 분석한 다음 API 호출을 수행하는 사용자 지정 코드를 구현하는 것입니다. 예를 들어, 항공편 예약 사용 사례에서 사용자가 "오스틴에서 취리히로 가는 항공편을 예약하고 싶습니다."라고 말할 수 있습니다. 이 시나리오에서 사용자 지정 코드 솔루션은 API 호출을 시도하기 전에 사용자 쿼리에서 관련 엔티티로 "Austin"과 "Zurich"를 추출해야 합니다. 하지만 사용자가 "취리히행 항공편을 예약하고 싶어요"라고 말하면서 출발 도시를 제공하지 않는다면 어떻게 될까요? 필요한 데이터가 없으면 API 호출은 실패할 것이며, 이와 같은 엣지 케이스와 코너 케이스를 포착하기 위해 더 많은 코드를 구현해야 할 것입니다. 이 접근 방식은 확장성이 없으며 구현된 사용자 지정 코드를 벗어나는 모든 시나리오에서 쉽게 중단될 수 있습니다.
A more resilient approach would be to use an Extension. An Extension bridges the gap between an agent and an API by: 보다 탄력적인 접근 방식은 확장 프로그램을 사용하는 것입니다. 확장 프로그램은 에이전트와 API 사이의 간극을 메워줍니다:
Teaching the agent how to use the API endpoint using examples. 예제를 사용하여 상담원에게 API 엔드포인트 사용 방법을 가르칩니다.
Teaching the agent what arguments or parameters are needed to successfully call the API endpoint. 에이전트에게 API 엔드포인트를 성공적으로 호출하는 데 필요한 인수 또는 매개 변수를 가르칩니다.
[1] “The get_flights method can be used to get the latest…” [1] "get_flights 메서드를 사용하여 최신..."을 가져올 수 있습니다.
[2] “When the user wants to search for flights, call get_flights …” [2] "사용자가 항공편을 검색하려면 get_flights ...를 호출하세요."
[3] “Input args for get_flights are arg1, arg2, …” [3] "get_flights의 입력 인수는 arg1, arg2, ..."
Figure 4. Extensions connect Agents to External APIs 그림 4. 확장 기능으로 에이전트를 외부 API에 연결
Extensions can be crafted independently of the agent, but should be provided as part of the agent’s configuration. The agent uses the model and examples at run time to decide which Extension, if any, would be suitable for solving the user’s query. This highlights a key strength of Extensions, their built-in example types, that allow the agent to dynamically select the most appropriate Extension for the task. 확장은 상담원과 독립적으로 만들 수 있지만 상담원 구성의 일부로 제공되어야 합니다. 에이전트는 런타임에 모델과 예제를 사용하여 사용자의 쿼리를 해결하는 데 적합한 확장 기능이 있는지 결정합니다. 이는 상담원이 작업에 가장 적합한 확장을 동적으로 선택할 수 있도록 해주는 기본 제공 예제 유형인 확장 기능의 핵심 강점을 강조합니다.
Figure 5. 1-to-many relationship between Agents, Extensions and APIs 그림 5. 에이전트, 확장 프로그램 및 API 간의 일대다 관계
Think of this the same way that a software developer decides which API endpoints to use while solving and solutioning for a user’s problem. If the user wants to book a flight, the developer might use the Google Flights API. If the user wants to know where the nearest coffee shop is relative to their location, the developer might use the Google Maps API. In this same way, the agent / model stack uses a set of known Extensions to decide which one will be the best fit for the user’s query. If you’d like to see Extensions in action, you can try them out on the Gemini application by going to Settings > Extensions and then enabling any you would like to test. For example, you could enable the Google Flights extension then ask Gemini “Show me flights from Austin to Zurich leaving next Friday.” 소프트웨어 개발자가 사용자의 문제를 해결하고 해결할 때 사용할 API 엔드포인트를 결정하는 것과 같은 방식으로 생각하면 됩니다. 사용자가 항공편을 예약하려는 경우 개발자는 Google 항공편 API를 사용할 수 있습니다. 사용자가 자신의 위치에서 가장 가까운 커피숍이 어디 있는지 알고 싶다면 개발자는 Google 지도 API를 사용할 수 있습니다. 이와 같은 방식으로 에이전트/모델 스택은 알려진 확장 프로그램 세트를 사용하여 사용자의 쿼리에 가장 적합한 확장 프로그램을 결정합니다. 확장 기능이 실제로 작동하는지 확인하려면 설정 > 확장 기능으로 이동한 다음 테스트하려는 확장 기능을 사용 설정하여 Gemini 애플리케이션에서 사용해 볼 수 있습니다. 예를 들어 Google 항공편 확장 프로그램을 활성화한 다음 Gemini에게 "다음 주 금요일에 출발하는 오스틴에서 취리히로 가는 항공편을 보여줘"라고 요청할 수 있습니다.
Sample Extensions 샘플 확장 기능
To simplify the usage of Extensions, Google provides some out of the box extensions that can be quickly imported into your project and used with minimal configurations. For example, the Code Interpreter extension in Snippet 1 allows you to generate and run Python code from a natural language description. 확장 프로그램 사용을 간소화하기 위해 Google은 프로젝트에 빠르게 가져와 최소한의 설정으로 사용할 수 있는 몇 가지 기본 제공 확장 프로그램을 제공합니다. 예를 들어 스니펫 1의 코드 인터프리터 확장 프로그램을 사용하면 자연어 설명에서 Python 코드를 생성하고 실행할 수 있습니다.
Python
import vertexai
import pprint
PROJECT_ID = "YOUR_PROJECT_ID"
REGION = "us-central1"
vertexai.init(project=PROJECT_ID, location=REGION)
from vertexai.preview.extensions import Extension
extension_code_interpreter = Extension.from_hub("code_interpreter")
CODE_QUERY = """Write a python method to invert a binary tree in O(n) time."""
response = extension_code_interpreter.execute(
operation_id = "generate_and_execute",
operation_params = {"query": CODE_QUERY}
)
print("Generated Code:")
pprint.pprint({response['generated_code']})
# The above snippet will generate the following code.
Generated Code:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
Python
def invert_binary_tree(root):
"""
Inverts a binary tree.
Args:
root: The root of the binary tree.
Returns:
The root of the inverted binary tree.
"""
if not root:
return None
# Swap the left and right children recursively
root.left, root.right =
invert_binary_tree(root.right), invert_binary_tree(root.left)
return root
# Example usage:
# Construct a sample binary tree
root = TreeNode(4)
root.left = TreeNode(2)
root.right = TreeNode(7)
root.left.left = TreeNode(1)
root.left.right = TreeNode(3)
root.right.left = TreeNode(6)
root.right.right = TreeNode(9)
# Invert the binary tree
inverted_root = invert_binary_tree(root)
`..
Snippet 1. Code Interpreter Extension can generate and run Python code 스니펫 1. 코드 인터프리터 확장으로 Python 코드 생성 및 실행 가능
To summarize, Extensions provide a way for agents to perceive, interact, and influence the outside world in a myriad of ways. The selection and invocation of these Extensions is guided by the use of Examples, all of which are defined as part of the Extension configuration. 요약하자면 확장 프로그램은 상담원이 수많은 방식으로 외부 세계를 인식하고 상호 작용하며 영향을 미칠 수 있는 방법을 제공합니다. 이러한 확장 기능의 선택 및 호출은 예제를 사용하여 안내되며, 예제는 모두 확장 기능 구성의 일부로 정의됩니다.
Functions 기능
In the world of software engineering, functions are defined as self-contained modules of code that accomplish a specific task and can be reused as needed. When a software developer is writing a program, they will often create many functions to do various tasks. They will also define the logic for when to call function_a versus function_b, as well as the expected inputs and outputs. 소프트웨어 엔지니어링 세계에서 함수는 특정 작업을 수행하고 필요에 따라 재사용할 수 있는 독립된 코드 모듈로 정의됩니다. 소프트웨어 개발자가 프로그램을 작성할 때 다양한 작업을 수행하기 위해 많은 함수를 만드는 경우가 많습니다. 또한 함수에는 함수_a와 함수_b를 언제 호출해야 하는지에 대한 로직과 예상되는 입력 및 출력도 정의합니다.
Functions work very similarly in the world of agents, but we can replace the software developer with a model. A model can take a set of known functions and decide when to use each Function and what arguments the Function needs based on its specification. Functions differ from Extensions in a few ways, most notably: 함수는 에이전트 세계에서 매우 유사하게 작동하지만 소프트웨어 개발자를 모델로 대체할 수 있습니다. 모델은 알려진 함수 집합을 가져와서 각 함수의 사양에 따라 각 함수를 언제 사용할지, 어떤 인수가 필요한지 결정할 수 있습니다. 함수는 몇 가지 점에서 확장과 다른데, 특히 다음과 같은 점이 가장 두드러집니다:
A model outputs a Function and its arguments, but doesn’t make a live API call. 모델은 함수와 그 인수를 출력하지만 라이브 API 호출을 수행하지는 않습니다.
Functions are executed on the client-side, while Extensions are executed on the agent-side. 함수는 클라이언트 측에서 실행되는 반면 확장은 에이전트 측에서 실행됩니다.
Using our Google Flights example again, a simple setup for functions might look like the example in Figure 7. Google 항공편의 예를 다시 사용하면 그림 7의 예시와 같이 간단한 함수 설정이 가능합니다.
Figure 7. How do functions interact with external APIs? 그림 7. 함수는 외부 API와 어떻게 상호 작용하나요?
Note that the main difference here is that neither the Function nor the agent interact directly with the Google Flights API. So how does the API call actually happen? 여기서 가장 큰 차이점은 함수나 상담원이 Google 항공편 API와 직접 상호 작용하지 않는다는 점입니다. 그렇다면 API 호출은 실제로 어떻게 이루어질까요?
With functions, the logic and execution of calling the actual API endpoint is offloaded away from the agent and back to the client-side application as seen in Figure 8 and Figure 9 below. This offers the developer more granular control over the flow of data in the application. There are many reasons why a Developer might choose to use functions over Extensions, but a few common use cases are: 함수를 사용하면 아래 그림 8과 그림 9에서 볼 수 있듯이 실제 API 엔드포인트를 호출하는 로직과 실행이 에이전트에서 클라이언트 측 애플리케이션으로 다시 오프로드됩니다. 이를 통해 개발자는 애플리케이션의 데이터 흐름을 보다 세밀하게 제어할 수 있습니다. 개발자가 확장 기능 대신 함수를 사용하는 데는 여러 가지 이유가 있지만 몇 가지 일반적인 사용 사례는 다음과 같습니다:
API calls need to be made at another layer of the application stack, outside of the direct agent architecture flow (e.g. a middleware system, a front end framework, etc.) API 호출은 직접 에이전트 아키텍처 흐름 외부의 애플리케이션 스택의 다른 계층(예: 미들웨어 시스템, 프런트엔드 프레임워크 등)에서 이루어져야 합니다.
Security or Authentication restrictions that prevent the agent from calling an API directly (e.g API is not exposed to the internet, or non-accessible by agent infrastructure) 상담원이 API를 직접 호출할 수 없도록 하는 보안 또는 인증 제한(예: API가 인터넷에 노출되지 않거나 상담원 인프라에서 액세스할 수 없는 경우)
Timing or order-of-operations constraints that prevent the agent from making API calls in real-time. (i.e. batch operations, human-in-the-loop review, etc.) 에이전트가 실시간으로 API 호출을 하지 못하도록 하는 타이밍 또는 작업 순서 제약 조건. (예: 배치 작업, 휴먼 인 더 루프 검토 등)
Additional data transformation logic needs to be applied to the API Response that the agent cannot perform. For example, consider an API endpoint that doesn’t provide a filtering mechanism for limiting the number of results returned. Using Functions on the client-side provides the developer additional opportunities to make these transformations. 상담원이 수행할 수 없는 추가적인 데이터 변환 로직을 API 응답에 적용해야 합니다. 예를 들어 반환되는 결과의 수를 제한하는 필터링 메커니즘을 제공하지 않는 API 엔드포인트를 생각해 보세요. 클라이언트 측에서 함수를 사용하면 개발자에게 이러한 변환을 수행할 수 있는 추가적인 기회가 제공됩니다.
The developer wants to iterate on agent development without deploying additional infrastructure for the API endpoints (i.e. Function Calling can act like “stubbing” of APIs) 개발자는 API 엔드포인트에 대한 추가 인프라를 배포하지 않고 에이전트 개발을 반복하고자 합니다(즉, 함수 호출은 API의 "스터빙"처럼 작동할 수 있음).
While the difference in internal architecture between the two approaches is subtle as seen in Figure 8, the additional control and decoupled dependency on external infrastructure makes Function Calling an appealing option for the Developer. 그림 8에서 볼 수 있듯이 두 접근 방식 간의 내부 아키텍처 차이는 미묘하지만, 외부 인프라에 대한 추가적인 제어와 분리된 종속성으로 인해 함수 호출은 개발자에게 매력적인 옵션입니다.
Figure 8. Delineating client vs. agent side control for extensions and function calling 그림 8. 확장 및 함수 호출에 대한 클라이언트 대 에이전트 측 제어 설명
Use cases 사용 사례
A model can be used to invoke functions in order to handle complex, client-side execution flows for the end user, where the agent Developer might not want the language model to manage the API execution (as is the case with Extensions). Let’s consider the following example where an agent is being trained as a travel concierge to interact with users that want to book vacation trips. The goal is to get the agent to produce a list of cities that we can use in our middleware application to download images, data, etc. for the user’s trip planning. A user might say something like: 최종 사용자를 위한 복잡한 클라이언트 측 실행 흐름을 처리하기 위해 함수를 호출하는 데 모델을 사용할 수 있는데, 이때 상담원 개발자가 언어 모델이 API 실행을 관리하지 않기를 원할 수도 있습니다(확장 프로그램의 경우처럼). 휴가 여행을 예약하려는 사용자와 상호 작용하는 여행 컨시어지로서 상담원을 교육하는 다음 예를 생각해 보겠습니다. 목표는 상담원이 미들웨어 애플리케이션에서 사용자의 여행 계획에 필요한 이미지, 데이터 등을 다운로드하는 데 사용할 수 있는 도시 목록을 생성하도록 하는 것입니다. 사용자가 다음과 같이 말할 수 있습니다:
I’d like to take a ski trip with my family but I’m not sure where to go. 가족과 함께 스키 여행을 가고 싶은데 어디로 가야 할지 모르겠어요.
In a typical prompt to the model, the output might look like the following: 모델에 대한 일반적인 프롬프트에서 출력은 다음과 같이 표시될 수 있습니다:
Sure, here’s a list of cities that you can consider for family ski trips: 가족 스키 여행을 고려할 수 있는 도시 목록은 다음과 같습니다:
Crested Butte, Colorado, USA 크레스티드 뷰트, 콜로라도, 미국
Whistler, BC, Canada 캐나다 브리티시컬럼비아주 휘슬러
Zermatt, Switzerland 스위스 체르마트
While the above output contains the data that we need (city names), the format isn’t ideal for parsing. With Function Calling, we can teach a model to format this output in a structured style (like JSON) that’s more convenient for another system to parse. Given the same input prompt from the user, an example JSON output from a Function might look like Snippet 5 instead. 위의 출력에는 필요한 데이터(도시 이름)가 포함되어 있지만 이 형식은 구문 분석에 적합하지 않습니다. 함수 호출을 사용하면 모델에 이 출력 형식을 다른 시스템에서 구문 분석하기에 더 편리한 구조화된 스타일(예: JSON)로 지정하도록 학습시킬 수 있습니다. 사용자의 입력 프롬프트가 동일하다고 가정할 때 함수의 JSON 출력 예시는 스니펫 5와 같이 보일 수 있습니다.
Snippet 5. Sample Function Call payload for displaying a list of cities and user preferences 스니펫 5. 도시 및 사용자 기본 설정 목록을 표시하기 위한 함수 호출 페이로드 샘플
This JSON payload is generated by the model, and then sent to our Client-side server to do whatever we would like to do with it. In this specific case, we’ll call the Google Places API to take the cities provided by the model and look up Images, then provide them as formatted rich content back to our User. Consider this sequence diagram in Figure 9 showing the above interaction in step by step detail. 이 JSON 페이로드는 모델에 의해 생성된 다음 클라이언트 측 서버로 전송되어 원하는 작업을 수행합니다. 이 특정 사례에서는 Google Places API를 호출하여 모델이 제공한 도시를 가져와 이미지를 조회한 다음 형식이 지정된 리치 콘텐츠로 사용자에게 다시 제공합니다. 위의 상호 작용을 단계별로 자세히 보여주는 그림 9의 시퀀스 다이어그램을 살펴보세요.
Figure 9. Sequence diagram showing the lifecycle of a Function Call 그림 9. 함수 호출의 수명 주기를 보여주는 시퀀스 다이어그램
The result of the example in Figure 9 is that the model is leveraged to “fill in the blanks” with the parameters required for the Client side UI to make the call to the Google Places API. The Client side UI manages the actual API call using the parameters provided by the model in the returned Function. This is just one use case for Function Calling, but there are many other scenarios to consider like: 그림 9의 예시의 결과는 클라이언트 측 UI가 Google Places API를 호출하는 데 필요한 매개변수로 '빈칸을 채우는' 데 모델을 활용한다는 것입니다. 클라이언트 측 UI는 반환된 함수에서 모델이 제공한 매개변수를 사용하여 실제 API 호출을 관리합니다. 이것은 함수 호출의 한 가지 사용 사례에 불과하지만, 다음과 같은 다른 많은 시나리오를 고려할 수 있습니다:
You want a language model to suggest a function that you can use in your code, but you don’t want to include credentials in your code. Because function calling doesn’t run the function, you don’t need to include credentials in your code with the function information. 언어 모델에서 코드에 사용할 수 있는 함수를 제안하고 싶지만 코드에 자격 증명을 포함시키고 싶지 않은 경우. 함수 호출은 함수를 실행하지 않으므로 코드에 함수 정보와 함께 자격 증명을 포함할 필요가 없습니다.
You are running asynchronous operations that can take more than a few seconds. These scenarios work well with function calling because it’s an asynchronous operation. 몇 초 이상 걸릴 수 있는 비동기 작업을 실행하고 있습니다. 이러한 시나리오는 비동기 작업이기 때문에 함수 호출과 잘 맞습니다.
You want to run functions on a device that’s different from the system producing the function calls and their arguments. 함수 호출과 그 인수를 생성하는 시스템과 다른 장치에서 함수를 실행하려고 합니다.
One key thing to remember about functions is that they are meant to offer the developer much more control over not only the execution of API calls, but also the entire flow of data in the application as a whole. In the example in Figure 9, the developer chose to not return API information back to the agent as it was not pertinent for future actions the agent might take. However, based on the architecture of the application, it may make sense to return the external API call data to the agent in order to influence future reasoning, logic, and action choices. Ultimately, it is up to the application developer to choose what is right for the specific application. 함수에 대해 기억해야 할 한 가지 중요한 점은 개발자가 API 호출의 실행뿐만 아니라 애플리케이션의 전체 데이터 흐름에 대해 훨씬 더 많은 제어를 할 수 있다는 것입니다. 그림 9의 예에서 개발자는 에이전트가 향후 수행할 수 있는 작업과 관련이 없기 때문에 API 정보를 에이전트에게 다시 반환하지 않기로 선택했습니다. 그러나 애플리케이션의 아키텍처에 따라 향후 추론, 논리 및 작업 선택에 영향을 미치기 위해 외부 API 호출 데이터를 상담원에게 반환하는 것이 합리적일 수 있습니다. 궁극적으로 특정 애플리케이션에 적합한 것을 선택하는 것은 애플리케이션 개발자의 몫입니다.
Function sample code 함수 샘플 코드
To achieve the above output from our ski vacation scenario, let’s build out each of the components to make this work with our gemini-1.5-flash-001 model. 스키 휴가 시나리오에서 위의 결과를 얻기 위해 각 구성 요소를 구축하여 gemini-1.5-flash-001 모델에서 작동하도록 해 보겠습니다.
First, we’ll define our display_cities function as a simple Python method. 먼저 간단한 파이썬 메서드로 display_cities 함수를 정의하겠습니다.
Python
def display_cities(cities: list[str], preferences: Optional[str] = None):
"""Provides a list of cities based on the user's search query and preferences.
Args:
preferences (str): The user's preferences for the search, like skiing,
beach, restaurants, bbq, etc.
cities (list[str]): The list of cities being recommended to the user.
Returns:
list[str]: The list of cities being recommended to the user.
" ""
return cities
Snippet 6. Sample python method for a function that will display a list of cities. 스니펫 6. 도시 목록을 표시하는 함수에 대한 샘플 파이썬 메서드입니다.
Next, we’ll instantiate our model, build the Tool, then pass in our user’s query and tools to the model. Executing the code below would result in the output as seen at the bottom of the code snippet. 다음으로 모델을 인스턴스화하고 도구를 빌드한 다음 사용자의 쿼리와 도구를 모델에 전달합니다. 아래 코드를 실행하면 코드 스니펫 하단에 표시된 것과 같은 출력이 생성됩니다.
Python
from vertexai.generative_models import GenerativeModel, Tool, FunctionDeclaration
model = GenerativeModel("gemini-1.5-flash-001")
display_cities_function = FunctionDeclaration.from_func(display_cities)
tool = Tool(function_declarations=[display_cities_function])
message = "I'd like to take a ski trip with my family but I'm not sure where
to go."
res = model.generate_content(message, tools=[tool])
print(f"Function Name: {res.candidates[0].content.parts[0].function_call.name}")
print(f"Function Args: {res.candidates[0].content.parts[0].function_call.args}")
> Function Name: display_cities
> Function Args: {'preferences': 'skiing', 'cities': ['Aspen', 'Vail',
'Park City']}
Snippet 7. Building a Tool, sending to the model with a user query and allowing the function call to take place 스니펫 7. 도구 빌드, 사용자 쿼리와 함께 모델에 전송하고 함수 호출이 이루어지도록 허용하기
In summary, functions offer a straightforward framework that empowers application developers with fine-grained control over data flow and system execution, while effectively leveraging the agent/model for critical input generation. Developers can selectively choose whether to keep the agent “in the loop” by returning external data, or omit it based on specific application architecture requirements. 요약하면, 함수는 애플리케이션 개발자가 데이터 흐름과 시스템 실행을 세밀하게 제어할 수 있는 간단한 프레임워크를 제공하는 동시에 중요한 입력 생성을 위해 에이전트/모델을 효과적으로 활용할 수 있도록 해줍니다. 개발자는 특정 애플리케이션 아키텍처 요구 사항에 따라 외부 데이터를 반환하여 에이전트를 '루프'로 유지할지, 아니면 생략할지를 선택적으로 선택할 수 있습니다.
Data stores 데이터 저장소
Imagine a language model as a vast library of books, containing its training data. But unlike a library that continuously acquires new volumes, this one remains static, holding only the knowledge it was initially trained on. This presents a challenge, as real-world knowledge is constantly evolving. Data Stores address this limitation by providing access to more dynamic and up-to-date information, and ensuring a model’s responses remain grounded in factuality and relevance. 언어 모델을 학습 데이터가 들어 있는 방대한 책 라이브러리라고 상상해 보세요. 하지만 지속적으로 새로운 책을 추가하는 도서관과 달리 이 모델은 처음에 학습된 지식만 담고 있는 정적인 상태입니다. 실제 지식은 끊임없이 진화하고 있기 때문에 이는 도전 과제입니다. 데이터 스토어는 보다 역동적인 최신 정보에 대한 액세스를 제공하고 모델의 응답이 사실성과 관련성을 기반으로 유지되도록 함으로써 이러한 한계를 해결합니다.
Consider a common scenario where a developer might need to provide a small amount of additional data to a model, perhaps in the form of spreadsheets or PDFs. 개발자가 모델에 스프레드시트나 PDF 형태로 소량의 추가 데이터를 제공해야 하는 일반적인 시나리오를 생각해 보겠습니다.
Figure 10. How can Agents interact with structured and unstructured data? 그림 10. 에이전트는 정형 및 비정형 데이터와 어떻게 상호 작용할 수 있나요?
Data Stores allow developers to provide additional data in its original format to an agent, eliminating the need for time-consuming data transformations, model retraining, or finetuning. The Data Store converts the incoming document into a set of vector database embeddings that the agent can use to extract the information it needs to supplement its next action or response to the user. 데이터 스토어를 사용하면 개발자가 에이전트에게 원래 형식의 추가 데이터를 제공할 수 있으므로 시간이 많이 걸리는 데이터 변환, 모델 재교육 또는 미세 조정이 필요하지 않습니다. 데이터 스토어는 수신 문서를 일련의 벡터 데이터베이스 임베딩으로 변환하여 에이전트가 다음 작업이나 사용자에 대한 응답을 보완하는 데 필요한 정보를 추출하는 데 사용할 수 있도록 합니다.
Figure 11. Data Stores connect Agents to new real-time data sources of various types. 그림 11. 데이터 스토어는 에이전트를 다양한 유형의 새로운 실시간 데이터 소스에 연결합니다.
Implementation and application 구현 및 적용
In the context of Generative AI agents, Data Stores are typically implemented as a vector database that the developer wants the agent to have access to at runtime. While we won’t cover vector databases in depth here, the key point to understand is that they store data in the form of vector embeddings, a type of high-dimensional vector or mathematical representation of the data provided. One of the most prolific examples of Data Store usage with language models in recent times has been the implementation of Retrieval Augmented 제너레이티브 AI 에이전트의 맥락에서 데이터 스토어는 일반적으로 개발자가 에이전트가 런타임에 액세스할 수 있도록 하는 벡터 데이터베이스로 구현됩니다. 여기서는 벡터 데이터베이스에 대해 자세히 다루지는 않겠지만, 여기서 이해해야 할 핵심 사항은 벡터 데이터베이스가 제공되는 데이터를 일종의 고차원 벡터 또는 수학적 표현인 벡터 임베딩의 형태로 데이터를 저장한다는 점입니다. 최근에 언어 모델과 함께 데이터 저장소를 가장 많이 사용한 사례 중 하나는 검색 증강을 구현한 것입니다.
Generation (RAG) based applications. These applications seek to extend the breadth and depth of a model’s knowledge beyond the foundational training data by giving the model access to data in various formats like: 세대(RAG) 기반 애플리케이션입니다. 이러한 애플리케이션은 모델에 다음과 같은 다양한 형식의 데이터에 대한 액세스 권한을 부여하여 기본 학습 데이터 이상으로 모델 지식의 폭과 깊이를 확장하고자 합니다:
Website content 웹사이트 콘텐츠
Structured Data in formats like PDF, Word Docs, CSV, Spreadsheets, etc. PDF, Word 문서, CSV, 스프레드시트 등과 같은 형식의 구조화된 데이터.
Unstructured Data in formats like HTML, PDF, TXT, etc. HTML, PDF, TXT 등과 같은 형식의 비정형 데이터
Figure 12. 1-to-many relationship between agents and data stores, which can represent various types of pre-indexed data 그림 12. 다양한 유형의 사전 인덱싱된 데이터를 나타낼 수 있는 에이전트와 데이터 저장소 간의 일대다 관계
The underlying process for each user request and agent response loop is generally modeled as seen in Figure 13. 각 사용자 요청 및 상담원 응답 루프에 대한 기본 프로세스는 일반적으로 그림 13과 같이 모델링됩니다.
A user query is sent to an embedding model to generate embeddings for the query 사용자 쿼리가 임베딩 모델로 전송되어 쿼리에 대한 임베딩을 생성합니다.
The query embeddings are then matched against the contents of the vector database using a matching algorithm like SCaNN 그런 다음 쿼리 임베딩은 SCaNN과 같은 매칭 알고리즘을 사용하여 벡터 데이터베이스의 콘텐츠와 매칭됩니다.
The matched content is retrieved from the vector database in text format and sent back to the agent 일치하는 콘텐츠가 벡터 데이터베이스에서 텍스트 형식으로 검색되어 상담원에게 다시 전송됩니다.
The agent receives both the user query and retrieved content, then formulates a response or action 상담원은 사용자 쿼리와 검색된 콘텐츠를 모두 수신한 다음 응답 또는 작업을 공식화합니다.
A final response is sent to the user 최종 응답이 사용자에게 전송됩니다.
Figure 13. The lifecycle of a user request and agent response in a RAG based application 그림 13. RAG 기반 애플리케이션에서 사용자 요청 및 상담원 응답의 수명 주기
The end result is an application that allows the agent to match a user’s query to a known data store through vector search, retrieve the original content, and provide it to the orchestration layer and model for further processing. The next action might be to provide a final answer to the user, or perform an additional vector search to further refine the results. 최종 결과는 에이전트가 벡터 검색을 통해 사용자의 쿼리를 알려진 데이터 저장소와 일치시키고, 원본 콘텐츠를 검색하여 추가 처리를 위해 오케스트레이션 계층과 모델에 제공할 수 있는 애플리케이션입니다. 다음 작업은 사용자에게 최종 답변을 제공하거나 추가 벡터 검색을 수행하여 결과를 더욱 세분화할 수 있습니다.
A sample interaction with an agent that implements RAG with ReAct reasoning/planning can be seen in Figure 14. 그림 14에서 ReAct 추론/계획으로 RAG을 구현하는 에이전트와의 상호작용 샘플을 볼 수 있습니다.
Agents 상담원
Figure 14. Sample RAG based application w/ ReAct reasoning/planning 그림 14. ReAct 추론/계획이 포함된 RAG 기반 애플리케이션 샘플
Tools recap 도구 요약
To summarize, extensions, functions and data stores make up a few different tool types available for agents to use at runtime. Each has their own purpose and they can be used together or independently at the discretion of the agent developer. 요약하자면 확장 기능, 함수 및 데이터 저장소는 상담원이 런타임에 사용할 수 있는 몇 가지 도구 유형으로 구성되어 있습니다. 각각 고유한 목적을 가지고 있으며 상담원 개발자의 재량에 따라 함께 또는 독립적으로 사용할 수 있습니다.
Extensions 확장 기능
Function Calling 함수 호출
Data Stores 데이터 저장소
Execution 실행
Agent-Side Execution 에이전트 측 실행
Client-Side Execution 클라이언트 측 실행
Agent-Side Execution 에이전트 측 실행
Use Case 사용 사례
- 개발자가 에이전트가 API 엔드포인트와의 상호작용을 제어하기를 원함 - 기본 사전 구축 확장(예: 버텍스 검색, 코드 인터프리터 등)을 활용할 때 유용함 - 멀티홉 계획 및 API 호출(예: 다음 에이전트 작업은 이전 작업 / API 호출의 출력에 따라 달라짐)
- Developer wants agent to control interactions with the API endpoints
- Multi-hop planning and API calling (i.e. the next agent action depends on the outputs of the previous action / API call)
- Developer wants agent to control interactions with the API endpoints
- Useful when leveraging native prebuilt Extensions (i.e. Vertex Search, Code Interpreter, etc.)
- Multi-hop planning and API calling (i.e. the next agent action depends on the outputs of the previous action / API call)| - Developer wants agent to control interactions with the API endpoints |
| :--- |
| - Useful when leveraging native prebuilt Extensions (i.e. Vertex Search, Code Interpreter, etc.) |
| - Multi-hop planning and API calling (i.e. the next agent action depends on the outputs of the previous action / API call) |
- 보안 또는 인증 제한으로 인해 상담원이 API를 직접 호출할 수 없는 경우 - 타이밍 제약 또는 작업 순서 제약으로 인해 상담원이 실시간으로 API를 호출할 수 없는 경우. (예: 일괄 작업, 휴먼 인 더 루프 검토 등) - 인터넷에 노출되지 않거나 Google 시스템에서 액세스할 수 없는 API
- Security or Authentication restrictions prevent the agent from calling an API directly
- Timing constraints or order-of-operations constraints that prevent the agent from making API calls in real-time. (i.e. batch operations, human-in-the-loop review, etc.)
- API that is not exposed to the internet, or non-accessible by Google systems
- Security or Authentication restrictions prevent the agent from calling an API directly
- Timing constraints or order-of-operations constraints that prevent the agent from making API calls in real-time. (i.e. batch operations, human-in-the-loop review, etc.)
- API that is not exposed to the internet, or non-accessible by Google systems| - Security or Authentication restrictions prevent the agent from calling an API directly |
| :--- |
| - Timing constraints or order-of-operations constraints that prevent the agent from making API calls in real-time. (i.e. batch operations, human-in-the-loop review, etc.) |
| - API that is not exposed to the internet, or non-accessible by Google systems |
개발자가 다음 데이터 유형으로 검색 증강 생성(RAG)을 구현하고자 합니다: - 사전 색인된 도메인 및 URL의 웹사이트 콘텐츠 - PDF, Word 문서, CSV, 스프레드시트 등과 같은 형식의 정형 데이터. - 관계형/비관계형 데이터베이스 - HTML, PDF, TXT 등과 같은 형식의 비정형 데이터
Developer wants to implement Retrieval Augmented Generation (RAG) with any of the following data types:
- Website Content from pre-indexed domains and URLs
- Structured Data in formats like PDF, Word Docs, CSV, Spreadsheets, etc.
- Relational / NonRelational Databases
- Unstructured Data in formats like HTML, PDF, TXT, etc.
Developer wants to implement Retrieval Augmented Generation (RAG) with any of the following data types:
- Website Content from pre-indexed domains and URLs
- Structured Data in formats like PDF, Word Docs, CSV, Spreadsheets, etc.
- Relational / NonRelational Databases
- Unstructured Data in formats like HTML, PDF, TXT, etc.| Developer wants to implement Retrieval Augmented Generation (RAG) with any of the following data types: |
| :--- |
| - Website Content from pre-indexed domains and URLs |
| - Structured Data in formats like PDF, Word Docs, CSV, Spreadsheets, etc. |
| - Relational / NonRelational Databases |
| - Unstructured Data in formats like HTML, PDF, TXT, etc. |
Extensions Function Calling Data Stores
Execution Agent-Side Execution Client-Side Execution Agent-Side Execution
Use Case "- Developer wants agent to control interactions with the API endpoints
- Useful when leveraging native prebuilt Extensions (i.e. Vertex Search, Code Interpreter, etc.)
- Multi-hop planning and API calling (i.e. the next agent action depends on the outputs of the previous action / API call)" "- Security or Authentication restrictions prevent the agent from calling an API directly
- Timing constraints or order-of-operations constraints that prevent the agent from making API calls in real-time. (i.e. batch operations, human-in-the-loop review, etc.)
- API that is not exposed to the internet, or non-accessible by Google systems" "Developer wants to implement Retrieval Augmented Generation (RAG) with any of the following data types:
- Website Content from pre-indexed domains and URLs
- Structured Data in formats like PDF, Word Docs, CSV, Spreadsheets, etc.
- Relational / NonRelational Databases
- Unstructured Data in formats like HTML, PDF, TXT, etc."| | Extensions | Function Calling | Data Stores |
| :---: | :---: | :---: | :---: |
| Execution | Agent-Side Execution | Client-Side Execution | Agent-Side Execution |
| Use Case | - Developer wants agent to control interactions with the API endpoints <br> - Useful when leveraging native prebuilt Extensions (i.e. Vertex Search, Code Interpreter, etc.) <br> - Multi-hop planning and API calling (i.e. the next agent action depends on the outputs of the previous action / API call) | - Security or Authentication restrictions prevent the agent from calling an API directly <br> - Timing constraints or order-of-operations constraints that prevent the agent from making API calls in real-time. (i.e. batch operations, human-in-the-loop review, etc.) <br> - API that is not exposed to the internet, or non-accessible by Google systems | Developer wants to implement Retrieval Augmented Generation (RAG) with any of the following data types: <br> - Website Content from pre-indexed domains and URLs <br> - Structured Data in formats like PDF, Word Docs, CSV, Spreadsheets, etc. <br> - Relational / NonRelational Databases <br> - Unstructured Data in formats like HTML, PDF, TXT, etc. |
Enhancing model performance with targeted learning 목표 학습으로 모델 성능 향상
A crucial aspect of using models effectively is their ability to choose the right tools when generating output, especially when using tools at scale in production. While general training helps models develop this skill, real-world scenarios often require knowledge beyond the training data. Imagine this as the difference between basic cooking skills and mastering a specific cuisine. Both require foundational cooking knowledge, but the latter demands targeted learning for more nuanced results. 모델을 효과적으로 사용하는 데 있어 중요한 측면은 결과물을 생성할 때, 특히 프로덕션에서 대규모로 도구를 사용할 때 적합한 도구를 선택하는 능력입니다. 일반적인 교육은 모델이 이러한 기술을 개발하는 데 도움이 되지만, 실제 시나리오에서는 교육 데이터 이상의 지식이 필요한 경우가 많습니다. 이를 기본적인 요리 기술과 특정 요리를 마스터하는 것의 차이점이라고 생각하면 됩니다. 둘 다 기본적인 요리 지식이 필요하지만, 후자는 보다 미묘한 결과를 얻기 위해 목표에 맞춘 학습이 필요합니다.
To help the model gain access to this type of specific knowledge, several approaches exist: 모델이 이러한 유형의 특정 지식에 액세스하는 데 도움이 되는 몇 가지 접근 방식이 존재합니다:
In-context learning: This method provides a generalized model with a prompt, tools, and few-shot examples at inference time which allows it to learn ‘on the fly’ how and when to use those tools for a specific task. The ReAct framework is an example of this approach in natural language. 상황에 맞는 학습: 이 방법은 추론 시점에 프롬프트, 도구, 몇 가지 예시를 통해 일반화된 모델을 제공하여 특정 작업에 이러한 도구를 언제 어떻게 사용해야 하는지 '즉시' 학습할 수 있도록 합니다. ReAct 프레임워크는 자연어에서 이 접근 방식의 한 예입니다.
Retrieval-based in-context learning: This technique dynamically populates the model prompt with the most relevant information, tools, and associated examples by retrieving them from external memory. An example of this would be the ‘Example Store’ in Vertex AI extensions or the data stores RAG based architecture mentioned previously. 검색 기반 컨텍스트 내 학습: 이 기술은 외부 메모리에서 가장 관련성이 높은 정보, 도구 및 관련 예제를 검색하여 모델 프롬프트를 동적으로 채웁니다. 예를 들어 Vertex AI 확장 기능의 '예제 저장소' 또는 앞서 언급한 데이터 저장소 RAG 기반 아키텍처가 이에 해당합니다.
Fine-tuning based learning: This method involves training a model using a larger dataset of specific examples prior to inference. This helps the model understand when and how to apply certain tools prior to receiving any user queries. 미세 조정 기반 학습: 이 방법은 추론하기 전에 특정 사례의 대규모 데이터 세트를 사용하여 모델을 학습시키는 것입니다. 이를 통해 모델은 사용자 쿼리를 받기 전에 특정 도구를 언제, 어떻게 적용해야 하는지 이해할 수 있습니다.
To provide additional insights on each of the targeted learning approaches, let’s revisit our cooking analogy. 각 타깃 학습 접근 방식에 대한 추가 인사이트를 제공하기 위해 요리 비유를 다시 살펴 보겠습니다.
Imagine a chef has received a specific recipe (the prompt), a few key ingredients (relevant tools) and some example dishes (few-shot examples) from a customer. Based on this limited information and the chef’s general knowledge of cooking, they will need to figure out how to prepare the dish ‘on the fly’ that most closely aligns with the recipe and the customer’s preferences. This is in-context learning. 셰프가 고객으로부터 특정 레시피(프롬프트), 몇 가지 주요 재료(관련 도구), 몇 가지 예시 요리(몇 컷 예시)를 받았다고 상상해 보세요. 이 제한된 정보와 요리사의 일반적인 요리 지식을 바탕으로 요리사는 레시피와 고객의 선호도에 가장 근접한 요리를 '즉석에서' 준비할 방법을 찾아야 합니다. 이것이 바로 상황 중심 학습입니다.
Now let’s imagine our chef in a kitchen that has a well-stocked pantry (external data stores) filled with various ingredients and cookbooks (examples and tools). The chef is now able to dynamically choose ingredients and cookbooks from the pantry and better align to the customer’s recipe and preferences. This allows the chef to create a more informed and refined dish leveraging both existing and new knowledge. This is retrieval-based in-context learning. 이제 다양한 재료와 요리책(예시 및 도구)으로 가득 찬 팬트리(외부 데이터 저장소)가 있는 주방의 요리사를 상상해 봅시다. 이제 셰프는 팬트리에서 재료와 요리책을 동적으로 선택하여 고객의 레시피와 선호도에 더 잘 맞출 수 있습니다. 이를 통해 셰프는 기존 지식과 새로운 지식을 모두 활용하여 더욱 정보에 입각하고 세련된 요리를 만들 수 있습니다. 이것이 바로 검색 기반 인컨텍스트 학습입니다.
Finally, let’s imagine that we sent our chef back to school to learn a new cuisine or set of cuisines (pre-training on a larger dataset of specific examples). This allows the chef to approach future unseen customer recipes with deeper understanding. This approach is perfect if we want the chef to excel in specific cuisines (knowledge domains). This is finetuning based learning. 마지막으로, 새로운 요리 또는 요리 세트를 배우기 위해 셰프를 학교로 다시 보냈다고 가정해 봅시다(특정 사례의 대규모 데이터 세트에 대한 사전 교육). 이렇게 하면 셰프가 이전에 보지 못한 고객 레시피에 대해 더 깊이 이해하고 접근할 수 있습니다. 이 접근 방식은 셰프가 특정 요리(지식 영역)에서 탁월한 능력을 발휘하기를 원할 때 적합합니다. 이것이 바로 미세 조정 기반 학습입니다.
Each of these approaches offers unique advantages and disadvantages in terms of speed, cost, and latency. However, by combining these techniques in an agent framework, we can leverage the various strengths and minimize their weaknesses, allowing for a more robust and adaptable solution. 이러한 접근 방식은 각각 속도, 비용, 지연 시간 측면에서 고유한 장단점을 제공합니다. 하지만 이러한 기술을 에이전트 프레임워크에 결합하면 다양한 강점을 활용하고 약점을 최소화하여 보다 강력하고 적응력 있는 솔루션을 제공할 수 있습니다.
Agent quick start with LangChain LangChain으로 에이전트 빠른 시작
In order to provide a real-world executable example of an agent in action, we’ll build a quick prototype with the LangChain and LangGraph libraries. These popular open source libraries allow users to build customer agents by “chaining” together sequences of logic, reasoning, and tool calls to answer a user’s query. We’ll use our gemini-1.5-flash-001 model and some simple tools to answer a multi-stage query from the user as seen in Snippet 8. 실제 에이전트의 실행 가능한 예시를 제공하기 위해 LangChain과 LangGraph 라이브러리를 사용해 간단한 프로토타입을 구축해 보겠습니다. 이러한 인기 있는 오픈 소스 라이브러리를 사용하면 사용자의 쿼리에 응답하기 위해 일련의 로직, 추론 및 도구 호출을 '체인'으로 연결하여 고객 에이전트를 구축할 수 있습니다. 여기서는 스니펫 8에 표시된 것처럼 gemini-1.5-flash-001 모델과 몇 가지 간단한 툴을 사용하여 사용자의 다단계 쿼리에 응답해 보겠습니다.
The tools we are using are the SerpAPI (for Google Search) and the Google Places API. After executing our program in Snippet 8, you can see the sample output in Snippet 9. 우리가 사용하는 도구는 SerpAPI(Google 검색용)와 Google 지역 정보 API입니다. 코드 조각 8에서 프로그램을 실행한 후 코드 조각 9에서 샘플 출력을 볼 수 있습니다.
Python
from langgraph.prebuilt import create_react_agent
from langchain_core.tools import tool
from langchain_community.utilities import SerpAPIWrapper
from langchain_community.tools import GooglePlacesTool
os.environ["SERPAPI_API_KEY"] = "XXXXX"
os.environ["GPLACES_API_KEY"] = "XXXXX"
@tool
def search(query: str):
"""Use the SerpAPI to run a Google Search."""
search = SerpAPIWrapper()
return search.run(query)
@tool
def places(query: str):
"""Use the Google Places API to run a Google Places Query."""
places = GooglePlacesTool()
return places.run(query)
model = ChatVertexAI(model="gemini-1.5-flash-001")
tools = [search, places]
query = "Who did the Texas Longhorns play in football last week? What is the
address of the other team's stadium?"
agent = create_react_agent(model, tools)
input = {"messages": [("human", query)]}
for s in agent.stream(input, stream_mode="values"):
message = s["messages"][-1]
if isinstance(message, tuple):
print(message)
else:
message.pretty_print()
Snippet 8. Sample LangChain and LangGraph based agent with tools 스니펫 8. 도구가 포함된 샘플 LangChain 및 LangGraph 기반 에이전트
Unset
=============================== Human Message ==================================
Who did the Texas Longhorns play in football last week? What is the address
of the other team's stadium?
================================= Ai Message ======================================
Tool Calls: search
Args:
query: Texas Longhorns football schedule
================================= Tool Message ===================================
Name: search
{...Results: "NCAA Division I Football, Georgia, Date..."}
================================== Ai Message =====================================
The Texas Longhorns played the Georgia Bulldogs last week.
Tool Calls: places
Args:
query: Georgia Bulldogs stadium
================================ Tool Message ====================================
Name: places
{...Sanford Stadium Address: 100 Sanford...}
================================= Ai Message ====================================
The address of the Georgia Bulldogs stadium is 100 Sanford Dr, Athens, GA
30602, USA
Snippet 9. Output from our program in Snippet 8 코드 조각 9. 스니펫 8의 프로그램 출력
While this is a fairly simple agent example, it demonstrates the foundational components of Model, Orchestration, and tools all working together to achieve a specific goal. In the final section, we’ll explore how these components come together in Google-scale managed products like Vertex AI agents and Generative Playbooks. 이는 매우 간단한 에이전트 예시이지만, 특정 목표를 달성하기 위해 모델, 오케스트레이션 및 도구의 기본 구성 요소가 모두 함께 작동하는 것을 보여줍니다. 마지막 섹션에서는 이러한 구성 요소가 Vertex AI 에이전트 및 제너레이티브 플레이북과 같은 Google 규모 관리형 제품에서 어떻게 결합되는지 살펴보겠습니다.
Production applications with Vertex Al agents 버텍스 알 에이전트를 사용한 프로덕션 애플리케이션
While this whitepaper explored the core components of agents, building production-grade applications requires integrating them with additional tools like user interfaces, evaluation frameworks, and continuous improvement mechanisms. Google’s Vertex AI platform simplifies this process by offering a fully managed environment with all the fundamental elements covered earlier. Using a natural language interface, developers can rapidly define crucial elements of their agents - goals, task instructions, tools, sub-agents for task delegation, and examples - to easily construct the desired system behavior. In addition, the platform comes with a set of development tools that allow for testing, evaluation, measuring agent performance, debugging, and improving the overall quality of developed agents. This allows developers to focus on building and refining their agents while the complexities of infrastructure, deployment and maintenance are managed by the platform itself. 이 백서에서는 에이전트의 핵심 구성 요소를 살펴보았지만, 프로덕션급 애플리케이션을 구축하려면 사용자 인터페이스, 평가 프레임워크, 지속적인 개선 메커니즘과 같은 추가 도구와 통합해야 합니다. Google의 Vertex AI 플랫폼은 앞서 다룬 모든 기본 요소를 갖춘 완전 관리형 환경을 제공함으로써 이 과정을 간소화합니다. 개발자는 자연어 인터페이스를 사용하여 목표, 작업 지침, 도구, 작업 위임을 위한 하위 에이전트, 예제 등 에이전트의 핵심 요소를 빠르게 정의하여 원하는 시스템 동작을 쉽게 구성할 수 있습니다. 또한 이 플랫폼에는 테스트, 평가, 에이전트 성능 측정, 디버깅 및 개발된 에이전트의 전반적인 품질 개선이 가능한 개발 도구 세트가 함께 제공됩니다. 따라서 개발자는 복잡한 인프라, 배포 및 유지 관리가 플랫폼 자체에서 관리되는 동안 에이전트를 구축하고 개선하는 데 집중할 수 있습니다.
In Figure 15 we’ve provided a sample architecture of an agent that was built on the Vertex Al platform using various features such as Vertex Agent Builder, Vertex Extensions, Vertex Function Calling and Vertex Example Store to name a few. The architecture includes many of the various components necessary for a production ready application. 그림 15에서는 버텍스 에이전트 빌더, 버텍스 확장, 버텍스 함수 호출, 버텍스 예제 스토어 등 다양한 기능을 사용하여 버텍스 Al 플랫폼에 구축된 에이전트의 샘플 아키텍처를 제공했습니다. 이 아키텍처에는 프로덕션 준비 애플리케이션에 필요한 다양한 구성 요소가 포함되어 있습니다.
Agents 상담원
Figure 15. Sample end-to-end agent architecture built on Vertex AI platform 그림 15. 버텍스 AI 플랫폼에 구축된 엔드투엔드 에이전트 아키텍처 샘플
You can try a sample of this prebuilt agent architecture from our official documentation. 공식 문서에서 이 사전 구축된 에이전트 아키텍처의 샘플을 사용해 볼 수 있습니다.
Summary 요약
In this whitepaper we’ve discussed the foundational building blocks of Generative AI agents, their compositions, and effective ways to implement them in the form of cognitive architectures. Some key takeaways from this whitepaper include: 이 백서에서는 제너레이티브 AI 에이전트의 기본 구성 요소와 구성, 그리고 이를 인지 아키텍처의 형태로 구현하는 효과적인 방법에 대해 설명했습니다. 이 백서의 주요 내용은 다음과 같습니다:
Agents extend the capabilities of language models by leveraging tools to access realtime information, suggest real-world actions, and plan and execute complex tasks autonomously. agents can leverage one or more language models to decide when and how to transition through states and use external tools to complete any number of complex tasks that would be difficult or impossible for the model to complete on its own. 에이전트는 도구를 활용하여 실시간 정보에 액세스하고, 실제 작업을 제안하고, 복잡한 작업을 자율적으로 계획 및 실행함으로써 언어 모델의 기능을 확장합니다. 에이전트는 하나 이상의 언어 모델을 활용하여 상태 전환 시기와 방법을 결정하고 외부 도구를 사용하여 모델 자체로는 완료하기 어렵거나 불가능한 복잡한 작업을 얼마든지 완료할 수 있습니다.
At the heart of an agent’s operation is the orchestration layer, a cognitive architecture that structures reasoning, planning, decision-making and guides its actions. Various reasoning techniques such as ReAct, Chain-of-Thought, and Tree-of-Thoughts, provide a framework for the orchestration layer to take in information, perform internal reasoning, and generate informed decisions or responses. 에이전트 운영의 중심에는 추론, 계획, 의사 결정을 구조화하고 행동을 안내하는 인지 아키텍처인 오케스트레이션 계층이 있습니다. 리액트, 생각의 사슬, 생각의 나무와 같은 다양한 추론 기법은 오케스트레이션 계층이 정보를 받아들이고 내부 추론을 수행하며 정보에 입각한 결정이나 응답을 생성할 수 있는 프레임워크를 제공합니다.
Tools, such as Extensions, Functions, and Data Stores, serve as the keys to the outside world for agents, allowing them to interact with external systems and access knowledge beyond their training data. Extensions provide a bridge between agents and external APIs, enabling the execution of API calls and retrieval of real-time information. functions provide a more nuanced control for the developer through the division of labor, allowing agents to generate Function parameters which can be executed client-side. Data Stores provide agents with access to structured or unstructured data, enabling data-driven applications. 확장 기능, 함수, 데이터 스토어와 같은 도구는 에이전트가 외부 시스템과 상호 작용하고 트레이닝 데이터 이외의 지식에 액세스할 수 있도록 하는 외부 세계로의 열쇠 역할을 합니다. 확장은 에이전트와 외부 API 간의 가교 역할을 하여 API 호출을 실행하고 실시간 정보를 검색할 수 있도록 하며, 함수는 분업을 통해 개발자에게 보다 미묘한 제어 기능을 제공하여 에이전트가 클라이언트 측에서 실행할 수 있는 함수 매개변수를 생성할 수 있도록 합니다. 데이터 저장소는 상담원에게 정형 또는 비정형 데이터에 대한 액세스를 제공하여 데이터 기반 애플리케이션을 구현할 수 있도록 합니다.
The future of agents holds exciting advancements and we’ve only begun to scratch the surface of what is possible. As tools become more sophisticated and reasoning capabilities are enhanced, agents will be empowered to solve increasingly complex problems. Furthermore, the strategic approach of ‘agent chaining’ will continue to gain momentum. By 상담원의 미래는 흥미진진한 발전이 기다리고 있으며 가능한 일의 표면만 긁어모으기 시작했을 뿐입니다. 도구가 더욱 정교해지고 추론 능력이 향상됨에 따라 상담원은 점점 더 복잡한 문제를 해결할 수 있는 역량을 갖추게 될 것입니다. 또한 '에이전트 체인'이라는 전략적 접근 방식은 계속해서 탄력을 받을 것입니다. 작성자
combining specialized agents - each excelling in a particular domain or task - we can create a ‘mixture of agent experts’ approach, capable of delivering exceptional results across various industries and problem areas. 특정 도메인이나 업무에 탁월한 전문 에이전트를 결합하여 다양한 산업과 문제 영역에서 탁월한 결과를 제공할 수 있는 '에이전트 전문가 혼합' 접근 방식을 만들 수 있습니다.
It’s important to remember that building complex agent architectures demands an iterative approach. Experimentation and refinement are key to finding solutions for specific business cases and organizational needs. No two agents are created alike due to the generative nature of the foundational models that underpin their architecture. However, by harnessing the strengths of each of these foundational components, we can create impactful applications that extend the capabilities of language models and drive real-world value. 복잡한 에이전트 아키텍처를 구축하려면 반복적인 접근 방식이 필요하다는 점을 기억하는 것이 중요합니다. 실험과 개선은 특정 비즈니스 사례와 조직의 요구 사항에 맞는 솔루션을 찾는 데 있어 핵심입니다. 아키텍처를 뒷받침하는 기본 모델의 생성적 특성으로 인해 모든 에이전트가 똑같이 만들어지지는 않습니다. 그러나 이러한 각 기본 구성 요소의 강점을 활용하면 언어 모델의 기능을 확장하고 실제 가치를 창출하는 영향력 있는 애플리케이션을 만들 수 있습니다.
Endnotes 각주
Shafran, I., Cao, Y. et al., 2022, ‘ReAct: Synergizing Reasoning and Acting in Language Models’. Available at: https://arxiv.org/abs/2210.03629 샤프란, I., 카오, Y. 외, 2022, 'ReAct: 언어 모델에서 추론과 행동의 시너지 효과'. 사용 가능: https://arxiv.org/abs/2210.03629
Wei, J., Wang, X. et al., 2023, ‘Chain-of-Thought Prompting Elicits Reasoning in Large Language Models’. Available at: https://arxiv.org/pdf/2201.11903.pdf. 2023, '대규모 언어 모델에서 추론을 유도하는 생각의 연쇄', Wei, J., Wang, X. 외., '대규모 언어 모델에서 추론을 유도하는 생각의 연쇄'. 사용 가능: https://arxiv.org/pdf/2201.11903.pdf.
Wang, X. et al., 2022, ‘Self-Consistency Improves Chain of Thought Reasoning in Language Models’. Available at: https://arxiv.org/abs/2203.11171. Wang, X. 외, 2022, '자기 일관성은 언어 모델에서 사고 추론의 사슬을 개선합니다'. 사용 가능: https://arxiv.org/abs/2203.11171.
Diao, S. et al., 2023, ‘Active Prompting with Chain-of-Thought for Large Language Models’. Available at: https://arxiv.org/pdf/2302.12246.pdf. 2023, '대규모 언어 모델을 위한 생각의 사슬을 이용한 능동적 프롬프트', Diao, S. 외., 2023. 사용 가능: https://arxiv.org/pdf/2302.12246.pdf.
Zhang, H. et al., 2023, ‘Multimodal Chain-of-Thought Reasoning in Language Models’. Available at: https://arxiv.org/abs/2302.00923. 2023, '언어 모델에서 다중 모드 사고 연쇄 추론'. 이용 가능: https://arxiv.org/abs/2302.00923.
Yao, S. et al., 2023, ‘Tree of Thoughts: Deliberate Problem Solving with Large Language Models’. Available at: https://arxiv.org/abs/2305.10601. 야오, S. 외, 2023, '생각의 나무: 대규모 언어 모델을 사용한 신중한 문제 해결'. 이용 가능: https://arxiv.org/abs/2305.10601.
Long, X., 2023, ‘Large Language Model Guided Tree-of-Thought’. Available at: https://arxiv.org/abs/2305.08291. Long, X., 2023, '대규모 언어 모델 안내 트리 오브 씽크'. 사용 가능: https://arxiv.org/abs/2305.08291.
Google. ‘Google Gemini Application’. Available at: http://gemini.google.com. 구글. '구글 제미니 애플리케이션'. 사용 가능: http://gemini.google.com.
Swagger. ‘OpenAPI Specification’. Available at: https://swagger.io/specification/. Swagger. 'OpenAPI 사양'. 사용 가능: https://swagger.io/specification/.
Xie, M., 2022, ‘How does in-context learning work? A framework for understanding the differences from traditional supervised learning’. Available at: https://ai.stanford.edu/blog/understanding-incontext/. Xie, M., 2022, '맥락 내 학습은 어떻게 작동하나요? 기존 지도 학습과의 차이점을 이해하기 위한 프레임워크'. 사용 가능: https://ai.stanford.edu/blog/understanding-incontext/.