Replicate Python client

news2025/7/19 16:36:26

在这里插入图片描述

本文翻译整理自:https://github.com/replicate/replicate-python

文章目录

    • 一、关于 Replicate Python 客户端
      • 相关链接资源
      • 关键功能特性
    • 二、1.0.0 版本的重大变更
    • 三、安装与配置
      • 1、系统要求
      • 2、安装
      • 3、认证配置
    • 四、核心功能
      • 1、运行模型
      • 2、异步IO支持
      • 3、流式输出模型
      • 4、后台运行模型
      • 5、后台运行模型并获取Webhook
      • 6、组合模型管道
      • 7、获取运行中模型的输出
      • 8、取消预测
      • 9、列出预测
      • 10、加载输出文件
        • FileOutput 对象
      • 11、列出模型
      • 12、创建模型
      • 13、微调模型
      • 14、自定义客户端行为
    • 五、开发


一、关于 Replicate Python 客户端

这是一个用于 Replicate 的 Python 客户端库,允许您从 Python 代码或 Jupyter Notebook 中运行模型,并在 Replicate 平台上执行各种操作。


相关链接资源

  • github : https://github.com/replicate/replicate-python
  • 官网:https://replicate.com
  • 官方文档:https://replicate.com/docs
  • 训练API文档:https://replicate.com/docs/fine-tuning
  • Webhooks文档:https://replicate.com/docs/webhooks
  • 流式输出文档:https://replicate.com/docs/streaming
  • Colab教程:https://colab.research.google.com/drive/1K91q4p-OhL96FHBAVLsv9FlwFdu6Pn3c

关键功能特性

  • 运行模型预测
  • 流式输出处理
  • 后台模型执行
  • 模型管道组合
  • 训练自定义模型
  • 预测管理(取消/列表)
  • 异步IO支持
  • Webhook集成

二、1.0.0 版本的重大变更

1.0.0 版本包含以下破坏性变更:

  • 对于输出文件的模型,replicate.run() 方法现在默认返回 FileOutput 对象而非 URL 字符串。FileOutput 实现了类似 httpx.Response 的可迭代接口,使文件处理更高效。

如需恢复旧行为,可通过传递 use_file_output=False 参数禁用 FileOutput

output = replicate.run("acmecorp/acme-model", use_file_output=False)

在大多数情况下,更新现有应用程序以调用 output.url 即可解决问题。

但我们建议直接使用 FileOutput 对象,因为我们计划对该 API 进行进一步改进,这种方法能确保获得最快的处理结果。

[!TIP]
👋 查看本教程的交互式版本:Google Colab

https://colab.research.google.com/drive/1K91q4p-OhL96FHBAVLsv9FlwFdu6Pn3c


三、安装与配置

1、系统要求

  • Python 3.8+

2、安装

pip install replicate

3、认证配置

在使用 API 运行任何 Python 脚本前,需设置环境变量中的 Replicate API 令牌。

从 replicate.com/account 获取令牌并设置为环境变量:

export REPLICATE_API_TOKEN=<your token>

我们建议不要直接将令牌添加到源代码中,因为您不希望将凭证提交到版本控制系统。如果任何人使用您的 API 密钥,其使用量将计入您的账户。


四、核心功能

1、运行模型

创建新的 Python 文件并添加以下代码,替换为您自己的模型标识符和输入:

>>> import replicate
>>> outputs = replicate.run(
        "black-forest-labs/flux-schnell",         input={"prompt": "astronaut riding a rocket like a horse"}
    )
[<replicate.helpers.FileOutput object at 0x107179b50>]
>>> for index, output in enumerate(outputs):
        with open(f"output_{index}.webp", "wb") as file:
            file.write(output.read())

如果预测失败,replicate.run 会抛出 ModelError 异常。您可以通过异常的 prediction 属性获取更多失败信息。

import replicate
from replicate.exceptions import ModelError

try:
  output = replicate.run("stability-ai/stable-diffusion-3", { "prompt": "An astronaut riding a rainbow unicorn" })
