Skip to main content
Eden AI 正在通过整合最优秀的 AI 提供商来革新 AI 领域,赋能用户挖掘无限可能并充分发挥人工智能的真正潜力。借助这一一站式的全面、简便平台,用户可以快速将 AI 功能部署至生产环境,通过单一 API 轻松访问 AI 能力的全部广度。(网站:edenai.co/ 本示例介绍如何使用 LangChain 与 Eden AI 模型进行交互。
EdenAI 不仅仅是模型调用,它还为您提供了高级功能,包括:
  • 多家提供商:访问多家提供商提供的多种语言模型,让您可以自由选择最适合您使用场景的模型。
  • 回退机制:设置回退机制,即使主提供商不可用也能确保无缝运行,可轻松切换到备用提供商。
  • 用量追踪:按项目和 API 密钥维度追踪用量统计数据。此功能让您可以有效监控和管理资源消耗。
  • 监控与可观测性EdenAI 在平台上提供全面的监控和可观测性工具。监控语言模型的性能、分析使用模式,并获取有价值的洞察以优化您的应用。
访问 EDENAI 的 API 需要 API 密钥, 您可以通过创建账户 app.edenai.run/user/register 并前往 app.edenai.run/admin/iam/api-keys 获取。 获取密钥后,运行以下命令将其设置为环境变量:
export EDENAI_API_KEY="..."
更多详情请参阅 API 参考文档:docs.edenai.co/reference 如果您不希望设置环境变量,也可以在初始化 EdenAI 聊天模型类时通过 edenai_api_key 命名参数直接传入密钥。
from langchain_community.chat_models.edenai import ChatEdenAI
from langchain.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 的更多信息和详细说明,请访问: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 类、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')

将工具结果传递给模型

以下是如何使用工具的完整示例。将工具输出传递给模型,并从模型获取结果:
from langchain.messages import HumanMessage, ToolMessage
from langchain.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}])]