Aim은 LangChain 실행을 시각화하고 디버깅하는 것을 매우 쉽게 만들어줍니다. Aim은 LLM과 tool의 입력 및 출력뿐만 아니라 agent의 작업도 추적합니다. Aim을 사용하면 개별 실행을 쉽게 디버깅하고 검사할 수 있습니다: 또한 여러 실행을 나란히 비교할 수 있는 옵션도 있습니다: Aim은 완전한 오픈 소스입니다. GitHub에서 Aim에 대해 자세히 알아보세요. 이제 Aim callback을 활성화하고 구성하는 방법을 살펴보겠습니다.

Aim으로 LangChain 실행 추적하기

이 노트북에서는 세 가지 사용 시나리오를 살펴보겠습니다. 시작하기 위해 필요한 패키지를 설치하고 특정 모듈을 import하겠습니다. 그런 다음 Python 스크립트 내에서 또는 터미널을 통해 설정할 수 있는 두 개의 환경 변수를 구성하겠습니다.
pip install -qU  aim
pip install -qU  langchain
pip install -qU  langchain-openai
pip install -qU  google-search-results
import os
from datetime import datetime

from langchain_community.callbacks import AimCallbackHandler
from langchain_core.callbacks import StdOutCallbackHandler
from langchain_openai import OpenAI
우리의 예제는 LLM으로 GPT model을 사용하며, OpenAI는 이를 위한 API를 제공합니다. 다음 링크에서 key를 얻을 수 있습니다: platform.openai.com/account/api-keys . Google에서 검색 결과를 가져오기 위해 SerpApi를 사용할 것입니다. SerpApi key를 얻으려면 serpapi.com/manage-api-key로 이동하세요.
os.environ["OPENAI_API_KEY"] = "..."
os.environ["SERPAPI_API_KEY"] = "..."
AimCallbackHandler의 event method는 LangChain module 또는 agent를 입력으로 받아 최소한 prompt와 생성된 결과, 그리고 LangChain module의 직렬화된 버전을 지정된 Aim run에 기록합니다.
session_group = datetime.now().strftime("%m.%d.%Y_%H.%M.%S")
aim_callback = AimCallbackHandler(
    repo=".",
    experiment_name="scenario 1: OpenAI LLM",
)

callbacks = [StdOutCallbackHandler(), aim_callback]
llm = OpenAI(temperature=0, callbacks=callbacks)
flush_tracker function은 Aim에 LangChain asset을 기록하는 데 사용됩니다. 기본적으로 session은 완전히 종료되지 않고 재설정됩니다.

시나리오 1

첫 번째 시나리오에서는 OpenAI LLM을 사용합니다.
# scenario 1 - LLM
llm_result = llm.generate(["Tell me a joke", "Tell me a poem"] * 3)
aim_callback.flush_tracker(
    langchain_asset=llm,
    experiment_name="scenario 2: Chain with multiple SubChains on multiple generations",
)

시나리오 2

두 번째 시나리오는 여러 generation에 걸쳐 여러 SubChain을 연결하는 것입니다.
from langchain.chains import LLMChain
from langchain_core.prompts import PromptTemplate
# scenario 2 - Chain
template = """You are a playwright. Given the title of play, it is your job to write a synopsis for that title.
Title: {title}
Playwright: This is a synopsis for the above play:"""
prompt_template = PromptTemplate(input_variables=["title"], template=template)
synopsis_chain = LLMChain(llm=llm, prompt=prompt_template, callbacks=callbacks)

test_prompts = [
    {
        "title": "documentary about good video games that push the boundary of game design"
    },
    {"title": "the phenomenon behind the remarkable speed of cheetahs"},
    {"title": "the best in class mlops tooling"},
]
synopsis_chain.apply(test_prompts)
aim_callback.flush_tracker(
    langchain_asset=synopsis_chain, experiment_name="scenario 3: Agent with Tools"
)

시나리오 3

세 번째 시나리오는 tool을 사용하는 agent입니다.
from langchain.agents import AgentType, initialize_agent, load_tools
# scenario 3 - Agent with Tools
tools = load_tools(["serpapi", "llm-math"], llm=llm, callbacks=callbacks)
agent = initialize_agent(
    tools,
    llm,
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
    callbacks=callbacks,
)
agent.run(
    "Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?"
)
aim_callback.flush_tracker(langchain_asset=agent, reset=False, finish=True)
> Entering new AgentExecutor chain...
 I need to find out who Leo DiCaprio's girlfriend is and then calculate her age raised to the 0.43 power.
Action: Search
Action Input: "Leo DiCaprio girlfriend"
Observation: Leonardo DiCaprio seemed to prove a long-held theory about his love life right after splitting from girlfriend Camila Morrone just months ...
Thought: I need to find out Camila Morrone's age
Action: Search
Action Input: "Camila Morrone age"
Observation: 25 years
Thought: I need to calculate 25 raised to the 0.43 power
Action: Calculator
Action Input: 25^0.43
Observation: Answer: 3.991298452658078

Thought: I now know the final answer
Final Answer: Camila Morrone is Leo DiCaprio's girlfriend and her current age raised to the 0.43 power is 3.991298452658078.

> Finished chain.

Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.
I