except ModelError as e
  if "(some known issue)" in e.prediction.logs:
    pass

  print("Failed prediction: " + e.prediction.id)

[!NOTE]
默认情况下,Replicate 客户端会保持连接打开最多 60 秒,等待预测完成。这种设计是为了优化模型输出返回客户端的速度。

可通过传递 wait=xreplicate.run() 来配置超时,其中 x 是 1 到 60 秒之间的超时值。要禁用同步模式,可传递 wait=False


2、异步IO支持

通过在方法名前添加 async_ 前缀,您也可以异步使用 Replicate 客户端。

以下是并发运行多个预测并等待它们全部完成的示例:

import asyncio
import replicate
 
# https://replicate.com/stability-ai/sdxl
model_version = "stability-ai/sdxl:39ed52f2a78e934b3ba6e2a89f5b1c712de7dfea535525255b1aa35c5565e08b"
prompts = [
    f"A chariot pulled by a team of {count} rainbow unicorns"
    for count in ["two", "four", "six", "eight"]
]

async with asyncio.TaskGroup() as tg:
    tasks = [
        tg.create_task(replicate.async_run(model_version, input={"prompt": prompt}))
        for prompt in prompts
    ]

results = await asyncio.gather(*tasks)
print(results)

对于需要文件输入的模型,您可以传递互联网上可公开访问文件的 URL,或本地设备上的文件句柄:

>>> output = replicate.run(
        "andreasjansson/blip-2:f677695e5e89f8b236e52ecd1d3f01beb44c34606419bcc19345e046d8f786f9",         input={ "image": open("path/to/mystery.jpg") }
    )

"an astronaut riding a horse"

3、流式输出模型

Replicate 的 API 支持语言模型的服务器发送事件流(SSEs)。使用 stream 方法可以实时消费模型生成的标记。

import replicate

for event in replicate.stream(
    "meta/meta-llama-3-70b-instruct",     input={
        "prompt": "Please write a haiku about llamas.",     }, ):
    print(str(event), end="")

[!TIP]
某些模型如 meta/meta-llama-3-70b-instruct 不需要版本字符串。您始终可以参考模型页面上的 API 文档了解具体细节。


您也可以流式传输已创建预测的输出。这在您希望将预测 ID 与其输出分开时很有用。

prediction = replicate.predictions.create(
    model="meta/meta-llama-3-70b-instruct",     input={"prompt": "Please write a haiku about llamas."},     stream=True, )

for event in prediction.stream():
    print(str(event), end="")

更多信息请参阅 Replicate 文档中的"流式输出"。


4、后台运行模型

您可以使用异步模式在后台启动并运行模型:

>>> model = replicate.models.get("kvfrans/clipdraw")
>>> version = model.versions.get("5797a99edc939ea0e9242d5e8c9cb3bc7d125b1eac21bda852e5cb79ede2cd9b")
>>> prediction = replicate.predictions.create(
    version=version,     input={"prompt":"Watercolor painting of an underwater submarine"})

>>> prediction
Prediction(...)

>>> prediction.status
'starting'

>>> dict(prediction)
{"id": "...", "status": "starting", ...}

>>> prediction.reload()
>>> prediction.status
'processing'

>>> print(prediction.logs)
iteration: 0, render:loss: -0.6171875
iteration: 10, render:loss: -0.92236328125
iteration: 20, render:loss: -1.197265625
iteration: 30, render:loss: -1.3994140625

>>> prediction.wait()

>>> prediction.status
'succeeded'

>>> prediction.output
<replicate.helpers.FileOutput object at 0x107179b50>

>>> with open("output.png", "wb") as file:
        file.write(prediction.output.read())

5、后台运行模型并获取Webhook

您可以运行模型并在完成时获取 webhook,而不是等待它完成:

