Magentic으로 LLM 활용한 간단한 Python 코드 작성 방법
AI Store에서 AI코딩으로 만들어진 앱을 만나보세요!
지금 바로 방문하기

LLM을 활용한 간단한 Python 코드 작성 방법

카테고리

프로그래밍/소프트웨어 개발

서브카테고리

인공지능

대상자

LLM(대규모 언어 모델)을 활용한 Python 스크립트 개발자, 간결한 코드 구현이 필요한 개발자

난이도: 초급~중급 (Python 및 LLM 기초 지식 필요)

핵심 요약

  • Magentic 패키지@prompt 데코레이터를 통해 LLM 호출을 3줄의 코드로 구현 가능
  • OpenAI, Anthropic, Ollama 등 다양한 LLM과 호환 가능 (LiteLLM 또는 OpenAI 호환 API 필요)
  • Pydantic Dataclass를 활용해 구조화된 출력데이터 처리 가능
  • 비동기 처리(async def) 및 스트리밍 응답(StreamedStr) 지원

섹션별 세부 요약

1. Magentic 소개 및 기본 사용법

  • openai, anthropic 등 기존 패키지보다 더 간단한 코드로 LLM 호출 가능
  • @prompt 데코레이터 사용 시 함수 본문 없이도 호출 가능한 함수 생성
  • 예시:

```python

from magentic import prompt

@prompt('Add more "dude"ness to: {phrase}')

def dudeify(phrase: str) -> str: ...

```

2. Pydantic 활용한 구조화된 출력

  • Pydantic BaseModel을 통해 API 응답 형식 정의 가능
  • 예시:

```python

class Animal(BaseModel):

species: str

legs: int

...

@prompt("Give me information on the animal {animal_name}.")

def animal_info(animal_name: str) -> Animal: ...

```

3. `@chatprompt`과 few-shot 학습

  • @chatprompt을 통해 대화형 메시지 전달 가능
  • 예시:

```python

@chatprompt(

SystemMessage("You are a movie buff."),

UserMessage("What is your favorite quote from {movie}?"),

...

)

def get_movie_quote(movie: str) -> Quote: ...

```

4. `@prompt_chain`과 외부 함수 호출

  • @prompt_chain을 통해 LLM이 외부 함수 호출 가능
  • 예시:

```python

@prompt_chain(

"Use your tools to answer the user's question: {query}",

functions=[web_search],

)

def search(query: str) -> str: ...

```

5. 다양한 LLM 지원 및 설정

  • LiteLLM, Anthropic, Ollama다양한 LLM 지원
  • 예시:

```python

model = AnthropicChatModel("claude-4-sonnet-latest")

@prompt(..., model=model)

def dudeify(...): ...

```

6. 비동기 처리 및 스트리밍

  • async def비동기 함수 생성 가능
  • StreamedStr을 통해 스트리밍 응답 처리
  • 예시:

```python

@prompt("Tell me about {country}")

def describe_country(country: str) -> StreamedStr: ...

```

결론

Magentic은 LLM 호출을 간결하게 구현할 수 있는 Python 패키지로, Pydantic, 비동기, 스트리밍 등 다양한 기능을 지원합니다. PEP 723과 uv를 활용해 스크립트 실행을 간소화할 수 있으며, LiteLLM 호환 LLM을 통해 확장성을 확보할 수 있습니다.