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 是一个开源的 Python 框架,用于在云原生技术栈上构建多模态 AI 应用——你可以把模型封装成 gRPC 微服务,把它们串成 Flow(流程),并从本地扩展到云端。
它是框架还是库?和直接用 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 项目主要由哪些部分组成?分三层:数据层——用 BaseDoc 和 DocList 处理输入和输出;服务层——Executor 处理 Document,Gateway 负责连接各个服务;编排层——Deployment 用来运行 Executor,Flow 用来搭建流水线。
一个最简单的 AI 服务长什么样?你围绕一个模型创建一个基于 gRPC 的服务——README 里演示的是 StableLM——用 Python 或 YAML 部署它,然后通过客户端调用。把多个服务串进一个 Flow,就得到一条流水线。
它怎么应对高负载?内置了扩缩容机制:replicas 用于并行处理,shards 用于数据分片,dynamic batching 用于高效的模型推理——README 用一个 Stable Diffusion 部署演示了这些功能。
支持流式输出 LLM 的回答吗?支持——内置了逐 token 的流式输出,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