model = replicate.models.get("ai-forever/kandinsky-2.2")
version = model.versions.get("ea1addaab376f4dc227f5368bbd8eff901820fd1cc14ed8cad63b29249e9d463")
prediction = replicate.predictions.create(
    version=version,     input={"prompt":"Watercolor painting of an underwater submarine"},     webhook="https://example.com/your-webhook",     webhook_events_filter=["completed"]
)

有关接收 webhook 的详细信息,请参阅 replicate.com/docs/webhooks。


6、组合模型管道

您可以运行一个模型并将其输出作为另一个模型的输入:

laionide = replicate.models.get("afiaka87/laionide-v4").versions.get("b21cbe271e65c1718f2999b038c18b45e21e4fba961181fbfae9342fc53b9e05")
swinir = replicate.models.get("jingyunliang/swinir").versions.get("660d922d33153019e8c263a3bba265de882e7f4f70396546b6c9c8f9d47a021a")
image = laionide.predict(prompt="avocado armchair")
upscaled_image = swinir.predict(image=image)

7、获取运行中模型的输出

在模型运行时获取其输出:

iterator = replicate.run(
    "pixray/text2image:5c347a4bfa1d4523a58ae614c2194e15f2ae682b57e3797a5bb468920aa70ebf",     input={"prompts": "san francisco sunset"}
)

for index, image in enumerate(iterator):
    with open(f"file_{index}.png", "wb") as file:
        file.write(image.read())

8、取消预测

您可以取消正在运行的预测:

>>> model = replicate.models.get("kvfrans/clipdraw")
>>> version = model.versions.get("5797a99edc939ea0e9242d5e8c9cb3bc7d125b1eac21bda852e5cb79ede2cd9b")
>>> prediction = replicate.predictions.create(
        version=version,         input={"prompt":"Watercolor painting of an underwater submarine"}
    )

>>> prediction.status
'starting'

>>> prediction.cancel()

>>> prediction.reload()
>>> prediction.status
'canceled'

9、列出预测

您可以列出所有运行过的预测:

replicate.predictions.list()
# [<Prediction: 8b0ba5ab4d85>, <Prediction: 494900564e8c>]

预测列表是分页的。您可以通过将 next 属性作为参数传递给 list 方法来获取下一页预测:

page1 = replicate.predictions.list()

if page1.next:
    page2 = replicate.predictions.list(page1.next)

10、加载输出文件

输出文件作为 FileOutput 对象返回:

import replicate
from PIL import Image # pip install pillow

output = replicate.run(
    "stability-ai/stable-diffusion:27b93a2413e7f36cd83da926f3656280b2931564ff050bf9575f1fdf9bcd7478",     input={"prompt": "wavy colorful abstract patterns, oceans"}
    )

# 具有返回二进制数据的.read()方法
with open("my_output.png", "wb") as file:
  file.write(output[0].read())
  
# 也实现了迭代器协议以流式传输数据
background = Image.open(output[0])

FileOutput 对象

FileOutput 是从 replicate.run() 方法返回的类文件对象,使处理输出文件的模型更容易使用。它实现了 IteratorAsyncIterator 用于分块读取文件数据,以及 read()aread() 方法将整个文件读入内存。

[!NOTE]
值得注意的是,目前 read()aread() 不接受 size 参数来读取最多 size 字节。

最后,底层数据源的 URL 可通过 url 属性获得,但我们建议您将对象用作迭代器或使用其 read()aread() 方法,因为 url 属性在未来可能不总是返回 HTTP URL。

print(output.url) #=> "data:image/png;base64,xyz123..." or "https://delivery.replicate.com/..."

要直接消费文件:

with open('output.bin', 'wb') as file:
    file.write(output.read())

对于非常大的文件,可以流式传输:

with open(file_path, 'wb') as file:
    for chunk in output:
        file.write(chunk)

每种方法都有对应的 asyncio API:

async with aiofiles.open(filename, 'w') as file:
    await file.write(await output.aread())

async with aiofiles.open(filename, 'w') as file:
    await for chunk in output:
        await file.write(chunk)

对于来自常见框架的流式响应,都支持接受 Iterator 类型:

