首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >使用LangChain自定义大模型 | 完美调用第三方 API | 如OneAPI/硅基流动

使用LangChain自定义大模型 | 完美调用第三方 API | 如OneAPI/硅基流动

作者头像
比克AI
修改2024-11-20 10:56:32
修改2024-11-20 10:56:32
4.3K0
举报
文章被收录于专栏:AI早高峰AI早高峰

很多OneAPI类的平台,提供了免费的API-KEY,不会使用怎么办? 在线等吗。。。 不! 看下面的方法

  • 【方法2】通过 OpenAI******接口调用。** 如果你想要封装为一个大模型/对话模型,体验更高级功能,比如跟LangChain框架结合。 像下面这样调用openai的就叫OpenAI接口方法

1. LangChain自定义大模型

安装 Python3.7.1 或更高版本并设置虚拟环境后,即可安装 OpenAI Python 库

代码语言:python
复制
pip install --upgrade openai

智谱zhipuglm-3为例,下面是LangChain自定义大模型的代码

代码语言:python
复制
from openai import OpenAI
from langchain.prompts import ChatPromptTemplate

# API密钥
API_KEY = "sk-sxhxxxoyw"

# 自定义硅基流动大模型类
class CustomLLM_Siliconflow:
    def __call__(self, prompt: str) -> str:
        # 初始化OpenAI客户端(base_url是硅基流动网站的地址)
        client = OpenAI(api_key=API_KEY, base_url="https://api.siliconflow.cn/v1")
        
        # 发送请求到模型
        response = client.chat.completions.create(
            model='THUDM/glm-4-9b-chat',
            messages=[
                {'role': 'user', 
                 'content': f"{prompt}"}  # 用户输入的提示
            ],
        )

        # 打印响应结构,以便调试
        # print("Response structure:", response)

        # 收集所有响应内容
        content = ""
        if hasattr(response, 'choices') and response.choices:
            for choice in response.choices:
                if hasattr(choice, 'message') and hasattr(choice.message, 'content'):
                    chunk_content = choice.message.content
                    # print(chunk_content, end='')  # 可选:打印内容
                    content += chunk_content  # 将内容累加到总内容中
        else:
            raise ValueError("Unexpected response structure")

        return content  # 返回最终的响应内容

注释说明

  1. API密钥:定义了访问OpenAI API的密钥。
  2. 自定义硅基流动大模型类:定义了一个自定义的LLM类,实现了__call__方法,使其可以像函数一样调用。
  3. 初始化OpenAI客户端:使用API密钥和基础URL初始化OpenAI客户端。
  4. 发送请求到模型:构建并发送一个包含用户输入提示的消息到指定的模型。
  5. 收集所有响应内容:遍历响应中的每个块,提取内容并累加到总内容中。
  6. 返回最终的响应内容:将收集到的所有内容作为最终结果返回。

2. 自定义LLM实例

代码语言:python
复制
# 创建自定义LLM实例
llm = CustomLLM_Siliconflow()
    
# 示例查询:将大象装进冰箱分几步?
print(llm("把大象装进冰箱分几步?"))

输出如下

把大象装进冰箱一般被分为以下三个步骤:

  1. 打开冰箱门。
  2. 把大象放进冰箱里。
  3. 关闭冰箱门。

但实际上,这个问题通常是一个幽默性质的开场白,用来引起人们的兴趣或调侃。现实中,大象体形巨大,不可能被放进普通的家用冰箱中。这样的问题往往用于儿童游戏或成人间的玩笑。

3. 使用LangChain的PromptTemplate

代码语言:python
复制
from openai import OpenAI
from langchain.prompts import ChatPromptTemplate

# API密钥
API_KEY = "sk-sxhxxxoyw"

# 自定义硅基流动大模型类
class CustomLLM_Siliconflow:
    def __call__(self, prompt: str) -> str:
        # 初始化OpenAI客户端
        client = OpenAI(api_key=API_KEY, base_url="https://api.siliconflow.cn/v1")
        
        # 发送请求到模型
        response = client.chat.completions.create(
            model='THUDM/glm-4-9b-chat',
            messages=[
                {'role': 'user', 
                 'content': f"{prompt}"}  # 用户输入的提示
            ],
        )

        # 打印响应结构,以便调试
        # print("Response structure:", response)

        # 收集所有响应内容
        content = ""
        if hasattr(response, 'choices') and response.choices:
            for choice in response.choices:
                if hasattr(choice, 'message') and hasattr(choice.message, 'content'):
                    chunk_content = choice.message.content
                    # print(chunk_content, end='')  # 可选:打印内容
                    content += chunk_content  # 将内容累加到总内容中
        else:
            raise ValueError("Unexpected response structure")

        return content  # 返回最终的响应内容

