serve README

The project's README from github.com/jina-ai/serve. As one markdown file: README.md.

Jina-Serve

PyPI PyPI - Downloads from official pypistats Github CD status

Jina-serve is a framework for building and deploying AI services that communicate via gRPC, HTTP and WebSockets. Scale your services from local development to production while focusing on your core logic.

Key Features

Comparison with FastAPI

Key advantages over FastAPI:

  • DocArray-based data handling with native gRPC support
  • Built-in containerization and service orchestration
  • Seamless scaling of microservices
  • One-command cloud deployment

Install

pip install jina

See guides for Apple Silicon and Windows.

Core Concepts

Three main layers:

Build AI Services

Let's create a gRPC-based AI service using StableLM:

from jina import Executor, requests
from docarray import DocList, BaseDoc
from transformers import pipeline


class Prompt(BaseDoc):
    text: str


class Generation(BaseDoc):
    prompt: str
    text: str


class StableLM(Executor):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.generator = pipeline(
            'text-generation', model='stabilityai/stablelm-base-alpha-3b'
        )

    @requests
    def generate(self, docs: DocList[Prompt], **kwargs) -> DocList[Generation]:
        generations = DocList[Generation]()
        prompts = docs.text
        llm_outputs = self.generator(prompts)
        for prompt, output in zip(prompts, llm_outputs):
            generations.append(Generation(prompt=prompt, text=output))
        return generations

Deploy with Python or YAML:

from jina import Deployment
from executor import StableLM

dep = Deployment(uses=StableLM, timeout_ready=-1, port=12345)

with dep:
    dep.block()
jtype: Deployment
with:
 uses: StableLM
 py_modules:
   - executor.py
 timeout_ready: -1
 port: 12345

Use the client:

from jina import Client
from docarray import DocList
from executor import Prompt, Generation

prompt = Prompt(text='suggest an interesting image generation prompt')
client = Client(port=12345)
response = client.post('/', inputs=[prompt], return_type=DocList[Generation])

Build Pipelines

Chain services into a Flow:

from jina import Flow

flow = Flow(port=12345).add(uses=StableLM).add(uses=TextToImage)

with flow:
    flow.block()

Scaling and Deployment

Local Scaling

Boost throughput with built-in features:

Example scaling a Stable Diffusion deployment:

jtype: Deployment
with:
 uses: TextToImage
 timeout_ready: -1
 py_modules:
   - text_to_image.py
 env:
  CUDA_VISIBLE_DEVICES: RR
 replicas: 2
 uses_dynamic_batching:
   /default:
     preferred_batch_size: 10
     timeout: 200

Cloud Deployment

Containerize Services

  1. Structure your Executor:
TextToImage/
├── executor.py
├── config.yml
├── requirements.txt
  1. Configure:
# config.yml
jtype: TextToImage
py_modules:
 - executor.py
metas:
 name: TextToImage
 description: Text to Image generation Executor
  1. Push to Hub:
jina hub push TextToImage

Deploy to Kubernetes

jina export kubernetes flow.yml ./my-k8s
kubectl apply -R -f my-k8s

Use Docker Compose

jina export docker-compose flow.yml docker-compose.yml
docker-compose up

JCloud Deployment

Deploy with a single command:

jina cloud deploy jcloud-flow.yml

LLM Streaming

Enable token-by-token streaming for responsive LLM applications:

  1. Define schemas:
from docarray import BaseDoc


class PromptDocument(BaseDoc):
    prompt: str
    max_tokens: int


class ModelOutputDocument(BaseDoc):
    token_id: int
    generated_text: str
  1. Initialize service:
from transformers import GPT2Tokenizer, GPT2LMHeadModel


class TokenStreamingExecutor(Executor):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.model = GPT2LMHeadModel.from_pretrained('gpt2')
  1. Implement streaming:
@requests(on='/stream')
async def task(self, doc: PromptDocument, **kwargs) -> ModelOutputDocument:
    input = tokenizer(doc.prompt, return_tensors='pt')
    input_len = input['input_ids'].shape[1]
    for _ in range(doc.max_tokens):
        output = self.model.generate(**input, max_new_tokens=1)
        if output[0][-1] == tokenizer.eos_token_id:
            break
        yield ModelOutputDocument(
            token_id=output[0][-1],
            generated_text=tokenizer.decode(
                output[0][input_len:], skip_special_tokens=True
            ),
        )
        input = {
            'input_ids': output,
            'attention_mask': torch.ones(1, len(output[0])),
        }
  1. Serve and use:
# Server
with Deployment(uses=TokenStreamingExecutor, port=12345, protocol='grpc') as dep:
    dep.block()


# Client
async def main():
    client = Client(port=12345, protocol='grpc', asyncio=True)
    async for doc in client.stream_doc(
        on='/stream',
        inputs=PromptDocument(prompt='what is the capital of France ?', max_tokens=10),
        return_type=ModelOutputDocument,
    ):
        print(doc.generated_text)

Support

Jina-serve is backed by Jina AI and licensed under Apache-2.0.

serve (jina-ai/serve)

Searching Database…

21.9K ·GitHub
Что это такое?Jina — это open-source Python-фреймворк для создания мультимодальных AI-приложений на cloud-native стеке: вы оборачиваете модели в gRPC-микросервисы, соединяете их в потоки (flows) и масштабируетесь от локального запуска до облака.
Это фреймворк или библиотека — и чем это отличается от того, чтобы просто использовать FastAPI?Фреймворк. В отличие от обычного FastAPI он даёт обработку данных на основе DocArray с нативной поддержкой gRPC, встроенную контейнеризацию и оркестрацию сервисов, бесшовное масштабирование микросервисов и развёртывание в облаке одной командой.
Как его запустить?Установите Python-пакет — в README есть ссылки на руководства по установке, включая отдельные для Apple Silicon и Windows — затем определите и запустите сервисы локально на Python или YAML.
Нужно ли заранее настроить Kubernetes или Docker, чтобы хоть что-то заработало?Нет — чтобы запустить сервисы локально, достаточно Python. Kubernetes, Docker Compose и Jina Hub понадобятся, только когда вы будете контейнеризировать сервисы и развёртывать их в облаке.
Обязательно ли развёртывать через собственное облако Jina (JCloud)?Нет. Сервисы масштабируются локально из коробки, а контейнеризировать и развёртывать их можно самостоятельно — в Kubernetes или через Docker Compose; развёртывание одной командой в JCloud — это просто вариант «в один клик».
Могу ли я использовать это в своём коммерческом продукте?Да — jina-serve распространяется по лицензии Apache-2.0 и поддерживается Jina AI, так что пользоваться им можно бесплатно, в том числе в коммерческих целях.
Из каких основных блоков состоит проект на Jina?Три слоя: Data — BaseDoc и DocList для входных и выходных данных; Serving — Executors обрабатывают Documents, а Gateway соединяет сервисы; Orchestration — Deployments обслуживают Executors, а Flows собирают пайплайны.
Как выглядит минимальный AI-сервис?Вы создаёте сервис на основе gRPC вокруг модели — в README в качестве примера используется StableLM — развёртываете его через Python или YAML и обращаетесь к нему через клиент. Соедините несколько сервисов в Flow — и получится пайплайн.
Как он справляется с большой нагрузкой?Встроенное масштабирование: replicas для параллельной обработки, shards для разбиения данных и dynamic batching для эффективного инференса моделей — в README это показано на примере развёртывания Stable Diffusion.
Поддерживается ли потоковая выдача ответов от LLM?Да — потоковая передача токен за токеном встроена, поэтому LLM-приложения могут показывать ответ по мере его генерации, не дожидаясь полного ответа.
What are similar projects?metaflow, gofr, signoz, jaeger, openobserve, bifrost, OpenLLM, skypilot
Creator
jina-ai
Size
1.6 GB
Stars
21.9K
Age
6y
Commits · 90 Days