Django

@condition(etag_func=None)
def stream_response(request):
    output = replicate.run("black-forest-labs/flux-schnell", input={...}, use_file_output =True)
    return HttpResponse(output, content_type='image/webp')

FastAPI

@app.get("/")
async def main():
    output = replicate.run("black-forest-labs/flux-schnell", input={...}, use_file_output =True)
    return StreamingResponse(output)

Flask

@app.route('/stream')
def streamed_response():
    output = replicate.run("black-forest-labs/flux-schnell", input={...}, use_file_output =True)
    return app.response_class(stream_with_context(output))

您可以通过向 replicate.run() 方法传递 use_file_output=False 来禁用 FileOutput

const replicate = replicate.run("acmecorp/acme-model", use_file_output=False);

11、列出模型

您可以列出您创建的模型:

replicate.models.list()

模型列表是分页的。您可以通过将 next 属性作为参数传递给 list 方法来获取下一页模型,或者使用 paginate 方法自动获取页面。

# 使用 `replicate.paginate` 自动分页(推荐)
models = []
for page in replicate.paginate(replicate.models.list):
    models.extend(page.results)
    if len(models) > 100:
        break

# 使用 `next` 游标手动分页
page = replicate.models.list()
while page:
    models.extend(page.results)
    if len(models) > 100:
          break
    page = replicate.models.list(page.next) if page.next else None

您还可以在 Replicate 上找到精选模型集合:

>>> collections = [collection for page in replicate.paginate(replicate.collections.list) for collection in page]
>>> collections[0].slug
"vision-models"
>>> collections[0].description
"Multimodal large language models with vision capabilities like object detection and optical character recognition (OCR)"

>>> replicate.collections.get("text-to-image").models
[<Model: stability-ai/sdxl>, ...]

12、创建模型

您可以为用户或组织创建具有给定名称、可见性和硬件 SKU 的模型:

import replicate

model = replicate.models.create(
    owner="your-username",     name="my-model",     visibility="public",     hardware="gpu-a40-large"
)

以下是列出 Replicate 上可用于运行模型的所有可用硬件的方法:

>>> [hw.sku for hw in replicate.hardware.list()]
['cpu', 'gpu-t4', 'gpu-a40-small', 'gpu-a40-large']

13、微调模型

使用训练API微调模型,使其在特定任务上表现更好。要查看当前支持微调的语言模型,请查看 Replicate 的可训练语言模型集合。

如果您想微调图像模型,请查看 Replicate 的图像模型微调指南。

以下是在 Replicate 上微调模型的方法:

training = replicate.trainings.create(
    model="stability-ai/sdxl",     version="39ed52f2a78e934b3ba6e2a89f5b1c712de7dfea535525255b1aa35c5565e08b",     input={
      "input_images": "https://my-domain/training-images.zip",       "token_string": "TOK",       "caption_prefix": "a photo of TOK",       "max_train_steps": 1000,       "use_face_detection_instead": False
    },     # 您需要在 Replicate 上创建一个模型作为训练版本的接收方
    destination="your-username/model-name"
)

14、自定义客户端行为

replicate 包导出一个默认的共享客户端。此客户端使用 REPLICATE_API_TOKEN 环境变量设置的 API 令牌初始化。

您可以创建自己的客户端实例以传递不同的 API 令牌值,向请求添加自定义标头,或控制底层 HTTPX 客户端的行为:

import os
from replicate.client import Client

replicate = Client(
    api_token=os.environ["SOME_OTHER_REPLICATE_API_TOKEN"]
    headers={
        "User-Agent": "my-app/1.0"
    }
)

[!WARNING]
切勿将 API 令牌等认证凭证硬编码到代码中。
相反,在运行程序时将它们作为环境变量传递。


五、开发

参见 CONTRIBUTING.md


伊织 xAI 2024-04-19(六)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2338551.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

deekseak 本地windows 10 部署步骤

