1. 本地运行 Yi-34B 模型

1.1 环境准备

确保你的系统满足以下要求:

  • Python 3.8 或更高版本。
  • 适当的硬件资源(至少 8GB RAM,推荐使用 GPU)。
1.2 安装依赖

使用以下命令安装所需的Python库:

pip install transformers torch gradio
  • 1.
1.3 下载模型

从 Hugging Face 下载 Yi-34B 模型:

from transformers import AutoTokenizer, AutoModelForCausalLM

tokenizer = AutoTokenizer.from_pretrained("01ai/Yi-34B")
model = AutoModelForCausalLM.from_pretrained("01ai/Yi-34B")
  • 1.
  • 2.
  • 3.
  • 4.
1.4 运行模型

以下是一个简单的示例,展示如何使用 Gradio 创建一个简单的聊天界面:

import gradio as gr

def chatbot(input_text):
    # 生成响应
    input_ids = tokenizer.encode(input_text, return_tensors='pt')
    outputs = model.generate(input_ids)
    response = tokenizer.decode(outputs[0], skip_special_tokens=True)
    return response

# 创建 Gradio 接口
iface = gr.Interface(fn=chatbot, inputs="text", outputs="text")
iface.launch()
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
1.5 注意事项
  • 确保在运行模型之前有足够的内存和计算资源。
  • 如果遇到性能问题,可以考虑使用半精度浮点数(fp16)来减少内存消耗。

2. 通过 API 调用 Yi-34B

2.1 获取 API Key

注册并获取 API Key,通常在开放平台或API提供商的网站上完成。

2.2 安装 SDK

安装适用于 Yi-34B 的 Python SDK(如果有的话):

pip install openai
  • 1.
2.3 发送请求

使用以下代码发送 API 请求:

import openai
from openai import OpenAI

API_BASE = "https://api.lingyiwanwu.com/v1"
API_KEY = "你的API密钥"

client = OpenAI(api_key=API_KEY, base_url=API_BASE)

completion = client.chat.completions.create(
    model="yi-34b-chat-0205",
    messages=[{"role": "user", "content": "Hi, who are you?"}]
)

print(completion)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
2.4 响应处理

API 调用后,检查响应内容并处理。确保处理可能出现的错误。

2.5 示例代码

以下是使用 SDK 的完整示例:

from http import HTTPStatus
import dashscope

def call_with_messages():
    messages = [{'role': 'system', 'content': 'You are a helpful assistant.'},
                {'role': 'user', 'content': '你好'}]
    response = dashscope.Generation.call(
        model='yi-medium',
        messages=messages,
    )
    if response.status_code == HTTPStatus.OK:
        print(response)
    else:
        print('Request id: %s, Status code: %s, error code: %s, error message: %s' % (
            response.request_id, response.status_code,
            response.code, response.message
        ))

if __name__ == '__main__':
    call_with_messages()
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.

请根据你的具体需求和环境调整这些步骤。如果你遇到任何问题,查看 Yi-34B 的官方文档或社区论坛可能会提供帮助。