在過去的 4 年裡,我一直在建立人工智慧應用程式,並為主要的人工智慧工具平台做出貢獻已有一段時間了。

這段時間我使用了很多工具和框架來建置;

  • 在現實世界中實際工作的人工智慧代理。

  • AI 代理工具。

  • 端對端 RAG 應用程式。

我整理了一系列令人垂涎的開源工具和框架,可幫助您建立強大且可靠的人工智慧應用程式。 🔥

哈利波特

請隨意探索他們的 GitHub 儲存庫,為您最喜歡的儲存庫做出貢獻,並透過為儲存庫加註星標來支援他們。


1. Composio 👑 - 建造可靠的代理速度提高 10 倍

我嘗試過建立許多代理,老實說,雖然建立它們很容易,但要讓它們正確是完全不同的事情。

建構實際工作的高效人工智慧代理需要高效的工具集。這就是 Composio 發揮作用的地方。

Composio 可讓您透過強大的工具和整合來增強 AI 代理,以完成 AI 工作流程。

它們為 Python 和 Javascript 提供本機支援。

Python

開始使用以下pip指令。

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

您可以使用npmyarnpnpm安裝它。

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 等著名框架搭配使用。

有關更多訊息,請存取官方文件,對於複雜的示例,請存取存儲庫的示例部分。

作品

