Skip to main content
Open In ColabOpen on GitHub

DeepInfra

DeepInfra 是一个无服务器推理即服务,提供对多种LLMs嵌入模型的访问。本笔记本介绍了如何将LangChain与DeepInfra结合使用以用于聊天模型。

设置环境API密钥

确保从DeepInfra获取您的API密钥。您需要登录并获取一个新的令牌。

您将获得1小时的无服务器GPU计算免费试用,以测试不同的模型。(参见这里) 您可以使用deepctl auth token打印您的令牌

# get a new token: https://deepinfra.com/login?from=%2Fdash

import os
from getpass import getpass

from langchain_community.chat_models import ChatDeepInfra
from langchain_core.messages import HumanMessage

DEEPINFRA_API_TOKEN = getpass()

# or pass deepinfra_api_token parameter to the ChatDeepInfra constructor
os.environ["DEEPINFRA_API_TOKEN"] = DEEPINFRA_API_TOKEN

chat = ChatDeepInfra(model="meta-llama/Llama-2-7b-chat-hf")

messages = [
HumanMessage(
content="Translate this sentence from English to French. I love programming."
)
]
chat.invoke(messages)
API Reference:ChatDeepInfra | HumanMessage

ChatDeepInfra 还支持异步和流式功能:

from langchain_core.callbacks import StreamingStdOutCallbackHandler
await chat.agenerate([messages])
chat = ChatDeepInfra(
streaming=True,
verbose=True,
callbacks=[StreamingStdOutCallbackHandler()],
)
chat.invoke(messages)

工具调用

DeepInfra 目前仅支持调用和异步调用工具调用。

有关支持工具调用的完整模型列表,请参阅我们的工具调用文档

import asyncio

from dotenv import find_dotenv, load_dotenv
from langchain_community.chat_models import ChatDeepInfra
from langchain_core.messages import HumanMessage
from langchain_core.tools import tool
from pydantic import BaseModel

model_name = "meta-llama/Meta-Llama-3-70B-Instruct"

_ = load_dotenv(find_dotenv())


# Langchain tool
@tool
def foo(something):
"""
Called when foo
"""
pass


# Pydantic class
class Bar(BaseModel):
"""
Called when Bar
"""

pass


llm = ChatDeepInfra(model=model_name)
tools = [foo, Bar]
llm_with_tools = llm.bind_tools(tools)
messages = [
HumanMessage("Foo and bar, please."),
]

response = llm_with_tools.invoke(messages)
print(response.tool_calls)
# [{'name': 'foo', 'args': {'something': None}, 'id': 'call_Mi4N4wAtW89OlbizFE1aDxDj'}, {'name': 'Bar', 'args': {}, 'id': 'call_daiE0mW454j2O1KVbmET4s2r'}]


async def call_ainvoke():
result = await llm_with_tools.ainvoke(messages)
print(result.tool_calls)


# Async call
asyncio.run(call_ainvoke())
# [{'name': 'foo', 'args': {'something': None}, 'id': 'call_ZH7FetmgSot4LHcMU6CEb8tI'}, {'name': 'Bar', 'args': {}, 'id': 'call_2MQhDifAJVoijZEvH8PeFSVB'}]
API Reference:ChatDeepInfra | HumanMessage | tool

这个页面有帮助吗?