AI大模型教程
一起来学习

Langchain如何调用Siliconflow的模型

硅基流动之前宣布了部分模型免费,那我们就可以调用API来搞些事情。
官网(Chat Completions (siliconflow.cn))上给出了详细的调用方式,我们可以方便的ctrl C 和 ctrl V

而Langchain支持自定义封装LLMCustom LLM | 🦜️🔗 Langchain

那我们就可以结合搞点事情,封装好的代码在这,需要自取:

from langchain.llms.base import LLM
from langchain_community.llms.utils import enforce_stop_tokens
import requests
import os

# 设置API密钥和基础URL环境变量
API_KEY = os.getenv("CUSTOM_API_KEY", "")
BASE_URL = "https://api.siliconflow.cn/v1/chat/completions"

class SiliconFlow(LLM):
    def __init__(self):
        super().__init__()

    @property
    def _llm_type(self) -> str:
        return "siliconflow"

    def siliconflow_completions(self, model: str, prompt: str) -> str:
        payload = {
            "model": model,
            "messages": [{"role": "user", "content": prompt}],
            "stream": False
        }
        headers = {
            "accept": "application/json",
            "content-type": "application/json",
            "authorization": f"Bearer {API_KEY}"
        }

        response = requests.post(BASE_URL, json=payload, headers=headers)
        response.raise_for_status()
        return response.json()["choices"][0]["message"]["content"]

    def _call(self, prompt: str, stop: list = None, model: str = "default-model") -> str:
        response = self.siliconflow_completions(model=model, prompt=prompt)
        if stop is not None:
            response = enforce_stop_tokens(response, stop)
        return response

if __name__ == "__main__":
    llm = SiliconFlow()
    response = llm._call(prompt="", model="")
    print(response)

文章来源于互联网:Langchain如何调用Siliconflow的模型

相关推荐: GitHubCopilot免费开放,完整使用攻略!|开发者必备

在开发工作中,时间与效率就是一切!作为程序员的“圣地”,GitHub推出的AI编程助手Copilot不仅能节省大量时间,还能让你的代码质量更上一层楼。尤其是现在免费版功能如此强大,实在没有理由不试试。 没错,就在几天前GitHub宣布了一项让开发者心跳加速的好…

赞(0)
未经允许不得转载:5bei.cn大模型教程网 » Langchain如何调用Siliconflow的模型
分享到: 更多 (0)

AI大模型,我们的未来

小欢软考联系我们