有些场景需要本地部署&#xff0c;例如金融、医疗&#xff08;HIPAA&#xff09;、政府&#xff08;GDPR&#xff09;、军工等&#xff0c;需完全控制数据存储和访问权限&#xff0c;避免云端合规风险或者偏远地区、船舶、矿井等无法依赖云服务&#xff0c;关键设施&#xff08…

<sql>、<resultMap>、<where>、<foreach>、<trim>、<set>等标签的作用和用法

目录 一. sql 代码片段标签 二. resultMap 映射结果集标签 三. where 条件标签 四. set 修改标签 五. trim 标签 六. foreach 循环标签 一. sql 代码片段标签 sql 标签是 mybatis 框架中一个非常常用的标签页&#xff0c;特别是当一张表很有多个字段多&#xff0c;或者要…

【项目】CherrySudio配置MCP服务器

CherrySudio配置MCP服务器 &#xff08;一&#xff09;Cherry Studio介绍&#xff08;二&#xff09;MCP服务环境搭建&#xff08;1&#xff09;环境准备&#xff08;2&#xff09;依赖组件安装<1> Bun和UV安装 &#xff08;3&#xff09;MCP服务器使用<1> 搜索MCP…

【技术派后端篇】 Redis 实现用户活跃度排行榜

在各类互联网应用中&#xff0c;排行榜是一个常见的功能需求&#xff0c;它能够直观地展示用户的表现或贡献情况&#xff0c;提升用户的参与感和竞争意识。在技术派项目中&#xff0c;也引入了用户活跃度排行榜&#xff0c;该排行榜主要基于 Redis 的 ZSET 数据结构来实现。接下…

模拟算法(一)作业分析及答案

目录 作业1&#xff1a;角谷猜想 解题思路 &#xff1a; 代码实现&#xff1a; 作业2&#xff1a;校门外的树 解题思路 注意事项 代码实现 作业3&#xff1a;乒乓球 ​编辑 问题重述 解题思路&#xff1a; 作业1&#xff1a;角谷猜想 【描述】 所谓角谷猜想&#xf…

西红柿番茄检测数据集VOC+YOLO格式2320张1类别可用于计数

数据集格式&#xff1a;Pascal VOC格式YOLO格式(不包含分割路径的txt文件&#xff0c;仅仅包含jpg图片以及对应的VOC格式xml文件和yolo格式txt文件) 图片数量(jpg文件个数)&#xff1a;2320 标注数量(xml文件个数)&#xff1a;2320 标注数量(txt文件个数)&#xff1a;2320 …

专题十六:虚拟路由冗余协议——VRRP

一、VRRP简介 VRRP&#xff08;Virtual Router Redundancy Protocol&#xff09;虚拟路由冗余协议通过把几台设备联合组成一台虚拟的设备&#xff0c;使用一定的机制保证当主机的下一跳设备出现故障时&#xff0c;及时将业务切换到备份设备&#xff0c;从而保持通讯的连续性和…

DDPM(diffusion)原理

DDPM&#xff08;diffusion&#xff09;原理 1、DDPM&#xff08;原理&#xff09;2、DDPM和 Conditional DDPM&#xff08;原理解释&#xff09;2.1. Diffusion Models 原理详解核心思想前向扩散过程&#xff08;Forward Diffusion&#xff09;反向去噪过程&#xff08;Revers…

《软件设计师》复习笔记(2.2)——效验码、体系结构、指令、流水线

目录 一、校验码 码距 奇偶校验码 循环冗余校验码&#xff08;CRC&#xff09; 海明码 真题示例&#xff1a; 二、体系结构 Flynn分类法 三、指令系统 指令组成 指令执行过程 指令的寻址方式 操作数的寻址方式 CISC vs RISC 真题示例&#xff1a; 四、流水线技…

IsaacSim Asserts 配置

IsaacSim Asserts 配置 背景解决方案资源准备具体操作步骤验证 背景 我是习惯使用 isaacsim 的 standalone 模式&#xff0c;使用 python 脚本直接运行 script&#xff0c;然后弹窗&#xff0c;按照规则正确运行即可&#xff0c;但是&#xff0c;这就导致了一些问题出现&#…

