DeepInfra

DeepInfra

DeepInfra의 LLM을 LlamaIndex에서 바로 쓸 수 있게 해 주는 통합 가이드예요. 설치부터 동기·비동기 완성과 채팅까지 한 번에 다룹니다.

출처: 문서

본문

설치 (Installation)

먼저 필요한 패키지를 설치해요.

%pip install llama-index-llms-deepinfra

초기화 (Initialization)

DeepInfraLLM 클래스를 API 키와 원하는 파라미터로 설정해요.

from llama_index.llms.deepinfra import DeepInfraLLM
import asyncio


llm = DeepInfraLLM(
    model="mistralai/Mixtral-8x22B-Instruct-v0.1",  # 기본 모델명
    api_key="your-deepinfra-api-key",  # DeepInfra API 키로 교체
    temperature=0.5,
    max_tokens=50,
    additional_kwargs={"top_p": 0.9},
)

동기 완성 (Synchronous Complete)

complete 메서드로 텍스트 완성을 동기적으로 생성해요.

response = llm.complete("Hello World!")
print(response.text)

동기 스트림 완성 (Synchronous Stream Complete)

stream_complete 메서드로 텍스트 완성을 동기적으로 스트리밍해요.

content = ""
for completion in llm.stream_complete("Once upon a time"):
    content += completion.delta
    print(completion.delta, end="")

동기 채팅 (Synchronous Chat)

chat 메서드로 채팅 응답을 동기적으로 생성해요.

from llama_index.core.base.llms.types import ChatMessage


messages = [
    ChatMessage(role="user", content="Tell me a joke."),
]
chat_response = llm.chat(messages)
print(chat_response.message.content)

동기 스트림 채팅 (Synchronous Stream Chat)

stream_chat 메서드로 채팅 응답을 동기적으로 스트리밍해요.

messages = [
    ChatMessage(role="system", content="You are a helpful assistant."),
    ChatMessage(role="user", content="Tell me a story."),
]
content = ""
for chat_response in llm.stream_chat(messages):
    content += chat_response.message.delta
    print(chat_response.message.delta, end="")

비동기 완성 (Asynchronous Complete)

acomplete 메서드로 텍스트 완성을 비동기적으로 생성해요.

async def async_complete():
    response = await llm.acomplete("Hello Async World!")
    print(response.text)


asyncio.run(async_complete())

비동기 스트림 완성 (Asynchronous Stream Complete)

astream_complete 메서드로 텍스트 완성을 비동기적으로 스트리밍해요.

async def async_stream_complete():
    content = ""
    response = await llm.astream_complete("Once upon an async time")
    async for completion in response:
        content += completion.delta
        print(completion.delta, end="")


asyncio.run(async_stream_complete())

비동기 채팅 (Asynchronous Chat)

achat 메서드로 채팅 응답을 비동기적으로 생성해요.

async def async_chat():
    messages = [
        ChatMessage(role="user", content="Tell me an async joke."),
    ]
    chat_response = await llm.achat(messages)
    print(chat_response.message.content)


asyncio.run(async_chat())

비동기 스트림 채팅 (Asynchronous Stream Chat)

astream_chat 메서드로 채팅 응답을 비동기적으로 스트리밍해요.

async def async_stream_chat():
    messages = [
        ChatMessage(role="system", content="You are a helpful assistant."),
        ChatMessage(role="user", content="Tell me an async story."),
    ]
    content = ""
    response = await llm.astream_chat(messages)
    async for chat_response in response:
        content += chat_response.message.delta
        print(chat_response.message.delta, end="")


asyncio.run(async_stream_chat())

질문이나 피드백은 [email protected]으로 연락 주세요.

더 알아보기 (Learn more)