三种访问Qwen大模型的方式

1. 通过API Key访问大模型


这是最直接的方式,通过官方API接口调用Qwen模型服务。你需要先在阿里云百炼平台获取API Key。

import dashscope
from dashscope.api_entities.dashscope_response import Role
​
# 设置API Key (替换为你的实际Key)
dashscope.api_key = "your_api_key_here"def get_response(messages):
    response = dashscope.Generation.call(
        model='qwen-turbo',  # 或使用其他Qwen模型如'qwen-plus'
        messages=messages,
        result_format='text'  # 输出格式可以是'message'或'text'
       #result_format='message'  # 将输出设置为message形式
    )
    return response
​
# 示例使用
review = '这本书写得很烂,读也读不懂。'
messages = [
    {"role": "system", "content": "你是一名舆情分析师,帮我判断产品口碑的正负向,回复请用一个词语:正向 或者 负向"},
    {"role": "user", "content": review}
]
​
response = get_response(messages)#对应text格式的输出
print(response.output.text)
# 对应message格式的content输出
#print(response.json()["output"]["choices"][0]["message"]["content"])
#print(response.output.choices[0].message.content)




说明:需替换your_api_key_here,支持流式输出(添加"stream": true参数)。

2. 本地部署大模型后在程序中封装调用


这种方式需要先在本地部署Qwen模型,然后通过transformers库直接调用。

from transformers import AutoModelForCausalLM, AutoTokenizer
​
# 加载本地部署的Qwen模型
# model_path = "/path/to/your/qwen_model"  # 替换为你的模型路径
model_path="C:\\Users\\Administrator\\AInewModels\\deepseek-ai\\DeepSeek-R1-Distill-Qwen-1___5B"
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(model_path, 
                                           device_map="auto", #如果有GPU可选"cuda"
                                           torch_dtype="auto", 
                                           trust_remote_code=True).eval()def query_model(text):
    inputs = tokenizer([text], return_tensors="pt").to(model.device)
    outputs = model.generate(**inputs, max_length=128,max_new_tokens=200)
    return tokenizer.decode(outputs[0], skip_special_tokens=True)# 示例使用
review = '这本书写得很烂,读也读不懂。'
messages = [
    {"role": "system", "content": "你是一名舆情分析师,帮我判断产品口碑的正负向,回复请用一个词语:正向 或者 负向"},
    {"role": "user", "content": review}
]
prompt = tokenizer.apply_chat_template(
    messages,
    tokenize=False,
    add_generation_prompt=True
)
response = query_model(prompt)
print(response)
'你是一名舆情分析师,帮我判断产品口碑的正负向,回复请用一个词语:正向 或者 负向<|User|>这本书写得很烂,读也读不懂。<|Assistant|><think>\n好,我现在需要分析用户的问题。用户提到这本书写得很烂,读也读不懂。首先,我应该判断这是正面还是负面评价。书的内容质量差,影响读者阅读体验,这属于负面评价。所以,回复应该是“负向”。\n</think>\n\n负向'


3. 本地部署大模型后通过类似API Key的方式调用


适用场景:将本地模型封装为HTTP服务供多端调用。
步骤

  1. 使用FastAPIFlask启动本地API服务。
  2. 通过requests访问本地端口。

    代码示例(服务端):
from fastapi import FastAPI
from transformers import AutoModelForCausalLM, AutoTokenizer
​
app = FastAPI()
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen-7B-Chat", device_map="auto")
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen-7B-Chat")@app.post("/chat")
def chat(question: str):
    inputs = tokenizer(question, return_tensors="pt").to("cuda")
    outputs = model.generate(**inputs, max_new_tokens=50)
    return {"answer": tokenizer.decode(outputs[0], skip_special_tokens=True)}


客户端调用

import requests
response = requests.post("http://localhost:8000/chat", json={"question": "Python怎么排序列表?"})
print(response.json()["answer"])


说明:可结合Ollama简化部署流程(如ollama run qwen2:7b)。



补充: 使用Ollama等工具本地部署Qwen后,可以创建兼容OpenAI API的本地服务。

from openai import OpenAI
​
# 配置本地API服务
client = OpenAI(
    base_url='http://localhost:11434/v1',  # Ollama默认端口
    api_key='ollama'  # 本地服务通常不需要真实API Key
)def get_local_response(prompt):
    completion = client.chat.completions.create(
        model="qwen",  # 本地部署的模型名称
        messages=[
            {"role": "system", "content": "你是一个有帮助的助手。"},
            {"role": "user", "content": prompt}
        ],
        temperature=0.7
    )
    return completion.choices[0].message.content
​
# 示例使用
response = get_local_response("请用Python写一个快速排序算法")
print(response)

总结对比

方法 适用场景 优点 缺点
API Key访问 快速测试、轻量级应用、无硬件资源 简单、无需部署、支持流式输出 依赖网络、长期成本高、隐私性低
本地直接调用 数据敏感、离线环境、高性能需求 隐私性强、离线可用、高度定制化 硬件要求高、部署复杂
本地HTTP服务调用 团队协作、多端调用、本地化部署 多端兼容、隐私性好、集中管理 需额外开发、硬件依赖、可能延迟


注意事项

  1. API Key方式需要网络连接,但使用最简单
  2. 本地部署方式需要足够的硬件资源(特别是GPU)
  3. Ollama方式对硬件要求较低,适合快速本地测试
  4. 所有代码示例中的参数(如模型名称、路径等)需要根据你的实际情况调整
Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