接口自动化 ——fixture allure

一.参数化实现数据驱动 上一篇介绍了参数化&#xff0c;这篇 说说用参数化实现数据驱动。在有很多测试用例的时候&#xff0c;可以将测试用例都存储在文件里&#xff0c;进行读写调用。本篇主要介绍 csv 文件和 json 文件。 1.读取 csv 文件数据 首先创建 csv 文件&#xff…

systemctl管理指令

今天我们来继续学习服务管理指令,接下来才是重头戏-systemctl,那么话不多说,直接开始吧. systemctl管理指令 1.基本语法: systemctl [start | stop | restart | status]服务 注&#xff1a;systemctl指令管理的服务在/usr/lib/ systemd/system查看 2.systemctl设置服务的自…

【文件操作与IO】详细解析文件操作与IO (二)

本篇博客是上一篇文章的续写,重点介绍数据流,还包括三道练习题. &#x1f40e;文章专栏: JavaEE初阶 &#x1f680;若有问题 评论区见 ❤ 欢迎大家点赞 评论 收藏 分享 如果你不知道分享给谁,那就分享给薯条. 你们的支持是我不断创作的动力 . 王子,公主请阅&#x1f680; 要开心…

go-map+sync.map的底层原理

map 哈希冲突解决方式 1.拉链法 2.开放地址法 底层结构 Go 的 map 在源码中由 runtime.hmap 结构体表示&#xff0c;buckets-指向桶数组的指针(常规桶)&#xff0c;oldbuckets-扩容时指向旧桶数组的指针。 type hmap struct {count int // 当前元素个数&#xff08;len…

Day53 二叉树的层序遍历

给你二叉树的根节点 root &#xff0c;返回其节点值的 层序遍历 。 &#xff08;即逐层地&#xff0c;从左到右访问所有节点&#xff09;。 /*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* T…

物联网智慧教室项目(完整版)

物联网智慧教室项目(一)&#xff1a;智慧教室项目解决方案 一、智慧教室项目设计 &#xff08;一&#xff09;环境信息采集控制功能 1、硬件设计 使用STM32开发板模拟灯光控制&#xff0c;报警控制&#xff0c;光照信息采集&#xff1a; 灯光控制通过GPIO控制板载LED报警控…

计算机网络期中复习笔记(自用)

复习大纲 –第一章 概述 计算机网络的组成 网络边缘&#xff1a;主机和网络应用程序&#xff08;又称为“端系统”&#xff09; 端系统中运行的程序之间的通信方式可划分为两大类&#xff1a; 客户/服务器方式&#xff08;C/S方式&#xff09; 对等方式&#xff08;P2P方式…

14.Chromium指纹浏览器开发教程之WebGL指纹定制

WebGL指纹概述 当在浏览器打开的网页上浏览内容时&#xff0c;看到的大多是平面的、静态的图像和文字。但是有时想要在网页上看到更加生动、立体的图像&#xff0c;如3D游戏、虚拟现实应用等。这时&#xff0c;就需要用到WebGL。 简单来说&#xff0c;WebGL&#xff08;Web G…

GitHub SSH连接终极解决方案

GitHub SSH连接终极解决方案&#xff1a;443端口修改多场景故障排查指南 一、问题现象速查 当开发者执行以下命令时出现连接异常&#xff1a; ssh -T gitgithub.com常见报错类型&#xff1a; 经典端口阻塞ssh: connect to host github.com port 22: Connection refused密钥验…

每日算法【双指针算法】(Day 1-移动零)

双指针算法 1.算法题目&#xff08;移动零&#xff09;2.讲解算法原理3.编写代码 1.算法题目&#xff08;移动零&#xff09; 2.讲解算法原理 数组划分&#xff0c;数组分块&#xff08;快排里面最核心的一步&#xff09;只需把0改为tmp 双指针算法&#xff1a;利用数组下标来…