成为 10x AI 工程师的 15 个隐藏开源瑰宝🧙♂️🪄
人工智能风靡一时,各种炒作铺天盖地。有人说它会(以一种错误的方式)改变我们已知的世界,也有人说这只是一时的热潮。
然而,正如埃隆·马斯克所说,“最有趣的结果是最有可能的。”
人工智能不会毁灭我们所有人,它也不是一时的潮流。相反,它将推动我们的生产力,构建更复杂的系统,或许可以用于太空旅行、寻找新材料(还记得LK-99吗?),以及治愈不治之症。
然而,为了实现这些目标,我们现在能做的最好的事情就是加快我们的方式的进步,而人工智能工程师将在其中发挥至关重要的作用。
人工智能工程是一个跨学科领域,包括:
- 训练和微调模型。
- 收集、清理和预处理数据。
- 构建用于复杂任务自动化的 AI 系统(AI 代理、RAG 等)。
- 将模型安全地部署到生产中。
- 持续监测和评估人工智能系统。
我一直在围绕它进行大量的构建和研究。因此,我准备了一份开源软件清单,希望它们能帮助你成为更优秀的 AI 工程师。
点击下面的表情符号即可访问相应部分。👇
- Composio:构建 AI 自动化速度提高 10 倍。🚀
- Unsloth:更快地训练和微调 AI 模型。🦥💨
- DsPy:LLM 编程框架。🛠️
- LLMware:用于构建企业 RAG 的框架。🏢
- TaiPy:使用 Python 更快地构建 AI Web 应用程序。🐍💻
- LanceDB:面向 AI 应用的向量知识库。📚
- Phidata:构建具有记忆功能的 LLM 代理。🧠
- Phoenix:LLM 可观察性更加高效。🔥
- Airbyte:可靠且可扩展的数据管道。🌬️
- AgentOps:代理监控和可观察性。👁️
- RAGAS:RAG 评估框架。📊
- BentoML:为 AI 应用和模型提供服务的最简单方法。🍱
- LoRAX :多 LoRA 推理服务器,可扩展至数千个经过微调的 LLM。📡
- 网关:使用单个 API 可靠地路由到 200 个 LLM。🌐
- LitServe:适用于 AI 模型的灵活、高吞吐量服务引擎。💫
欢迎随意探索并为存储库做出贡献。
1. Composio 👑:构建 AI 自动化速度提高 10 倍 🚀
工具和集成构成了构建 AI 代理的核心。
我一直在构建 AI 工具和代理,但工具准确性一直是个问题,直到我遇到 Composio。
Composio 使 GitHub、Slack、Jira、Airtable 等流行应用程序与 AI 代理的集成变得更加容易,从而可以构建复杂的自动化。
它代表您的用户处理集成的用户身份验证和授权。因此,您可以安心构建 AI 应用程序。并且它已获得 SOC2 认证。
那么,您可以按照以下方法开始使用它。
Python
pip install composio-core
添加 GitHub 集成。
composio add github
Composio 代表您处理用户身份验证和授权。
以下是如何使用 GitHub 集成来为存储库加注星标的方法。
from openai import OpenAI
from composio_openai import ComposioToolSet, App
openai_client = OpenAI(api_key="******OPENAIKEY******")
# Initialise the Composio Tool Set
composio_toolset = ComposioToolSet(api_key="**\\*\\***COMPOSIO_API_KEY**\\*\\***")
## Step 4
# Get GitHub tools that are pre-configured
actions = composio_toolset.get_actions(actions=[Action.GITHUB_ACTIVITY_STAR_REPO_FOR_AUTHENTICATED_USER])
## Step 5
my_task = "Star a repo ComposioHQ/composio on GitHub"
# Create a chat completion request to decide on the action
response = openai_client.chat.completions.create(
model="gpt-4-turbo",
tools=actions, # Passing actions we fetched earlier.
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": my_task}
]
)
运行此 Python 脚本以使用代理执行给定的指令。
JavaScript
您可以使用 npm
、、 yarn
或来 安装它pnpm
。
npm install composio-core
定义一种方法让用户连接他们的 GitHub 帐户。
import { OpenAI } from "openai";
import { OpenAIToolSet } from "composio-core";
const toolset = new OpenAIToolSet({
apiKey: process.env.COMPOSIO_API_KEY,
});
async function setupUserConnectionIfNotExists(entityId) {
const entity = await toolset.client.getEntity(entityId);
const connection = await entity.getConnection('github');
if (!connection) {
// If this entity/user hasn't already connected, the account
const connection = await entity.initiateConnection(appName);
console.log("Log in via: ", connection.redirectUrl);
return connection.waitUntilActive(60);
}
return connection;
}
将所需的工具添加到 OpenAI SDK 并将实体名称传递给 executeAgent
函数。
async function executeAgent(entityName) {
const entity = await toolset.client.getEntity(entityName)
await setupUserConnectionIfNotExists(entity.id);
const tools = await toolset.get_actions({ actions: ["github_activity_star_repo_for_authenticated_user"] }, entity.id);
const instruction = "Star a repo ComposioHQ/composio on GitHub"
const client = new OpenAI({ apiKey: process.env.OPEN_AI_API_KEY })
const response = await client.chat.completions.create({
model: "gpt-4-turbo",
messages: [{
role: "user",
content: instruction,
}],
tools: tools,
tool_choice: "auto",
})
console.log(response.choices[0].message.tool_calls);
await toolset.handle_tool_call(response, entity.id);
}
executeGithubAgent("joey")
执行代码并让代理为您完成工作。
Composio 与 LangChain、LlamaIndex、CrewAi 等著名框架兼容。
欲了解更多信息,请访问官方 文档,欲查看更复杂的示例,请参阅存储库的 示例 部分。
2. Unsloth:更快地训练和微调 AI 模型🦥💨
训练和微调大型语言模型 (LLM) 是人工智能工程的关键部分。
很多情况下,专有模型可能无法满足需求。原因可能是成本、个性化或隐私问题。有时,你需要在自定义数据集上对模型进行微调。目前,Unsloth 是用于微调和训练 LLM 的最佳库之一。
它支持流行 LLM(包括 Llama-3 和 Mistral)及其衍生产品(如 Yi、Open-hermes 等)的完整版、LoRA 和 QLoRA 微调。它实现了自定义 triton 内核和手动反向传播引擎,以提高模型训练的速度。
要开始使用 Unsloth,请使用 安装它pip
并确保您拥有torch 2.4
和 CUDA 12.1
。
pip install --upgrade pip
pip install "unsloth[cu121-torch240] @ git+https://github.com/unslothai/unsloth.git"
这是一个使用 SFT(监督微调)在数据集上训练 Mistral 模型的简单脚本
from unsloth import FastLanguageModel
from unsloth import is_bfloat16_supported
import torch
from trl import SFTTrainer
from transformers import TrainingArguments
from datasets import load_dataset
max_seq_length = 2048 # Supports RoPE Scaling internally, so choose any!
# Get LAION dataset
url = "https://huggingface.co/datasets/laion/OIG/resolve/main/unified_chip2.jsonl"
dataset = load_dataset("json", data_files = {"train" : url}, split = "train")
# 4bit pre quantized models we support for 4x faster downloading + no OOMs.
fourbit_models = [
"unsloth/mistral-7b-v0.3-bnb-4bit", # New Mistral v3 2x faster!
] # More models at https://huggingface.co/unsloth
model, tokenizer = FastLanguageModel.from_pretrained(
model_name = "unsloth/llama-3-8b-bnb-4bit",
max_seq_length = max_seq_length,
dtype = None,
load_in_4bit = True,
)
# Do model patching and add fast LoRA weights
model = FastLanguageModel.get_peft_model(
model,
r = 16,
target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj",],
lora_alpha = 16,
lora_dropout = 0, # Supports any, but = 0 is optimized
bias = "none", # Supports any, but = "none" is optimized
# [NEW] "unsloth" uses 30% less VRAM, fits 2x larger batch sizes!
use_gradient_checkpointing = "unsloth", # True or "unsloth" for very long context
random_state = 3407,
max_seq_length = max_seq_length,
use_rslora = False, # We support rank stabilized LoRA
loftq_config = None, # And LoftQ
)
trainer = SFTTrainer(
model = model,
train_dataset = dataset,
dataset_text_field = "text",
max_seq_length = max_seq_length,
tokenizer = tokenizer,
args = TrainingArguments(
per_device_train_batch_size = 2,
gradient_accumulation_steps = 4,
warmup_steps = 10,
max_steps = 60,
fp16 = not is_bfloat16_supported(),
bf16 = is_bfloat16_supported(),
logging_steps = 1,
output_dir = "outputs",
optim = "adamw_8bit",
seed = 3407,
),
)
trainer.train()
更多信息请参考官方文档。
3. DsPy:LLM 编程框架
阻碍 LLM 在生产用例中使用的一个因素是其随机性。对于这些用例来说,促使它们输出所需的响应失败率很高。
DsPy 正在解决这个问题。它不是提示,而是对 LLM 进行编程,以获得最高的可靠性。
DSPy 通过做两件关键的事情来简化这一过程:
- 将程序流程与参数分离: 此功能将程序流程(您执行的步骤)与每个步骤的具体执行细节(LM 提示和权重)分离。这使得您的系统管理和更新更加便捷。
- 引入新的优化器: DSPy 使用先进的算法,根据您的目标自动微调 LM 提示和权重,例如提高准确性或减少错误。
查看此 入门笔记本, 了解有关如何使用 DsPy 的更多信息。
4. LLMware:构建企业 RAG 的框架
在开发企业软件时,隐私、安全和可靠性至关重要。如果您正在寻找构建企业 AI 应用程序的框架,LLMWare 是您的首选。
它们提供了一个统一的框架,使用微小的、专门的模型来构建基于 LLM 的应用程序(例如 RAG、Agents),这些模型可以私下部署、安全地与企业知识源集成,并且可以经济高效地调整和适应任何业务流程。
LLMWare 有两个主要组件:
- RAG 管道 ——将知识源与生成 AI 模型连接起来的集成组件。
- 50 多个小型、专用模型 针对企业流程自动化中的关键任务进行了微调,包括基于事实的问答、分类、总结和提取。
使用以下方式设置 LLMwarepip
pip3 install llmware
以下是创建和使用数据集的方法。
""" This example demonstrates creating and using datasets
1. Datasets suitable for fine-tuning embedding models
2. Completion and other types of datasets
3. Generating datasets from all data in a library or with filtered data
4. Creating datasets from AWS Transcribe transcripts
"""
import json
import os
from llmware.dataset_tools import Datasets
from llmware.library import Library
from llmware.retrieval import Query
from llmware.setup import Setup
from llmware.configs import LLMWareConfig
def build_and_use_dataset(library_name):
# Setup a library and build a knowledge graph. Datasets will use the data in the knowledge graph
print (f"\n > Creating library {library_name}...")
library = Library().create_new_library(library_name)
sample_files_path = Setup().load_sample_files()
library.add_files(os.path.join(sample_files_path,"SmallLibrary"))
library.generate_knowledge_graph()
# Create a Datasets object from library
datasets = Datasets(library)
# Build a basic dataset useful for industry domain adaptation for fine-tuning embedding models
print (f"\n > Building basic text dataset...")
basic_embedding_dataset = datasets.build_text_ds(min_tokens=500, max_tokens=1000)
dataset_location = os.path.join(library.dataset_path, basic_embedding_dataset["ds_id"])
print (f"\n > Dataset:")
print (f"(Files referenced below are found in {dataset_location})")
print (f"\n{json.dumps(basic_embedding_dataset, indent=2)}")
sample = datasets.get_dataset_sample(datasets.current_ds_name)
print (f"\nRandom sample from the dataset:\n{json.dumps(sample, indent=2)}")
# Other Dataset Generation and Usage Examples:
# Build a simple self-supervised generative dataset- extracts text and splits into 'text' & 'completion'
# Several generative "prompt_wrappers" are available - chat_gpt | alpaca |
basic_generative_completion_dataset = datasets.build_gen_ds_targeted_text_completion(prompt_wrapper="alpaca")
# Build a generative self-supervised training set by pairing 'header_text' with 'text.'
xsum_generative_completion_dataset = datasets.build_gen_ds_headline_text_xsum(prompt_wrapper="human_bot")
topic_prompter_dataset = datasets.build_gen_ds_headline_topic_prompter(prompt_wrapper="chat_gpt")
# Filter a library by a key term as part of building the dataset
filtered_dataset = datasets.build_text_ds(query="agreement", filter_dict={"master_index":1})
# Pass a set of query results to create a dataset from those results only
query_results = Query(library=library).query("africa")
query_filtered_dataset = datasets.build_text_ds(min_tokens=250,max_tokens=600, qr=query_results)
return 0
if __name__ == "__main__":
LLMWareConfig().set_active_db("sqlite")
build_and_use_dataset("test_txt_datasets_0")
探索如何使用 LLMWare 的示例。更多信息,请参阅文档。
5. TaiPy:使用 Python 更快地构建 AI Web 应用程序。🐍💻
Taipy 是一款基于 Python 的开源软件,旨在在生产环境中构建 AI Web 应用。它增强了 Streamlit 和 Gradio 的功能,使 Python 开发者能够在生产环境中部署演示应用。
Taipy 专为数据科学家和机器学习工程师构建数据和人工智能网络应用程序而设计。
- 支持构建可用于生产的 Web 应用程序
- 无需学习新语言。只需要 Python。
- 专注于数据和人工智能算法,无需开发和部署复杂性。
快速开始使用它 pip
。
pip install taipy
这个简单的 Taipy 应用程序演示了如何使用 Taipy 创建一个基本的电影推荐系统。
import taipy as tp
import pandas as pd
from taipy import Config, Scope, Gui
# Defining the helper functions
# Callback definition - submits scenario with genre selection
def on_genre_selected(state):
scenario.selected_genre_node.write(state.selected_genre)
tp.submit(scenario)
state.df = scenario.filtered_data.read()
## Set initial value to Action
def on_init(state):
on_genre_selected(state)
# Filtering function - task
def filter_genre(initial_dataset: pd.DataFrame, selected_genre):
filtered_dataset = initial_dataset[initial_dataset["genres"].str.contains(selected_genre)]
filtered_data = filtered_dataset.nlargest(7, "Popularity %")
return filtered_data
# The main script
if __name__ == "__main__":
# Taipy Scenario & Data Management
# Load the configuration made with Taipy Studio
Config.load("config.toml")
scenario_cfg = Config.scenarios["scenario"]
# Start Taipy Core service
tp.Core().run()
# Create a scenario
scenario = tp.create_scenario(scenario_cfg)
# Taipy User Interface
# Let's add a GUI to our Scenario Management for a complete application
# Get list of genres
genres = [
"Action", "Adventure", "Animation", "Children", "Comedy", "Fantasy", "IMAX"
"Romance","Sci-FI", "Western", "Crime", "Mystery", "Drama", "Horror", "Thriller", "Film-Noir","War", "Musical", "Documentary"
]
# Initialization of variables
df = pd.DataFrame(columns=["Title", "Popularity %"])
selected_genre = "Action"
# User interface definition
my_page = """
# Film recommendation
## Choose your favorite genre
<|{selected_genre}|selector|lov={genres}|on_change=on_genre_selected|dropdown|>
## Here are the top seven picks by popularity
<|{df}|chart|x=Title|y=Popularity %|type=bar|title=Film Popularity|>
"""
Gui(page=my_page).run()
查看 文档 以了解更多信息。
6. LanceDB:面向 AI 应用的向量知识库。📚
如果您正在构建 AI 应用程序,则需要一个矢量数据库来存储和检索文本、图像和视频等结构化数据。与传统数据库不同,矢量数据库存储这些数据的嵌入。
嵌入是数据的高维数值表示。向量数据库使用相似度得分等方法来检索相关数据。
LanceDb 是一个用 Typescript 编写的开源矢量数据库。它提供生产级矢量搜索、多模式支持、零拷贝、自动数据版本控制、GPU 驱动的查询等功能。
开始使用 LanceDB。
npm install @lancedb/lancedb
创建并查询矢量数据库。
import * as lancedb from "@lancedb/lancedb";
const db = await lancedb.connect("data/sample-lancedb");
const table = await db.createTable("vectors", [
{ id: 1, vector: [0.1, 0.2], item: "foo", price: 10 },
{ id: 2, vector: [1.1, 1.2], item: "bar", price: 50 },
], {mode: 'overwrite'});
const query = table.vectorSearch([0.1, 0.3]).limit(2);
const results = await query.toArray();
// You can also search for rows by specific criteria without involving a vector search.
const rowsByCriteria = await table.query().where("price >= 10").toArray();
您可以在此处的文档中找到有关 LanceDB 的更多信息 。
7. Phidata:构建具有记忆功能的 LLM 代理。🧠
构建有效的代理通常并不像听起来那么容易。管理内存、缓存和工具执行可能会非常具有挑战性。
Phidata 是一个开源框架,它提供了一种方便可靠的方法来构建具有长期记忆、上下文知识和使用函数调用采取行动的能力的代理。
通过安装开始使用 Phidatapip
pip install -U phidata
让我们创建一个可以查询财务数据的简单助手。
from phi.assistant import Assistant
from phi.llm.openai import OpenAIChat
from phi.tools.yfinance import YFinanceTools
assistant = Assistant(
llm=OpenAIChat(model="gpt-4o"),
tools=[YFinanceTools(stock_price=True, analyst_recommendations=True, company_info=True, company_news=True)],
show_tool_calls=True,
markdown=True,
)
assistant.print_response("What is the stock price of NVDA")
assistant.print_response("Write a comparison between NVDA and AMD, use all tools available.")
一个可以上网的助手。
from phi.assistant import Assistant
from phi.tools.duckduckgo import DuckDuckGo
assistant = Assistant(tools=[DuckDuckGo()], show_tool_calls=True)
assistant.print_response("Whats happening in France?", markdown=True)
有关示例和信息,请参阅官方文档。
8. Phoenix:LLM 可观测性更加高效。🔥
只有添加可观察层,才能构建完整的 AI 应用程序。通常,LLM 应用程序包含许多可变部分,例如提示、模型温度、p 值等,即使细微的变化也会对结果产生重大影响。
这会使应用程序极不稳定且不可靠。这正是 LLM 可观察性发挥作用的地方。ArizeAI 的 Phoneix 可以方便地追踪 LLM 执行的整个过程。
它是一个开源的 AI 可观察性平台,专为实验、评估和故障排除而设计。它提供:
- 跟踪 - 使用基于 OpenTelemetry 的仪器跟踪 LLM 应用程序的运行时。
- 评估 - 利用 LLM 通过响应和检索评估来对应用程序的性能进行基准测试。
- 数据集 ——创建用于实验、评估和微调的示例版本数据集。
- 实验 ——跟踪和评估提示、LLM 和检索变化。
Phoenix 与供应商和语言无关,支持 LlamaIndex、LangChain、DSPy 等框架以及 OpenAI 和 Bedrock 等 LLM 提供商。
它可以在各种环境中运行,包括 Jupyter 笔记本、本地机器、容器或云。
使用 Phoneix 很容易上手。
pip install arize-phoenix
首先,启动 Phoenix 应用程序。
import phoenix as px
session = px.launch_app()
这将启动 Phoneix 服务器。
您现在可以为您的 AI 应用程序设置跟踪,以便在跟踪流入时调试您的应用程序。
要使用 LlamaIndex 的一键功能,您必须先安装小型集成:
pip install 'llama-index>=0.10.44'
import phoenix as px
from openinference.instrumentation.llama_index import LlamaIndexInstrumentor
import os
from gcsfs import GCSFileSystem
from llama_index.core import (
Settings,
VectorStoreIndex,
StorageContext,
set_global_handler,
load_index_from_storage
)
from llama_index.embeddings.openai import OpenAIEmbedding
from llama_index.llms.openai import OpenAI
import llama_index
# To view traces in Phoenix, you will first have to start a Phoenix server. You can do this by running the following:
session = px.launch_app()
# Initialize LlamaIndex auto-instrumentation
LlamaIndexInstrumentor().instrument()
os.environ["OPENAI_API_KEY"] = "<ENTER_YOUR_OPENAI_API_KEY_HERE>"
# LlamaIndex application initialization may vary
# depending on your application
Settings.llm = OpenAI(model="gpt-4-turbo-preview")
Settings.embed_model = OpenAIEmbedding(model="text-embedding-ada-002")
# Load your data and create an index. Here we've provided an example of our documentation
file_system = GCSFileSystem(project="public-assets-275721")
index_path = "arize-phoenix-assets/datasets/unstructured/llm/llama-index/arize-docs/index/"
storage_context = StorageContext.from_defaults(
fs=file_system,
persist_dir=index_path,
)
index = load_index_from_storage(storage_context)
query_engine = index.as_query_engine()
# Query your LlamaIndex application
query_engine.query("What is the meaning of life?")
query_engine.query("How can I deploy Arize?")
# View the traces in the Phoenix UI
px.active_session().url
一旦您为应用程序执行了足够数量的查询(或聊天),您就可以通过刷新浏览器 URL 来查看 UI 的详细信息。
请参阅他们的 文档 以获取更多跟踪、数据集版本控制和评估示例。
9. Airbyte:可靠且可扩展的数据管道。🌬️
数据对于构建 AI 应用至关重要,尤其是在生产环境中,您必须管理来自各种来源的海量数据。Airbyte 在这方面表现出色。
Airbyte 提供了超过 300 个用于 API、数据库、数据仓库和数据湖的连接器的广泛目录。
Airbyte 还提供了一个名为 PyAirByte 的 Python 扩展。此扩展支持 LangChain 和 LlamaIndex 等热门框架,让您可以轻松地将数据从多个来源迁移到 GenAI 应用程序。
查看此 笔记本 了解有关使用 LangChain 实现 PyAirByte 的详细信息。
欲了解更多信息,请查看 文档。
10. AgentOps:代理监控和可观察性。👁️
与传统软件系统一样,人工智能代理需要持续的监控和观察。这对于确保代理的行为不偏离预期至关重要。
AgentOps 为监控和观察 AI 代理提供了全面的解决方案。
它提供重放分析、LLM 成本管理、代理基准测试、合规性和安全性工具,并与 CrewAI、AutoGen 和 LangChain 等框架本地集成。
通过安装来开始使用 AgentOps pip
。
pip install agentops
初始化 AgentOps 客户端并自动获取每个 LLM 调用的分析。
import agentops
# Beginning of program's code (i.e. main.py, __init__.py)
agentops.init( < INSERT YOUR API KEY HERE >)
...
# (optional: record specific functions)
@agentops.record_action('sample function being record')
def sample_function(...):
...
# End of program
agentops.end_session('Success')
# Woohoo You're done 🎉
请参阅他们的 文档 以了解更多信息。
11. RAGAS:RAG 评估框架。📊
构建 RAG 流程本身就充满挑战,但确定其在实际场景中的有效性又是另一回事。尽管 RAG 应用框架取得了一些进展,但确保其对真实用户的可靠性仍然具有挑战性,尤其是在错误检索成本高昂的情况下。
RAGAS 是一个旨在解决此问题的框架。它可以帮助您评估检索增强生成 (RAG) 流程。
它可以帮助您生成合成测试集,针对它们测试您的 RAG 管道,并在生产中监控您的 RAG 应用程序。
查看文档以了解如何使用 RAGAS 来改进新的和现有的 RAG 管道。
12. BentoML:为 AI 应用和模型提供服务的最简单方法。🍱
BentoML 是一款开源软件,它提供了一种便捷的方式,用于在生产环境中为模型和 AI 应用提供服务。无论是传统的机器学习模型还是语言模型,它只需几行代码和标准的 Python 类型提示,就能将任何模型推理脚本转换为 REST API 服务器。
它提供模型服务优化功能,如动态批处理、模型并行、多阶段管道和多模型推理图编排。
BentoML 让您可以使用自定义业务逻辑、模型推理和多模型组合快速实现自己的 API 或任务队列。
首先安装 BentoML 库。
# Requires Python≥3.8
pip install -U bentoml
在文件中定义 API service.py
。
from __future__ import annotations
import bentoml
@bentoml.service(
resources={"cpu": "4"}
)
class Summarization:
def __init__(self) -> None:
import torch
from transformers import pipeline
device = "cuda" if torch.cuda.is_available() else "cpu"
self.pipeline = pipeline('summarization', device=device)
@bentoml.api(batchable=True)
def summarize(self, texts: list[str]) -> list[str]:
results = self.pipeline(texts)
return [item['summary_text'] for item in results]
在本地运行服务代码(默认在 http://localhost:3000 提供服务):
pip install torch transformers # additional dependencies for local run
bentoml serve service.py:Summarization
现在,您可以通过浏览器访问 http://localhost:3000 或使用 Python 脚本运行推理:
import bentoml
with bentoml.SyncHTTPClient('http://localhost:3000') as client:
summarized_text: str = client.summarize([bentoml.__doc__])[0]
print(f"Result: {summarized_text}")
探索文档以了解更多信息。
13. LoRAX:多 LoRA 推理服务器,可扩展至数千个经过微调的 LLM。📡
LoRAX(LoRA eXchange)是一个框架,允许用户在单个 GPU 上提供数千个经过微调的模型,从而大幅降低服务成本,同时不影响吞吐量或延迟。
它可以从 HuggingFace、Predibase 或任何文件系统动态加载 LoRA 适配器,而不会阻止并发请求。
LoRAX 利用先进的量化和优化技术,例如分页注意力、Flash 注意力、张量并行和令牌流,以低延迟提供高吞吐量。
首先,您需要 Linux 操作系统和 Cuda 版本 11.8 兼容设备驱动程序、Nvidia GPU Ampere 以及以上一代。
启动 LoRAX 服务器
model=mistralai/Mistral-7B-Instruct-v0.1
volume=$PWD/data
docker run --gpus all --shm-size 1g -p 8080:80 -v $volume:/data \
ghcr.io/predibase/lorax:main --model-id $model
提示基础法学硕士:
curl 127.0.0.1:8080/generate \
-X POST \
-d '{
"inputs": "[INST] Natalia sold clips to 48 of her friends in April, and then she sold half as many clips in May. How many clips did Natalia sell altogether in April and May? [/INST]",
"parameters": {
"max_new_tokens": 64
}
}' \
-H 'Content-Type: application/json'
提示 LoRA 适配器:
curl 127.0.0.1:8080/generate \
-X POST \
-d '{
"inputs": "[INST] Natalia sold clips to 48 of her friends in April, and then she sold half as many clips in May. How many clips did Natalia sell altogether in April and May? [/INST]",
"parameters": {
"max_new_tokens": 64,
"adapter_id": "vineetsharma/qlora-adapter-Mistral-7B-Instruct-v0.1-gsm8k"
}
}' \
-H 'Content-Type: application/json'
有关完整详细信息,请参阅 参考 - REST API 。
14. Gateway:通过单个 API 可靠地路由到 200 个 LLM
在构建 AI 应用程序时,我们可能依赖专有的 LLM 或某些云托管网站提供的 LLM。最好做好应对中断的准备,因为你永远不知道会发生什么。
在这种情况下,您应该将请求从一个提供商路由到另一个提供商。网关是最佳解决方案。
它为 200 多家 LLM 提供商提供统一的 API。它支持缓存、负载均衡、路由和重试,并可进行边缘部署以最大程度地降低延迟。
这是构建容错、健壮的人工智能系统的关键部分。它支持 Python、Go、Rust、Java、Ruby 和 Javascript 语言。
通过安装来开始使用 Gateway。
pip install -qU portkey-ai openai
对于 OpenAI 模型,
from openai import OpenAI
from portkey_ai import PORTKEY_GATEWAY_URL, createHeaders
client = OpenAI(
api_key=OPENAI_API_KEY,
base_url=PORTKEY_GATEWAY_URL,
default_headers=createHeaders(
provider="openai",
api_key=PORTKEY_API_KEY
)
)
chat_complete = client.chat.completions.create(
model="gpt-4",
messages=[{"role": "user",
"content": "What's a fractal?"}],
)
print(chat_complete.choices[0].message.content)
对于人择模型,
from openai import OpenAI
from portkey_ai import PORTKEY_GATEWAY_URL, createHeaders
client = OpenAI(
api_key=userdata.get('ANTHROPIC_API_KEY')
base_url=PORTKEY_GATEWAY_URL,
default_headers=createHeaders(
provider="anthropic",
api_key=PORTKEY_API_KEY
),
)
response = client.chat.completions.create(
model="claude-3-opus-20240229",
messages=[{"role": "user",
"content": "What's a fractal?"}],
max_tokens= 512
)
欲了解更多信息,请访问 官方存储库。
15. LitServe:灵活、高吞吐量的 AI 模型服务引擎。💫
LitServe 是另一个 AI 模型服务引擎。它针对并行执行进行了高度优化,并具有扩展 AI 工作负载的原生功能。我们的基准测试表明,LitServe(基于 FastAPI 构建)比 FastAPI 和 TorchServe 能够处理更多并发请求。
LitServe 可以在您的机器上独立托管 - 非常适合喜欢 DIY 方法的黑客、学生和开发人员。
通过 pip 安装 LitServe(其他安装选项):
pip install litserve
定义服务器
这是一个 Hello World 示例(探索真实示例):
# server.py
import litserve as ls
# STEP 1: DEFINE A MODEL API
class SimpleLitAPI(ls.LitAPI):
# Called once at startup. Setup models, DB connections, etc...
def setup(self, device):
self.model = lambda x: x**2
# Convert the request payload to model input.
def decode_request(self, request):
return request["input"]
# Run inference on the model, and return the output.
def predict(self, x):
return self.model(x)
# Convert the model output to a response payload.
def encode_response(self, output):
return {"output": output}
# STEP 2: START THE SERVER
if __name__ == "__main__":
api = SimpleLitAPI()
server = ls.LitServer(api, accelerator="auto")
server.run(port=8000)
现在通过命令行运行服务器
python server.py
LitAPI
该类提供完全的控制和可破解性。
LitServer
处理批处理、自动 GPU 缩放等优化...
查询服务器
使用自动生成的 LitServe 客户端:
python client.py
感谢您阅读本文。如果您构建或使用过任何其他开源 AI 代码库,请在下方评论。👇
文章来源:https://dev.to/composiodev/15-hidden-open-source-gems-to-become-10x-ai-engineer-39pd