if __name__ == '__main__':
    # 创建自定义LLM实例
    llm = CustomLLM_Siliconflow()
    
    # 示例查询:将大象装进冰箱分几步?
    # print(llm("把大象装进冰箱分几步?"))


 # 基础版
    # 定义国家名称
    country = """中国"""
    
    # 定义任务模板
    country_template = """
    任务: 输入一个国家,输出国家的首都
    语言:中文

    按json格式输出,输出格式如下:
    country_name
    capital_name

    国家: {country_name}
    """

    # 使用模板创建提示
    prompt_template = ChatPromptTemplate.from_template(country_template)
    messages = prompt_template.format_messages(country_name=country)
    
    # 获取模型响应
    response = llm(messages)
    print(response)  # 打印响应内容

输出如下

json { { "country\_name": "中国", "capital\_name": "北京" }

注释说明

  1. 定义国家名称:定义了一个国家名称变量。
  2. 定义任务模板:定义了一个任务模板,用于生成特定格式的提示。
  3. 使用模板创建提示:使用模板和国家名称生成具体的提示消息。
  4. 获取模型响应:调用自定义LLM实例,获取模型的响应。
  5. 打印响应内容:将模型的响应内容打印出来。

4.(进阶)使用LangChain的PromptTemplate+ Parser

代码语言:python
复制
from openai import OpenAI
from langchain.prompts import ChatPromptTemplate
from langchain.output_parsers import ResponseSchema
from langchain.output_parsers import StructuredOutputParser

# API密钥
API_KEY = "sk-sxhxxxoyw"

# 自定义硅基流动大模型类
class CustomLLM_Siliconflow:
    def __call__(self, prompt: str) -> str:
        # 初始化OpenAI客户端
        client = OpenAI(api_key=API_KEY, base_url="https://api.siliconflow.cn/v1")
        
        # 发送请求到模型
        response = client.chat.completions.create(
            model='THUDM/glm-4-9b-chat',
            messages=[
                {'role': 'user', 
                 'content': f"{prompt}"}  # 用户输入的提示
            ],
        )

        # 打印响应结构,以便调试
        # print("Response structure:", response)

        # 收集所有响应内容
        content = ""
        if hasattr(response, 'choices') and response.choices:
            for choice in response.choices:
                if hasattr(choice, 'message') and hasattr(choice.message, 'content'):
                    chunk_content = choice.message.content
                    # print(chunk_content, end='')  # 可选:打印内容
                    content += chunk_content  # 将内容累加到总内容中
        else:
            raise ValueError("Unexpected response structure")

        return content  # 返回最终的响应内容

if __name__ == '__main__':
    # 创建自定义LLM实例
    llm = CustomLLM_Siliconflow()
    
    # 示例查询:将大象装进冰箱分几步?
    # print(llm("把大象装进冰箱分几步?"))


    # 进阶版
    country_schema = ResponseSchema(name="country_name", description="国家的名称。")
    capital_schema = ResponseSchema(name="capital_name", description="对应国家的首都名称。")
    response_schemas = [country_schema, capital_schema]
    output_parser = StructuredOutputParser.from_response_schemas(response_schemas)
    # 获取格式化指令
    format_instructions = output_parser.get_format_instructions()

    # 定义模板字符串,用于构建提示词
    country_template = """\
    任务: 输入一个国家,输出国家的首都
    语言:中文

    国家: {country_name}
    {format_instructions}
    """

    prompt_template = ChatPromptTemplate.from_template(country_template)
    messages = prompt_template.format_messages(country_name="中国",
                                            format_instructions=format_instructions)
    # 发送消息并获取响应
    response = llm(messages)
    print(response)     # 里面本来有response.content,现在用自定义模型,就没有这个内容了

    # 使用 `output_parser` 解析响应内容
    output_dict = output_parser.parse(response)
    print(output_dict)

输出如下

json { { "country\_name": "中国", "capital\_name": "北京" }

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. LangChain自定义大模型
  • 2. 自定义LLM实例
  • 3. 使用LangChain的PromptTemplate
  • 4.(进阶)使用LangChain的PromptTemplate+ Parser
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档