Python 및 TypeScript v2 Functions는 실행 결과를 청크 단위로 스트리밍할 수 있습니다. 이는 데이터가 시간이 지남에 따라 사용 가능해질 때 유용하며, 소비 애플리케이션이 결과가 완료되기 전에 처리를 시작할 수 있도록 합니다.
응답을 스트리밍하려면, Python Functions는 Iterable[T] 반환 유형으로 주석을 달고, yield 키워드를 사용하여 값이 사용 가능해질 때마다 생성해야 합니다. TypeScript에서는 function 키워드 뒤에 * 문자를 추가하여 비동기 생성자 Function을 선언하고, AsyncIterable<T> 반환 유형을 지정하며, yield 키워드를 사용하여 값이 사용 가능해질 때마다 생성해야 합니다.
다음 예제는 각 정수 사이에 1초가 경과하는 정수 스트림을 반환하는 Function을 보여줍니다:
Copied!1 2 3 4 5 6 7 8 9from functions.api import function from typing import Iterable import time @function def my_lazy_number_generator(n: int) -> Iterable[int]: for i in range(n): time.sleep(1) yield i
Copied!1 2 3 4 5 6 7 8import { Integer } from "@osdk/functions"; export default async function* myLazyNumberGenerator(n: Integer): AsyncIterable<Integer> { for (let i = 0; i < n; i++) { await new Promise(resolve => setTimeout(resolve, 1_000)); yield i; } }
스트리밍 응답을 사용하는 Functions는 전체 결과물을 생성하는 데 시간이 걸릴 수 있는 언어 모델과 작업할 때 유용합니다. 모델이 응답의 각 청크를 생성할 때마다 이를 제공함으로써, 전체 응답이 완료될 때까지 기다리지 않고 실시간 경험을 제공합니다. Functions에서 언어 모델을 호출하는 방법에 대한 자세한 내용은 TypeScript v2 및 Python Functions에서의 언어 모델을 확인 해주세요.
다음 예제는 openai SDK를 사용하여 언어 모델을 호출하고, 요청에서 stream 플래그를 활성화하여 응답을 스트리밍으로 반환하는 방법을 보여줍니다:
Copied!1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34from openai import OpenAI from functions.api import function from functions.aliases import model from foundry_sdk.v2.language_models import ( get_openai_base_url, get_foundry_token, get_http_client, ) from typing import Iterable @function def create_chat_completion(prompt: str) -> Iterable[str]: client = OpenAI( api_key=get_foundry_token(preview=True), base_url=get_openai_base_url(preview=True), http_client=get_http_client(preview=True), ) stream = client.chat.completions.create( model=model("gpt55").rid, messages=[ { "role": "user", "content": prompt, }, ], stream=True ) for event in stream: if event.choices: content = event.choices[0].delta.content if content: yield content
Copied!1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27import { PlatformClient } from "@osdk/client"; import OpenAI from "openai"; import { Aliases } from "@osdk/functions"; import { getFoundryToken, getOpenAiBaseUrl, createFetch } from "@osdk/language-models"; export default async function* createChatCompletion(client: PlatformClient, prompt: string): AsyncIterable<string> { const oaiClient = new OpenAI({ apiKey: await getFoundryToken(client), baseURL: getOpenAiBaseUrl(client), fetch: createFetch(client), }); const stream = await oaiClient.chat.completions.create({ model: Aliases.model("gpt55").rid, messages: [ { role: 'user', content: prompt }, ], stream: true }); for await (const event of stream) { const content = event.choices[0]?.delta?.content; if (content) { yield content; } } }
스트리밍 Function을 태그하고 게시한 후, React 애플리케이션, Workshop의 사용자 정의 위젯 또는 다른 Function에서 온톨로지 SDK를 통해 실행할 수 있습니다.
온톨로지 SDK를 통해 스트리밍 응답을 사용하는 Functions를 실행하는 기능은 베타 개발 단계에 있습니다. 활성 개발 중에 기능이 변경될 수 있습니다.
Copied!1 2 3 4 5 6from foundry_sdk_runtime import AllowBetaFeatures with AllowBetaFeatures(): with client.ontology.queries.create_chat_completion_streaming(prompt="Where is Mount Everest?") as stream: for text in stream: # ...
Copied!1 2 3 4 5 6 7 8 9 10 11 12import { __EXPERIMENTAL__NOT_SUPPORTED_YET__executeStreamingFunction } from "@osdk/api/unstable"; const stream = client(__EXPERIMENTAL__NOT_SUPPORTED_YET__executeStreamingFunction).executeStreamingFunction( createChatCompletion, { prompt: "Where is Mount Everest?", } ); for await (const text of stream) { // ... }