2026/08 20

X. Agent의 여러 요소를 하나의 class Agent로 묶어가는 과정.

# 1. Dictionary와 Class의 차이 # 다음과 같은 경우 딕셔너리를 사용하세요: # 단순히 데이터일 때 # JSON에 바로 전달할 때 # 별도의 규칙을 적용할 필요가 없을 때 # 다음과 같은 경우 클래스를 사용하세요: # 데이터와 동작이 함께 있어야 할 때 # 여러 개의 독립적인 복사본이 필요할 때 # 유효하지 않은 상태를 방지해야 할 때 #-------- 2. 첫 번째 Agent 클래스(Agent라는 새로운 자료형 만들기): __init__()와 self class Agent: def __init__(self, name, max_steps=5): self.na..

Agentic AI/AI_AGENT 2026.08.24

IX. AI Agent에 “기억과 기록” 기능을 붙이는 단계

# 1. 파일에 쓰고 읽기 with open("notes.txt", "w", encoding="utf-8") as f: f.write("에이전트 작동이 시작되었습니다. \n") f.write("tool: search \n") with open("notes.txt", "r", encoding="utf-8") as f: contents = f.read() print(contents) print("characters: ", len(contents)) #-------- 2. 로그 파일에 추가하기 with open("runlog.txt", "a", encoding="utf-8") as f: f.write("1단계 | searc..

Agentic AI/AI_AGENT 2026.08.23

VIII. Agent Loop + Tool Dispatcher 다음 단계인 예외 처리(Exception), 재시도(Retry), Logging 스터디

# 1. KeyError — 딕셔너리에 없는 키를 찾았을 때 # def get_units(record): # return record["units"] # get_units({"sku":"51001"}) # 결과: Exception has occurred: KeyError 'units' #-------- 2. try / except / else / finally def to_int(value): try: number = int(value) except ValueError: print(f" {value!r}을 숫자로 변환할 수 없습니다.") return None exce..

Agentic AI/AI_AGENT 2026.08.23

VII. Python 함수 → Tool 함수 → Agent의 Tool Dispatcher 구조

# 1. 함수의 기본값과 키워드 인수 def search(query, limit=3, safe=True): mode = "safe" if safe else "unfiltered" return f"searching '{query}' | limit={limit} | {mode}" print(search("환불정책")) print(search("환불정책", 10)) print(search("환불정책", limit=5, safe=False)) print(search(limit=1, query="환불정책")) #-------- 2. 함수 기본값의 함정 (mutable default) def add_bad(item, bucket=[]): ..

Agentic AI/AI_AGENT 2026.08.23

VI. Python의 반복문과 자료구조를 이용해 AI Agent의 실제 실행 흐름을 만드는 과정

# 1. history 순회 + range() history = [ {"role":"user","content":"제품번호 5001의 재고를 확인해라."}, {"role":"assistant", "content":"지금 찾아보고 있어요."}, {"role":"user", "content":"그 제품이 어느 창고로부터 배송되는지 확인해라."}, ] for message in history: print(f"{message['role']}: {message['content']}") print() for i in range(3): print(f"step {i}") #-------- 2. enumerate() + ..

Agentic AI/AI_AGENT 2026.08.23

V. AI Agent의 핵심 부품들 하나씩 만들어보기

# 1. Tool 실행과 안전장치 TOOLS = {"calculator": lambda a: eval_expr(a.get("expr",""))} def eval_expr(expr): return f"{expr}의 결과값" def run_tool(name, args, steps, max_steps): if steps >= max_steps: return "중지되었습니다. 단계 제한에 도달하였습니다." if name not in TOOLS: return f"중지되었습니다. {name}이라는 툴이 없습니다." if not isinstance(args, dict): return "중지..

Agentic AI/AI_AGENT 2026.08.23

IV. AI Agent가 LLM의 응답을 JSON으로 받고, 그 안에서 Tool 이름과 인자(arguments)를 꺼내서 실제 Tool 실행으로 연결하기 위한 기초

# 1. JSON 문자열을 Python 객체로. import json raw = '{"tool":"search", "args":{"query":"refund policy"}, "done":false}' data = json.loads(raw) print(type(data)) print(data["tool"]) print(data["args"]["query"]) print(data["done"], type(data["done"])) #-------- 2. Python 객체를 JSON 문자열로 import json payload = { "model":"some-model", "max_tokens": 2048, ..

Agentic AI/AI_AGENT 2026.08.22

III. 대화 기록(history)을 어떻게 Python으로 관리하는가

history = [ {"role":"system", "content":"너는 도움을 주는 에이전트야."}, {"role":"user", "content":"내 주문에 대한 배송이 늦네."}, {"role":"assistant", "content":"내가 그 주문을 확인해 볼께."}, ] print(history[1]["content"]) print("Turns: ", len(history)) for msg in history: print(f"[{msg['role']:^9}] {msg['content']}") #-------- response = { "id":"steven_20", "usage..

Agentic AI/AI_AGENT 2026.08.22

II. AI Agent를 만들 때 자주 사용하는 패턴들

# 1. 변수 f-string user_name = "스티븐" task = "분기별 판매 보고서를 요약하세요." step = 2 max_steps = 5 prompt = f"User: {user_name} \nTask: {task} \nStep {step} of {max_steps}" print(prompt) #------- 2. 숫자 formatting tokens_used = 25123 cost_per_token = 0.000003 print(f"사용한 토큰수: {tokens_used:,}") print(f"현재까지 비용: ${tokens_used * cost_per_token:.4f}") print(f"남아있는 예산: ${100..

Agentic AI/AI_AGENT 2026.08.22

I. Python 실행 환경이 제대로 갖춰져 있는지 확인하는 간단한 점검 프로그램

import sys import os print("파이썬 실행환경 체크하기") print("-"*30) version = f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}" print("Python version: " + version) in_venv = sys.prefix != sys.base_prefix print("Virtual env active: " + str(in_venv)) print("Interpreter path: " + sys.executable) print("Working folder: " + os.getcwd()) if sys.vers..

Agentic AI/AI_AGENT 2026.08.22