Eden AI
Eden AI 正在革新 AI 領域,透過整合最佳的 AI 提供商,讓使用者能夠釋放無限的可能性,並發掘人工智慧的真正潛力。藉由一站式全面且無憂的平台,使用者可以快速地將 AI 功能部署到生產環境,透過單一 API 輕鬆存取完整的 AI 功能。(網站:https://edenai.co/)
這個範例說明如何使用 LangChain 與 Eden AI 模型互動。
EdenAI
不僅僅是模型調用。它還為您提供進階功能,包括:
-
多重供應商:存取由多家供應商提供的多樣化語言模型,讓您能自由選擇最適合您使用案例的模型。
-
備援機制:設定備援機制,即使主要供應商無法使用,也能確保操作順暢,您可以輕鬆切換到替代供應商。
-
使用量追蹤:依專案和 API 金鑰追蹤使用量統計數據。此功能讓您能夠有效地監控和管理資源消耗。
-
監控與可觀測性:
EdenAI
平台提供全面的監控與可觀測性工具。監控您的語言模型效能、分析使用模式,並獲得寶貴的洞察,以優化您的應用程式。
存取 EDENAI 的 API 需要 API 金鑰,
您可以透過建立帳戶來取得金鑰 https://app.edenai.run/user/register,並前往此處 https://app.edenai.run/admin/iam/api-keys
取得金鑰後,您需要執行以下指令將其設定為環境變數:
export EDENAI_API_KEY="..."
您可以在 API 參考文件中找到更多詳細資訊:https://docs.edenai.co/reference
如果您不想設定環境變數,可以直接透過 edenai_api_key 具名參數傳遞金鑰
在初始化 EdenAI 聊天模型類別時。
from langchain_community.chat_models.edenai import ChatEdenAI
from langchain_core.messages import HumanMessage
chat = ChatEdenAI(
edenai_api_key="...", provider="openai", temperature=0.2, max_tokens=250
)
messages = [HumanMessage(content="Hello !")]
chat.invoke(messages)
AIMessage(content='Hello! How can I assist you today?')
await chat.ainvoke(messages)
AIMessage(content='Hello! How can I assist you today?')
串流與批次處理
ChatEdenAI
支援串流與批次處理。以下是一個範例。
for chunk in chat.stream(messages):
print(chunk.content, end="", flush=True)
Hello! How can I assist you today?
chat.batch([messages])
[AIMessage(content='Hello! How can I assist you today?')]
備援機制
透過 Eden AI,您可以設定備援機制,即使主要供應商無法使用,也能確保操作順暢,您可以輕鬆切換到替代供應商。
chat = ChatEdenAI(
edenai_api_key="...",
provider="openai",
temperature=0.2,
max_tokens=250,
fallback_providers="google",
)
在此範例中,如果 OpenAI 遇到任何問題,您可以將 Google 作為備份供應商。
有關 Eden AI 的更多資訊和詳細資料,請查看此連結:https://docs.edenai.co/docs/additional-parameters
鏈式調用
from langchain_core.prompts import ChatPromptTemplate
prompt = ChatPromptTemplate.from_template(
"What is a good name for a company that makes {product}?"
)
chain = prompt | chat
chain.invoke({"product": "healthy snacks"})
AIMessage(content='VitalBites')
工具
bind_tools()
透過 ChatEdenAI.bind_tools
,我們可以輕鬆地將 Pydantic 類別、字典綱要、LangChain 工具,甚至函數作為工具傳遞給模型。
from pydantic import BaseModel, Field
llm = ChatEdenAI(provider="openai", temperature=0.2, max_tokens=500)
class GetWeather(BaseModel):
"""Get the current weather in a given location"""
location: str = Field(..., description="The city and state, e.g. San Francisco, CA")
llm_with_tools = llm.bind_tools([GetWeather])
ai_msg = llm_with_tools.invoke(
"what is the weather like in San Francisco",
)
ai_msg
AIMessage(content='', response_metadata={'openai': {'status': 'success', 'generated_text': None, 'message': [{'role': 'user', 'message': 'what is the weather like in San Francisco', 'tools': [{'name': 'GetWeather', 'description': 'Get the current weather in a given location', 'parameters': {'type': 'object', 'properties': {'location': {'description': 'The city and state, e.g. San Francisco, CA', 'type': 'string'}}, 'required': ['location']}}], 'tool_calls': None}, {'role': 'assistant', 'message': None, 'tools': None, 'tool_calls': [{'id': 'call_tRpAO7KbQwgTjlka70mCQJdo', 'name': 'GetWeather', 'arguments': '{"location":"San Francisco"}'}]}], 'cost': 0.000194}}, id='run-5c44c01a-d7bb-4df6-835e-bda596080399-0', tool_calls=[{'name': 'GetWeather', 'args': {'location': 'San Francisco'}, 'id': 'call_tRpAO7KbQwgTjlka70mCQJdo'}])
ai_msg.tool_calls
[{'name': 'GetWeather',
'args': {'location': 'San Francisco'},
'id': 'call_tRpAO7KbQwgTjlka70mCQJdo'}]
with_structured_output()
BaseChatModel.with_structured_output 介面讓從聊天模型取得結構化輸出變得容易。您可以使用 ChatEdenAI.with_structured_output(底層使用工具調用),讓模型更可靠地以特定格式傳回輸出。
structured_llm = llm.with_structured_output(GetWeather)
structured_llm.invoke(
"what is the weather like in San Francisco",
)
GetWeather(location='San Francisco')
將工具結果傳遞給模型
這是一個如何使用工具的完整範例。將工具輸出傳遞給模型,並從模型取得結果。
from langchain_core.messages import HumanMessage, ToolMessage
from langchain_core.tools import tool
@tool
def add(a: int, b: int) -> int:
"""Adds a and b.
Args:
a: first int
b: second int
"""
return a + b
llm = ChatEdenAI(
provider="openai",
max_tokens=1000,
temperature=0.2,
)
llm_with_tools = llm.bind_tools([add], tool_choice="required")
query = "What is 11 + 11?"
messages = [HumanMessage(query)]
ai_msg = llm_with_tools.invoke(messages)
messages.append(ai_msg)
tool_call = ai_msg.tool_calls[0]
tool_output = add.invoke(tool_call["args"])
# This append the result from our tool to the model
messages.append(ToolMessage(tool_output, tool_call_id=tool_call["id"]))
llm_with_tools.invoke(messages).content
'11 + 11 = 22'
串流
Eden AI 目前不支援串流工具調用。嘗試串流將產生單一最終訊息。
list(llm_with_tools.stream("What's 9 + 9"))
/home/eden/Projects/edenai-langchain/libs/community/langchain_community/chat_models/edenai.py:603: UserWarning: stream: Tool use is not yet supported in streaming mode.
warnings.warn("stream: Tool use is not yet supported in streaming mode.")
[AIMessageChunk(content='', id='run-fae32908-ec48-4ab2-ad96-bb0d0511754f', tool_calls=[{'name': 'add', 'args': {'a': 9, 'b': 9}, 'id': 'call_n0Tm7I9zERWa6UpxCAVCweLN'}], tool_call_chunks=[{'name': 'add', 'args': '{"a": 9, "b": 9}', 'id': 'call_n0Tm7I9zERWa6UpxCAVCweLN', 'index': 0}])]