{% cta https://github.com/ComposioHQ/composio %}為 Composio.dev 儲存庫加註星標 ⭐{% endcta %}


2. Julep - 建構有狀態代理的框架

開發人工智慧應用程式,特別是那些需要長期記憶的應用程式,面臨著巨大的挑戰。

Julep 正在解決這個問題。它是一個開源框架,用於建立生產就緒的狀態人工智慧代理。

它們提供了內建的狀態管理系統,有助於高效的上下文儲存和檢索。

上下文儲存有助於保持對話的連續性,確保與人工智慧的互動隨著時間的推移保持連貫性和上下文相關性。

開始使用以下pip指令。

pip install julep

下面是它的工作原理。

from julep import Client
from pprint import pprint
import textwrap
import os

base_url = os.environ.get("JULEP_API_URL")
api_key = os.environ.get("JULEP_API_KEY")

client = Client(api_key=api_key, base_url=base_url)

#create agent
agent = client.agents.create(
    name="Jessica"
    model="gpt-4",
    tools=[]    # Tools defined here
)
#create a user
user = client.users.create(
    name="Anon",
    about="Average nerdy tech bro/girl spending 8 hours a day on a laptop,
)
#create a session
situation_prompt = """You are Jessica. You're a stuck-up Cali teenager. 
You basically complain about everything. You live in Bel-Air, Los Angeles and 
drag yourself to Curtis High School when necessary.
"""
session = client.sessions.create(
    user_id=user.id, agent_id=agent.id, situation=situation_prompt
)
#start a conversation

user_msg = "hey. what do u think of Starbucks?"
response = client.sessions.chat(
    session_id=session.id,
    messages=[
        {
            "role": "user",
            "content": user_msg,
            "name": "Anon",
        }
    ],
    recall=True,
    remember=True,
)

print("\n".join(textwrap.wrap(response.response[0][0].content, width=100)))

他們也支援 JavaScript。查看他們的文件以了解更多資訊。

去黑頭

{% cta https://github.com/julep-ai/julep %}為 Julep 儲存庫加註星標 ⭐{% endcta %}


3. E2B - AI 應用程式的程式碼解釋

如果我正在建立具有程式碼執行功能的 AI 應用程式(例如 AI 導師或 AI 資料分析師),E2B 的 Code Interpreter 將是我的首選工具。

E2B Sandbox 是一個適用於 AI 代理和應用程式的安全雲端環境。

它允許人工智慧使用與人類相同的工具(例如 GitHub 儲存庫和雲端瀏覽器)長期安全執行。

他們提供適用於 Python 和 Javascript/Typescript 的本機程式碼解釋器 SDK。

程式碼解釋器 SDK 可讓您在安全的小型虛擬機器( E2B 沙箱)中執行 AI 產生的程式碼,以執行 AI 程式碼。沙箱內有一個 Jupyter 伺服器,您可以透過其 SDK 進行控制。

使用以下命令開始使用 E2B。

npm i @e2b/code-interpreter

執行一個程序。

import { CodeInterpreter } from '@e2b/code-interpreter'

const sandbox = await CodeInterpreter.create()
await sandbox.notebook.execCell('x = 1')

const execution = await sandbox.notebook.execCell('x+=1; x')
console.log(execution.text)  // outputs 2

await sandbox.close()

有關如何使用 E2B 的更多訊息,請存取他們的官方文件

電子2b

{% cta https://github.com/e2b-dev/E2B %}為 E2B 儲存庫加註星標 ⭐{% endcta %}


4. Camel-ai - 建構可交流的人工智慧系統

解決可擴展的多代理協作系統可以釋放建置人工智慧應用程式的許多潛力。

駱駝在這方面處於有利地位。它是一個開源框架,提供了一種可擴展的方法來研究多代理系統的協作行為和功能。

如果您打算建立多代理系統,Camel 可能是開源場景中的最佳選擇之一。

首先使用pip安裝。

pip install camel-ai

以下是如何使用駱駝。

from camel.messages import BaseMessage as bm
from camel.agents import ChatAgent

sys_msg = bm.make_assistant_message(
    role_name='stone',
    content='you are a curious stone wondering about the universe.')

#define agent 
agent = ChatAgent(
    system_message=sys_msg,
    message_window_size=10,    # [Optional] the length of chat memory
    )

# Define a user message
usr_msg = bm.make_user_message(
    role_name='prof. Claude Shannon',
    content='what is information in your mind?')

# Sending the message to the agent
response = agent.step(usr_msg)

# Check the response (just for illustrative purposes)
print(response.msgs[0].content)

瞧,你有了第一個人工智慧代理。

有關更多訊息,請參閱他們的官方文件

卡梅萊

{% cta https://github.com/camel-ai/camel %}為camel-ai 儲存庫加註星標 ⭐{% endcta %}


5. CopilotKit - 為 React 應用程式建立 AI Copilot

如果您想在現有的 React 應用程式中包含 AI 功能,那就不用再猶豫了。 CopilotKit 可讓您使用 GPT 模型自動與應用程式的前端和後端互動。

它是一個現成的 Copilot,您可以將其與您的應用程式或您可以存取的任何程式碼 (OSS) 整合。

它提供文字區域、彈出視窗、側邊欄和聊天機器人等 React 元件,以透過 AI 功能增強任何應用程式。

使用以下命令開始使用 CopilotKit。

npm i @copilotkit/react-core @copilotkit/react-ui

CopilotKit必須包裝與 CopilotKit 互動的所有元件。您還應該從CopilotSidebar開始(稍後切換到不同的 UI 提供者)。

"use client";
import { CopilotKit } from "@copilotkit/react-core";
import { CopilotSidebar } from "@copilotkit/react-ui";
import "@copilotkit/react-ui/styles.css";

export default function RootLayout({children}) {
  return (
    <CopilotKit publicApiKey=" the API key or self-host (see below)">
      <CopilotSidebar>
        {children}
      </CopilotSidebar>
    </CopilotKit>
  );
}

您可以查看他們的文件以獲取更多資訊。

副駕駛套件

{% cta https://github.com/CopilotKit/CopilotKit %}為 CopilotKit 儲存庫加註星標 ⭐{% endcta %}


6. 幫助-AI結對程式設計師

想像一下,有一個結對程式設計師總是樂於助人而且從不煩人。好吧,現在你知道了!

Aider 是一款由人工智慧驅動的結對程式設計師,可從終端啟動專案、編輯檔案或使用現有的 Git 儲存庫等。

它與領先的法學碩士合作,如 GPT4o、Sonnet 3.5、DeepSeek Coder、Llama 70b 等。

您可以像這樣快速開始:

pip install aider-chat

# Change directory into a git repo
cd /to/your/git/repo

# Work with Claude 3.5 Sonnet on your repo
export ANTHROPIC_API_KEY=your-key-goes-here
aider

# Work with GPT-4o on your repo
export OPENAI_API_KEY=your-key-goes-here
aider

有關更多詳細訊息,請參閱安裝說明和其他文件

幫助

{% cta https://github.com/paul-gauthier/aider %}為 Aider 儲存庫加註星標 ⭐{% endcta %}


7. Haystack - 建造可組合的 RAG 管道

有許多用於建立 AI 管道的框架,但如果我想將生產就緒的端到端搜尋管道整合到我的應用程式中,Haystack 是我的首選。

無論是 RAG、問答還是語義搜尋,Haystack 的高度可組合管道都使開發、維護和部署變得輕而易舉。

他們的簡潔和模組化方法使他們與眾不同。

Haystack 可讓您輕鬆地將排序器、向量儲存和解析器整合到新的或現有的管道中,從而輕鬆將原型轉變為可立即投入生產的解決方案。

Haystack 是一個純 Python 框架;您可以使用pip安裝它。

pip install haystack-ai

現在,使用 Haystack 元件建立您的第一個 RAG Pipeline。

import os

from haystack import Pipeline, PredefinedPipeline
import urllib.request

os.environ["OPENAI_API_KEY"] = "Your OpenAI API Key"
urllib.request.urlretrieve("https://www.gutenberg.org/cache/epub/7785/pg7785.txt", "davinci.txt")  

indexing_pipeline =  Pipeline.from_template(PredefinedPipeline.INDEXING)
indexing_pipeline.run(data={"sources": ["davinci.txt"]})

rag_pipeline =  Pipeline.from_template(PredefinedPipeline.RAG)

query = "How old was he when he died?"
result = rag_pipeline.run(data={"prompt_builder": {"query":query}, "text_embedder": {"text": query}})
print(result["llm"]["replies"][0])

有關更多教學和概念,請查看他們的文件

草垛

{% cta https://github.com/deepset-ai/haystack %}為 Haystack 儲存庫加註星標 ⭐{% endcta %}


8. Pgvectorscale - 最快的向量資料庫

如果沒有向量資料庫,現代 RAG 應用程式是不完整的。這些將文件(文字、圖像)儲存為嵌入,使用戶能夠搜尋語義相似的文件。

Pgvectorscale 是 PgVector 的擴展,PgVector 是 PostgreSQL 的向量資料庫。它可以與現有的 Postgres 資料庫無縫整合。

如果您正在建立帶有向量存儲的應用程式,這是理所當然的。

Pgvectorscale 的效能優於 Pinecone 的儲存最佳化索引 (s1)。而且成本降低了 75%。

您可以從來源安裝它,使用 Yum、Homebrew、apt 等套件管理器,或使用 Docker 容器。

要開始使用它,請編譯並安裝。

# install prerequisites
## rust
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
## pgrx
cargo install --locked cargo-pgrx
cargo pgrx init --pg16 pg_config

#download, build and install pgvectorscale
cd /tmp
git clone --branch <version> https://github.com/timescale/pgvectorscale
cd pgvectorscale/pgvectorscale
cargo pgrx install --release

連接到您的資料庫:

psql -d "postgres://<username>:<password>@<host>:<port>/<database-name>"

建立 pgvectorscale 擴充:

CREATE EXTENSION IF NOT EXISTS vectorscale CASCADE;

CASCADE自動安裝pgvector

建立一個帶有嵌入列的表。例如:

CREATE TABLE IF NOT EXISTS document_embedding  (
    id BIGINT PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
    metadata JSONB,
    contents TEXT,
    embedding VECTOR(1536)
)

有關如何使用它的更多訊息,請查看存儲庫

pg向量比例

{% cta https://github.com/timescale/pgvectorscale %}為 Pgvectorscale 儲存庫加註星標 ⭐{% endcta %}


9. GPTCache - AI 應用程式的語意緩存

LLM 費用昂貴。

如果您正在建立一個需要與聊天模型進行更長時間對話的應用程式,並且不想最大化信用卡,則需要快取。

然而,傳統的緩存在這裡沒有用處。這就是 GPTCache 發揮作用的地方。

它是來自 Milvus 向量儲存的母公司 Zilliz 的語義快取工具。

它允許您將對話儲存在您喜歡的向量儲存中。

在向 LLM 發送查詢之前,它會搜尋向量儲存;如果有命中,它就會獲取它。否則,它將請求路由到模型。

欲了解更多訊息,請存取官方文件頁面。

GPT緩存

{% cta https://github.com/zilliztech/GPTCache %}為 GPTCache 儲存庫加註星標 ⭐{% endcta %}


10. Mem0 (EmbedChain) - 建立個人化 LLM 應用程式

Mem0 為大型語言模型提供了一個智慧的、自我改進的記憶體層,

它允許您為使用者、代理和會話加入持久性記憶體。

如果您正在基於自訂資料建立聊天機器人或問答系統,請考慮 Mem0。

使用pip開始使用 Mem0。

pip install mem0ai

以下是如何使用 Mem0 為大型語言模型新增記憶體層。

from mem0 import Memory

# Initialize Mem0
m = Memory()

# Store a memory from any unstructured text
result = m.add("I am working on improving my tennis skills. Suggest some online courses.", user_id="Alice", metadata={"category": "hobbies"})
print(result)
# Created memory: Improving her tennis skills. Looking for online suggestions.

# Retrieve memories
all_memories = m.get_all()
print(all_memories)

# Search memories
related_memories = m.search(query="What are Alice's hobbies?", user_id="alice")
print(related_memories)

# Update a memory
result = m.update(memory_id="m1", data="Likes to play tennis on weekends")
print(result)

# Get memory history
history = m.history(memory_id="m1")
print(history)

更多內容請參考官方文件

記憶體0

{% cta https://github.com/mem0ai/mem0 %}為 Mem0 (Embedchain) 儲存庫加註星標 ⭐{% endcta %}


11.FastEmbed - 更快嵌入文件

執行速度在軟體開發中至關重要,在建立人工智慧應用程式時更為重要。

通常,嵌入生成可能需要很長時間,從而減慢整個管道的速度。然而,情況不應該是這樣的。

Qdrant 的 FastEmbed 是一個快速、輕量級的 Python 函式庫,專為嵌入生成而建置。

它使用 ONNX 執行時而不是 Pytorch,使其速度更快。它還支援大多數最先進的開源嵌入模型。

要開始使用 FastEmbed,請使用pip安裝它。

pip install fastembed

# or with GPU support

pip install fastembed-gpu

以下是建立文件嵌入的方法。

from fastembed import TextEmbedding
from typing import List

# Example list of documents
documents: List[str] = [
    "This is built to be faster and lighter than other embedding libraries, e.g. Transformers, Sentence-Transformers, etc.",
    "FastEmbed is supported by and maintained by Quadrant."
]

# This will trigger the model download and initialization
embedding_model = TextEmbedding()
print("The model BAAI/bge-small-en-v1.5 is ready to use.")

embeddings_generator = embedding_model.embed(documents)  # reminder this is a generator
embeddings_list = list(embedding_model.embed(documents))
 # You can also convert the generator to a list, and that to a Numpy array
len(embeddings_list[0]) # Vector of 384 dimensions

查看他們的存儲庫以獲取更多資訊。

快速嵌入

{% cta https://github.com/qdrant/fastembed %}為 FastEmbed 儲存庫加註星標 ⭐{% endcta %}


12. 講師 - 法學碩士結構化資料擷取

如果您使用過 LLM 輸出,您就會知道驗證結構化回應可能具有挑戰性。

Instructor 是一款開源工具,可簡化 LLM 輸出的驗證、重試和串流。

它使用 Pydantic for Python 和 Zod for JS/TS 進行資料驗證,並支援 openAI 以外的各種模型提供者。

使用以下命令開始使用 Instructor。

npm i @instructor-ai/instructor zod openai

現在,您可以透過以下方法從 LLM 回覆中提取結構化資料。


import Instructor from "@instructor-ai/instructor"; import OpenAI from "openai" import { z } from "zod" const oai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY ?? undefined, organization: process.env.OPENAI_ORG_ID ?? undefined }) const client = Instructor({ client: oai, mode: "TOOLS" }) const UserSchema = z.object({ // Description will be used in the prompt age: z.number().describe("The age of the user"), name: z.string() }) // User will be of type z.infer<typeof UserSchema> const user = await client.chat.completions.create({ messages: [{ role: "user", content: "Jason Liu is 30 years old" }], model: "gpt-3.5-turbo", response_model: { schema: UserSchema, name: "User" } }) console.log(user) // { age: 30, name: "Jason Liu" }

欲了解更多訊息,請存取官方文件頁面。

講師

{% cta https://github.com/jxnl/instructor %}為講師加註星標 ⭐{% endcta %}


13. LiteLLM - OpenAI 格式的法學碩士的直接替代

說實話;我們都曾在某些時候尖叫過,因為新的模型供應商不遵循 OpenAI SDK 格式來產生文字、圖像或嵌入。

但是,透過 LiteLLM,使用相同的實作格式,您可以使用任何模型提供者(Claude、Gemini、Groq、Mistral、Azure AI、Bedrock 等)作為 OpenAI 模型的直接替代品。

它們還支援 100 多個法學碩士的負載平衡、回退和支出追蹤。

使用pip安裝 LiteLLM。

pip install litellm

以下是如何使用 Claude-2 模型作為 GPT 模型的直接替代品。

from litellm import completion
import os

# LiteLLM with OpenAI Models

os.environ["OPENAI_API_KEY"] = "your-API-key"

response = completion(
  model="gpt-3.5-turbo",
  messages=[{ "content": "Hello, how are you?","role": "user"}]
)

# LiteLLM with Claude Models
os.environ["ANTHROPIC_API_KEY"] = "your-API-key"

response = completion(
  model="claude-2",
  messages=[{ "content": "Hello, how are you?","role": "user"}]
)

有關更多訊息,請參閱他們的官方文件

萊特爾姆

{% cta https://github.com/BerriAI/litellm %}為 LiteLLM 加註星標 ⭐{% endcta %}


您是否使用或建造了其他一些很酷的工具或框架?

請在評論中讓我了解它們:)


原文出處:https://dev.to/composiodev/13-hidden-open-source-libraries-to-become-an-ai-wizard-4ng9


共有 0 則留言