"에이전트들이 협업하며, 자율적으로 해동 계획을 수립하고, 목표를 달성하는 시스템 전체 또는 프레임워크이다". 보통 AI Agent 라는 부르는 것은 "특정 목표를 수행하는 개별 인공지능 객체"를 의미한다.
Agentic AI 에서 중요한 것은 3가지 이다.
- 자율적 자기주도적 사고
- 멀티에이전트 협업 능력
- 목표 달성 중심 시스템(프레임워크)
AI Engineering 롤을 두개로 나눈다면 AI Solution Engineer와 AI Data Engineer로 나눠 보았을 때, AI Solution Engineer가 Agentic AI 시스템을 구축하는 것이고, AI Data Engineer가 전통적인 ML 및 비즈니스 핵심 알고리즘을 구현하는 부분이라 본다.
그렇다면 AI Solution Engineering의 파트를 구체화 한다면 다음의 7 Layers로 나누어 볼 수 있겠다.
Where humans interact with the agent - through chatbots, dashboards, or voice assistants.
It’s the UI layer of agent interaction.
2. Discovery Layer
This is how the agent finds and injects relevant knowledge
- using RAG, vector databases, and memory recall techniques.
3. Agent Composition Layer
Defines the internal structure of your agent.
Combines modular sub-agents into complex, goal-driven workflows.
4. Reasoning & Planning Layer
The thinking brain of the agent. It plans actions, reflects, sets priorities,
and uses strategies like CoT or ReAct.
5. Tool & API Layer
Connects reasoning to real-world execution.
It handles file systems, APIs, shell commands, and function calls.
6. Memory & Feedback Layer
Where the agent learns and adapts.
Stores past interactions, builds self-awareness, and uses memory to improve.
7. Infrastructure Layer
The backend engine scales agents, manages models, deploys pipelines,
and secures the whole system.
인프라스트럭처의 LLMOps 에서 부터 A2A 또는 LangGraph와 같은 Framework을 활용하여 Multi Agent를 구현하고, UI를 제공하는 모든 부분을 Agentic AI Framework 또는 System 이라 말할 수 있다. 이부분을 AI Solution Engineer가 해야할 영역으로 본다.
Agentic AI Solution 은 "자기 주도적이면 자율적으로 멀티 에이전트가 협업하여 목표를 달성하는" 것을 목적으로 한다. 여기서 해당 솔루션을 비즈니스에 적용하기 위하여 최근 이야기 되고 있는 Context Engineering 관점의 접근도 필요하다.
Context Engineering 이란?
“Context Engineering”은 특히 대규모 언어 모델(LLM) 시대에 들어서면서 주목받는 개념으로, AI가 정확하게 이해하고 응답할 수 있도록 입력(프롬프트)의 맥락을 설계·조정하는 기술 또는 실천적 전략을 의미한다. 즉 AI Solution Engineer는 Agentic AI System 구축시 (AI Data Engineer가) Context Engineering을 유연하게 적용할 수 있는 시스템을 지향해야 한다.
Context Engineering = Prompting + Memory + Retrieval + Role Control + History 관리의 종합 아키텍처 설계 기술
프롬프트의 시대는 저물고 있습니다.
이제는 더욱 중요한 '컨텍스트'를 설계해야 할 때입니다.
해외 AI 업계에서는 최근 '컨텍스트 엔지니어링'이라는 개념이 주목받고 있습니다.
단순히 질문(프롬프트)을 잘 던지는 것만으로는 부족하다는 뜻입니다.
중요한 건, AI가 제대로 이해하고 일할 수 있도록 '맥락'을 설계하는 일입니다.
AI는 신입사원과 같습니다. 업무 지시만으로는 부족합니다.
조직의 문화, 일하는 방식, 기대 기준 등을 함께 알려줘야 제대로 일합니다.
'맥락'은 단순한 배경정보가 아닙니다.
우리가 평소 사용하는 리포트 포맷, 문서 스타일, 브랜드의 말투 등이 곧 조직의 언어이자 컨텍스트이죠.
결국 AI에게 일을 시키려면, 우리가 어떻게 일하는지를 먼저 정의해야 합니다.
AI를 잘 쓴다는 건, 우리 조직의 이상적인 일처리 기준을 정의하고, 그것을 AI에게 정확히 전달하는 것입니다.
이제는 ‘프롬프트’가 아닌 ‘컨텍스트’를 설계하는 시대입니다.
LLM을 도구 이상으로 활용하려면, 그 배경에 숨어 있는 이 섬세한 맥락 설계의 기술과 감각을 이해하여 사용한다.
Usage: uv [OPTIONS] <COMMAND>
Commands:
run Run a command or script
init Create a new project
add Add dependencies to the project
remove Remove dependencies from the project
sync Update the project's environment
lock Update the project's lockfile
export Export the project's lockfile to an alternate format
tree Display the project's dependency tree
tool Run and install commands provided by Python packages
python Manage Python versions and installations
pip Manage Python packages with a pip-compatible interface
venv Create a virtual environment
build Build Python packages into source distributions and wheels
publish Upload distributions to an index
cache Manage uv's cache
self Manage the uv executable
version Display uv's version
help Display documentation for a command
Cache options:
-n, --no-cache Avoid reading from or writing to the cache, instead using a temporary directory for the
duration of the operation [env: UV_NO_CACHE=]
--cache-dir <CACHE_DIR> Path to the cache directory [env: UV_CACHE_DIR=]
Python options:
--python-preference <PYTHON_PREFERENCE> Whether to prefer uv-managed or system Python installations [env:
UV_PYTHON_PREFERENCE=] [possible values: only-managed, managed, system,
only-system]
--no-python-downloads Disable automatic downloads of Python. [env: "UV_PYTHON_DOWNLOADS=never"]
Global options:
-q, --quiet
Do not print any output
-v, --verbose...
Use verbose output
--color <COLOR_CHOICE>
Control the use of color in output [possible values: auto, always, never]
--native-tls
Whether to load TLS certificates from the platform's native certificate store [env: UV_NATIVE_TLS=]
--offline
Disable network access [env: UV_OFFLINE=]
--allow-insecure-host <ALLOW_INSECURE_HOST>
Allow insecure connections to a host [env: UV_INSECURE_HOST=]
--no-progress
Hide all progress outputs [env: UV_NO_PROGRESS=]
--directory <DIRECTORY>
Change to the given directory prior to running the command
--project <PROJECT>
Run the command within the given project directory
--config-file <CONFIG_FILE>
The path to a `uv.toml` file to use for configuration [env: UV_CONFIG_FILE=]
--no-config
Avoid discovering configuration files (`pyproject.toml`, `uv.toml`) [env: UV_NO_CONFIG=]
-h, --help
Display the concise help for this command
-V, --version
Display the uv version
> npx create-nx-workspace
✔ Where would you like to create your workspace? · aip
✔ Which stack do you want to use? · none
✔ Would you like to use Prettier for code formatting? · Yes
✔ Which CI provider would you like to use? · azure
NX Creating your v20.5.0 workspace.
✔ Installing dependencies with npm
[2] NX 전용 파이썬 플러그인을 설치한다. @nxlv/python 은 build, publish 등 uv 패키지 메니져 사용시, poetry 의 장점을 보완한다.
NX의 모노레포 아키텍쳐에서는 Shell Library Pattern 방식을 지향한다. 이는 다양한 애플리케이션(서비스)안에서 사용하는 패키지(라이브러리)를 분리 관리하는 방식으로 확장성과 유지보수성을 높혀준다.
프로젝트에서 애플리케이션의 모든 페이지와 컴포넌트를 패키지에 담고, 애플리케이션은 이들의 조합하고 설정하는 역할만 수행한다. 이때 패키지는 Nexus Registry에 배포하여 버전관리를 하게되면 유지보수성이 좋아진다.
실 프로젝트에서 Frontend 파트를 보면 Micro Applications들은 각가의 Micro Frontend 로 구성하고, Portal 이 라는 곳에서 Module Federation을 통해 각 micro frontend를 통합하여 표현한다. Micro Frontend에는 비즈니스 로직이 없고, 애플리케이션 구성 환경설정만 존재한다. libs 폴더안에 있는 것이 패키지로 각 패키지는 NPM Registry에 배포되어 버전 관리를 하고, 애플리케이션은 libs에 있는 패키지를 통해 화면 및 비지니스 로직을 구현한다.
Peter real project folder structure
NX의 Shell Library Pattern도 유사하게 Feature Shell 이라는 Integrated Application을 제공한다.
Figure 1
A domain-wise application is the composition of every application that has the same routes, behavior, and functionalities. In the example in Figure 1, the Booking Application is the union of the Booking Web Application, the Booking Desktop Application, and the Booking Mobile Application.
UV 기반의 python 애플리케이션 또는 패키지를 생성(Generate)하기 위한 명령어.
npx nx g @nxlv/python:uv-project src --projectType=library --directory=packages/embedding --packageName=aip-embedding --publishable
- src 폴더 밑으로 템플릿 기반 소스 생성
- pyproject.toml 파일 생성
- project.json NX 환경파일 생성
- 그외 Unit test 용 tests 폴더 생성
▶ npx nx g @nxlv/python:uv-project src --projectType=library --directory=packages/embedding --packageName=aip-embedding --publishable
NX Generating @nxlv/python:uv-project
CREATE packages/embedding/project.json
CREATE packages/embedding/README.md
CREATE packages/embedding/.python-version
CREATE packages/embedding/src/__init__.py
CREATE packages/embedding/src/hello.py
CREATE packages/embedding/pyproject.toml
CREATE packages/embedding/tests/__init__.py
CREATE packages/embedding/tests/conftest.py
CREATE packages/embedding/tests/test_hello.py
=========
▶ npx nx g @nxlv/python:uv-project --help
NX generate @nxlv/python:uv-project [name] [options,...]
From: @nxlv/python (v20.7.0)
Name: uv-project
Options:
--name [string]
--projectType Project type [string] [choices: "application",
"library"] [default: "application"]
--buildBundleLocalDependencies Bundle local dependencies [boolean] [default: true]
--buildLockedVersions Use locked versions for build dependencies [boolean] [default: true]
--codeCoverage Generate code coverage report [boolean] [default: true]
--codeCoverageHtmlReport Generate html report for code coverage [boolean] [default: true]
--codeCoverageThreshold Code coverage threshold [number]
--codeCoverageXmlReport Generate Xml report for code coverage [boolean] [default: true]
--description Project short description [string]
--devDependenciesProject This approach installs all the missing dev [string]
dependencies in a separate project
(optional)
--directory A directory where the project is placed [string]
--linter Project linter [string] [choices: "flake8", "ruff",
"none"] [default: "ruff"]
--moduleName Python module name [string]
--packageName Python package name [string]
--projectNameAndRootFormat Whether to generate the project name and [string] [choices: "as-provided",
root directory as provided (`as-provided`) "derived"] [default: "as-provided"]
or generate them composing their values and
taking the configured layout into account
(`derived`).
--publishable Project is publishable [boolean]
--pyenvPythonVersion Pyenv .python-version content (default to [string]
current python version)
--pyprojectPythonDependency Pyproject python dependency version range [string] [default: ">=3.9,<4"]
--rootPyprojectDependencyGroup If a shared pyproject.toml is used, which [string] [default: "main"]
dependency group does this new project
should belong to
--tags, -t Add tags to the project (used for linting) [string]
--templateDir Custom template directory, this will [string]
override the default template, if not
provided the default template will be used
--unitTestHtmlReport Generate html report for unit tests [boolean] [default: true]
--unitTestJUnitReport Generate junit report for unit tests [boolean] [default: true]
--unitTestRunner Project unit test runner [string] [choices: "pytest", "none"]
[default: "pytest"]
- AI agents typically use language models as part of their software stack to interpret messages, perform reasoning, and execute actions.
- Each agent is a self-contained unit that can be developed, tested, and deployed independently.
[2] Multi Agent 특징
- Run within the same process or on the same machine
- Operate across different machines or organizational boundaries
- Be implemented in diverse programming languages and make use of different AI models or instructions
- Work together towards a shared goal, coordinating their actions through messaging
[3] Agent 실행 환경
the framework provides a runtime environment, which facilitates communication between agents, manages their identities and lifecycles, and enforce security and privacy boundaries.
Standalone Agent Runtime
- single process application
- all agents are implemented in the same language
- running in the same process.
Agent는 runtime 동안 메세지를 통해 통신을 하고, 런타임은 Agent의 LifeCycle을 관리한다.
Distrubuted Agent Runtime
- multi process applications
- Agents are implemented in different programming languages
- running on different machines
분산환경은 host servicer와 multiple workers를 갖는다.
- host servicer는 agent 사이의 통신과 연결상태를 관리한다.
- worker는 agent를 구동하고 host servicer와 gateway를 통해 통신한다.
[4] 애플리케이션 스택
AutoGen core는 다양한 multi-agent application 개발할 때 사용된다.
[5] Agent 식별 방법 & 라이프 사이클 관리
Agent 런타임은 에이젼트 identities와 lifecyles을 관리한다.
- Agent ID = Agent Type + Agent Key(instance)
런타임에서 Agent가 없으면 생성하고, 메세지로 agent type & key를 전달한다.
[6] Topic & Subscription
message를 broadcast할 때 방법을 설명한다.
- Topic : pubishing messages with Topic Type, Topic Source
- Subscription : topic 과 agentID와 맵팽한다. 런타임 환경에 맵핑을 만들고 삭제할 수 있다.
Type-based subscription
Topic Type -> Agent Type 전파
- Single Tenant & Single Topic
- Single Tenant & Multi Topics
- Multi Tenant
in single tenant, the topic source is "default". for multi tenant, it become data-dependent.
with get_openai_callback() as cb:는 Python의 컨텍스트 관리자(context manager)를 사용하여 get_openai_callback 함수가 반환하는 객체(cb)를 생성하고, 그 객체를 사용하는 블록을 정의하는 구문입니다. 이 구문을 이해하기 위해서는 Python의 컨텍스트 관리자가 어떻게 작동하는지와 get_openai_callback이 어떤 역할을 하는지를 아는 것이 중요합니다.
1. 컨텍스트 관리자 (Context Manager)
컨텍스트 관리자는 with 블록의 시작과 종료 시 특정 코드를 자동으로 실행하게 해줍니다. 일반적으로, 컨텍스트 관리자는 자원(resource)을 할당하고 해제하는 작업에 사용됩니다. 예를 들어, 파일을 열고 작업을 한 후 자동으로 파일을 닫는 데 사용할 수 있습니다.
•__enter__(): with 블록이 시작될 때 호출됩니다. 이 메서드는 일반적으로 어떤 자원을 할당하거나 초기화합니다.
•__exit__(): with 블록이 끝날 때 호출됩니다. 이 메서드는 자원을 해제하거나, 예외가 발생했을 때 이를 처리합니다.
2. get_openai_callback의 역할
get_openai_callback은 OpenAI API 호출과 관련된 메트릭을 수집하는 콜백 객체를 반환합니다. 이 콜백 객체는 컨텍스트 관리자에서 사용될 때 API 호출 동안의 토큰 사용량, 비용 등을 추적합니다.
3. with get_openai_callback() as cb:의 의미
•get_openai_callback()은 컨텍스트 관리자 역할을 하는 객체를 반환합니다.
•with 블록이 시작되면, cb 변수에 이 객체가 할당됩니다.
•with 블록 내에서 OpenAI API 호출이 이루어지면, cb 객체는 API 호출 관련 데이터를 수집합니다.
•with 블록이 종료되면, cb 객체는 수집한 데이터를 자동으로 정리하고, 필요한 경우 자원을 해제합니다.
예시 코드 분석
from langchain.llms import OpenAI
from langchain.callbacks import get_openai_callback
llm = OpenAI(model="text-davinci-003")
with get_openai_callback() as cb:
response = llm("What is the capital of France?")
print(response)
print(f"Total Tokens: {cb.total_tokens}")
print(f"Total Cost: {cb.total_cost}")
•get_openai_callback(): 콜백 객체를 생성하여 반환합니다.
•with ... as cb:: cb 변수에 콜백 객체를 할당하고, with 블록 내에서 이 객체를 사용합니다.
•cb.total_tokens, cb.total_cost: with 블록이 끝난 후, API 호출 동안 사용된 총 토큰 수와 총 비용을 출력합니다.
이 구문을 사용함으로써 개발자는 OpenAI API 호출의 성능을 모니터링하고 리소스 사용량을 효율적으로 관리할 수 있습니다.
get_openai_callback
소스: langchain_community/callbacks/manager.py
from contextlib import contextmanager
@contextmanager
def get_openai_callback() -> Generator[OpenAICallbackHandler, None, None]:
"""Get the OpenAI callback handler in a context manager.
which conveniently exposes token and cost information.
Returns:
OpenAICallbackHandler: The OpenAI callback handler.
Example:
>>> with get_openai_callback() as cb:
... # Use the OpenAI callback handler
"""
cb = OpenAICallbackHandler()
openai_callback_var.set(cb)
yield cb
openai_callback_var.set(None)