Skip to main content
Open In Colab在 GitHub 上打开

伊甸园 AI

Eden AI 通过联合最好的 AI 提供商来彻底改变 AI 领域,使用户能够解锁无限可能并挖掘人工智能的真正潜力。借助一体化的全面、轻松的平台,它允许用户以闪电般的速度将 AI 功能部署到生产环境中,从而通过单个 API 轻松访问全面的 AI 功能。(网站:https://edenai.co/)

此示例介绍了如何使用 LangChain 与 Eden AI 模型进行交互


EdenAI不仅仅是模型调用。它为您提供高级功能,包括:

  • 多个提供商:访问各种提供商提供的各种语言模型,让您可以自由选择最适合您用例的模型。

  • 回退机制:设置回退机制以确保无缝作即使主提供商不可用,您也可以轻松切换到替代提供商。

  • Usage Tracking (使用情况跟踪):基于每个项目和 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 Chat Model 类时。

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?')]

回退 mecanism

使用 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
API 参考:ChatPromptTemplate
chain.invoke({"product": "healthy snacks"})
AIMessage(content='VitalBites')

工具

bind_tools()

ChatEdenAI.bind_tools,我们可以轻松地传入 Pydantic 类、dict 模式、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')

将 Tool Results 传递给模型

以下是如何使用工具的完整示例。将工具输出传递给模型,并从模型中获取结果

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}])]