最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用Python調(diào)用大模型(LLM)的四種方式匯總

 更新時(shí)間:2025年09月29日 10:38:45   作者:用什么都重名  
隨著大語言模型(LLM)在各類任務(wù)中的強(qiáng)大表現(xiàn),越來越多的開發(fā)者和研究人員希望將這些模型集成到自己的工作流程或產(chǎn)品中,Python?作為最主流的?AI?開發(fā)語言,提供了豐富的生態(tài)工具,能夠靈活、高效地調(diào)用各類大模型,本文分析了四種不同的LLM?API調(diào)用腳本

前言

隨著大語言模型(LLM)在各類任務(wù)中的強(qiáng)大表現(xiàn),從問答系統(tǒng)到代碼生成,從寫作助手到數(shù)據(jù)分析,越來越多的開發(fā)者和研究人員希望將這些模型集成到自己的工作流程或產(chǎn)品中。Python 作為最主流的 AI 開發(fā)語言,提供了豐富的生態(tài)工具,能夠靈活、高效地調(diào)用各類大模型。

本篇博客旨在幫助開發(fā)者掌握不同的API調(diào)用方式來與各種LLM服務(wù)進(jìn)行交互。本文分析了四種不同的LLM API調(diào)用腳本,涵蓋了從最基礎(chǔ)的HTTP請求到高級SDK的使用方法。

1. 原生HTTP請求方式

1.1 核心特點(diǎn)

- 使用Python的`requests`庫直接發(fā)送HTTP請求

- 調(diào)用本地部署的Qwen模型

- 采用OpenAI兼容的API格式

1.2 關(guān)鍵代碼分析

# 請求體結(jié)構(gòu)
data = {
    "model": "/models/Qwen2___5-32B-Instruct-AWQ",
    "messages": [
        {"role": "user", "content": "分析當(dāng)前全球經(jīng)濟(jì)形勢,并提出你的見解"}
    ],
    "max_tokens": 2048,
    "temperature": 0.7,
    "top_k": 1,
    "top_p": 0.75,
}

1.3 優(yōu)勢和適用場景

**優(yōu)勢:**

- 靈活性最高,可以完全自定義請求參數(shù)

- 不依賴特定SDK,減少依賴

- 適合需要精確控制請求細(xì)節(jié)的場景

**適用場景:**

- 自定義LLM服務(wù)調(diào)用

- 需要特殊請求頭或認(rèn)證方式

- 對性能要求較高的生產(chǎn)環(huán)境

1.4 完整代碼

import requests
import json
 
# 本地服務(wù)的 API 端點(diǎn)
url = "http://127.0.0.1:6790/v1/chat/completions"
 
# 請求頭
headers = {
    "Content-Type": "application/json",
    #"Authorization": "Bearer your_api_key"  # 如果需要的話
}
 
# 請求體
data = {
    "model": "/models/Qwen2___5-32B-Instruct-AWQ",
    "messages": [
        {"role": "user", "content": "分析當(dāng)前全球經(jīng)濟(jì)形勢,并提出你的見解"}
    ],
    "max_tokens": 2048,
    "temperature": 0.7,
    "top_k": 1,
    "top_p": 0.75,
}
 
# 發(fā)送 POST 請求
response = requests.post(url, headers=headers, data=json.dumps(data))
 
# 解析并打印回復(fù)內(nèi)容
if response.status_code == 200:
    response_data = response.json()
    print(response_data['choices'][0]['message']['content'])
else:
    print(f"請求失敗,狀態(tài)碼:{response.status_code}")
    print(response.text)

2. 封裝式API調(diào)用

2.1 核心特點(diǎn)

- 將API調(diào)用邏輯封裝成函數(shù)

- 支持多種模型選擇(qwen2.5_32b_awq, qwen2.5_7b_awq)

- 使用completion API而非chat completion API

2.2 關(guān)鍵代碼分析

def llm_inference(prompt_list: list, model_name: str):
    # 根據(jù)模型名稱選擇不同的服務(wù)器配置
    if model_name == "qwen2.5_32b_awq":
        llm_server = {"server_url": "http://127.0.0.1:6790/v1/completions",
                      "path": "/psd/models/Qwen2___5-32B-Instruct-AWQ"}

2.3 優(yōu)勢和適用場景

**優(yōu)勢:**

- 代碼復(fù)用性好,便于維護(hù)

- 支持多模型切換

- 統(tǒng)一的錯(cuò)誤處理機(jī)制

**適用場景:**

- 需要頻繁切換不同模型的場景

- 批量處理多個(gè)請求

- 作為其他項(xiàng)目的依賴模塊

2.4 完整代碼 

# -*- coding: utf-8 -*-            
# @Author : yuan
# @Time : 2025/7/22 5:20

import requests
import json

def llm_inference(prompt_list: list, model_name: str):
    if model_name == "qwen2.5_32b_awq":
        llm_server = {"server_url": "http://127.0.0.1:6790/v1/completions",
                      "path": "/models/Qwen2___5-32B-Instruct-AWQ"}

    elif model_name == "qwen2.5_7b_awq":
        llm_server = {"server_url": "http://127.0.0.1:6791/v1/completions",
                      "path": "/models/Qwen2___5-7B-Instruct-AWQ"}
    else:
        llm_server = {"server_url": "http://127.0.0.1:6790/v1/completions",
                      "path": "/models/Qwen2___5-32B-Instruct-AWQ"}

    # system_text = ""
    # prompt = f"<|im_start|>system\n{system_text}<|im_end|>\n<|im_start|>user\n{query_text}<|im_end|><|im_start|>assistant\n"
    rewrite_server_url = llm_server["server_url"]
    rewrite_server_headers = {
        'Content-Type': 'application/json'
    }
    rewrite_server_data = {
        'model': llm_server["path"],
        'prompt': prompt_list,
        'max_tokens': 4096, # 生成長度
        'top_k': 1,
        'top_p': 0.75,
        'temperature': 0,
        'stop': ["<|im_end|>"]
    }
    response = requests.post(rewrite_server_url, headers=rewrite_server_headers, data=json.dumps(rewrite_server_data))
    # return response.json()['choices'][0]['text']
    return response.json()

if __name__ == "__main__":
    prompt_list = [f"<|im_start|>system\n{'你是圍城智能機(jī)器人'}<|im_end|>\n<|im_start|>user\n{'你是誰'}<|im_end|><|im_start|>assistant\n"]

    answer = llm_inference(prompt_list, "qwen2.5_32b_awq")
    # print(answer)
    for i in range(len(prompt_list)):
        print(answer['choices'][i]['text'])

3. OpenAI SDK方式

3.1 核心特點(diǎn)

- 使用官方的OpenAI Python SDK

- 調(diào)用第三方API服務(wù)(chataiapi.com)

- 支持多種模型(GPT-4o, Gemini-2.5-pro等)

3.2 關(guān)鍵代碼分析

client = OpenAI(
    api_key=openai_api_key,
    base_url=openai_api_base,
)
response = client.chat.completions.create(
    model=model_name,
    messages=messages,
    temperature=0.0
)

3.3 優(yōu)勢和適用場景

**優(yōu)勢:**

- 使用官方SDK,穩(wěn)定性高

- 自動(dòng)處理認(rèn)證和請求格式

- 支持流式響應(yīng)等高級功能

**適用場景:**

- 調(diào)用OpenAI官方或兼容API

- 需要SDK提供的便利功能

- 快速原型開發(fā)

3.4 完整代碼 

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
極簡化的API請求測試腳本
只保留發(fā)送請求的核心功能
"""

from openai import OpenAI


def send_test_request(client, model_name, test_message="im testing, response me latter 'test' only"):
    """
    發(fā)送測試請求
    Args:
        client: OpenAI客戶端
        model_name: 模型名稱
        test_message: 測試消息
    Returns:
        str: 響應(yīng)內(nèi)容
    """
    # messages = [
    #     {"role": "user", "content": [
    #         {"type": "text", "text": test_message}
    #     ]}
    # ]
    # 構(gòu)建消息列表
    messages = [{"role": "user", "content": "你叫什么名字!"}]
    response = client.chat.completions.create(
        model=model_name,
        messages=messages,
        temperature=0.0
    )

    print(f"Response: {response}")
    return response.choices[0].message.content


if __name__ == "__main__":
    # API配置
    openai_api_key = "sk-WVoD66MR7b"
    openai_api_base = "https://www.api.com/v1"
    model_name = "gpt-4o"  # gemini-2.5-pro  gpt-4o  Claude 3.5 Sonnet  o3-mini

    # 初始化客戶端
    client = OpenAI(
        api_key=openai_api_key,
        base_url=openai_api_base,
    )
    test_message = "你好"
    # 發(fā)送測試請求
    try:
        response_content = send_test_request(client, model_name, test_message)
        print(f"Success! Response content: {response_content}")
    except Exception as e:
        print(f"Error: {e}")

4. 傳統(tǒng)OpenAI庫方式

4.1 核心特點(diǎn)

- 使用傳統(tǒng)的`openai`庫(非SDK)

- 支持本地和遠(yuǎn)程API調(diào)用

- 簡潔的API調(diào)用方式

4.2 關(guān)鍵代碼分析

openai.api_key = "sk-WVoD66MR"
openai.api_base = "https://www.api.com/v1"

response = openai.ChatCompletion.create(
    model=model_name,
    messages=[{"role": "user", "content": "你叫什么名字!"}],
    max_tokens=512,
    temperature=0.7
)

4.3 優(yōu)勢和適用場景

**優(yōu)勢:**

- 代碼簡潔,易于理解

- 兼容性好,支持多種API服務(wù)

- 學(xué)習(xí)成本低

**適用場景:**

- 快速測試和驗(yàn)證

- 教學(xué)和演示

- 簡單的集成需求

4.4 完整代碼 

import openai

# 設(shè)置 API 密鑰(如果本地服務(wù)需要)
openai.api_key = "sk-WVoD66MR7bx"

# 設(shè)置 API 基礎(chǔ) URL 為本地模型服務(wù)的地址
# openai.api_base = "http://127.0.0.1:6790/v1"
openai.api_base = "https://www.chataiapi.com/v1"

# 指定要使用的模型名稱
# model_name = "/models/Qwen2___5-32B-Instruct-AWQ"
model_name = "gemini-2.5-pro"

# 創(chuàng)建聊天完成請求
response = openai.ChatCompletion.create(
    model=model_name,
    messages=[{"role": "user", "content": "你叫什么名字!"}],
    max_tokens=512,
    temperature=0.7
)
print("response:",response)
# 打印生成的回復(fù)內(nèi)容
print(response['choices'][0]['message']['content'])

5. 對比分析

| 特性 | llm_request.py | api_inference.py | llm_openai.py | llm_request_local.py |

|------|----------------|------------------|---------------|---------------------|

| 靈活性 | ????? | ???? | ??? | ??? |

| 易用性 | ?? | ???? | ????? | ????? |

| 可維護(hù)性 | ?? | ????? | ???? | ??? |

| 功能豐富度 | ??? | ??? | ????? | ??? |

| 學(xué)習(xí)成本 | ?? | ??? | ???? | ????? |

總結(jié)

這四種調(diào)用方式各有特色,適用于不同的開發(fā)場景。開發(fā)者應(yīng)該根據(jù)具體需求選擇合適的方式:

追求靈活性:選擇原生HTTP請求

追求可維護(hù)性:選擇封裝函數(shù)

追求功能豐富:選擇OpenAI SDK

追求簡單易用:選擇傳統(tǒng)OpenAI庫

無論選擇哪種方式,都要注意API密鑰的安全性和錯(cuò)誤處理的完整性。在實(shí)際項(xiàng)目中,建議根據(jù)項(xiàng)目規(guī)模和團(tuán)隊(duì)技術(shù)棧做出合理選擇。

以上就是使用Python調(diào)用大模型(LLM)的四種方式匯總的詳細(xì)內(nèi)容,更多關(guān)于Python調(diào)用大模型(LLM)的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論

紫阳县| 承德县| 灌阳县| 盘锦市| 华宁县| 徐汇区| 永新县| 宁晋县| 利辛县| 襄汾县| 福建省| 洪江市| 铅山县| 宁阳县| 电白县| 社旗县| 信丰县| 娱乐| 区。| 渭源县| 富平县| 福泉市| 永康市| 石林| 马关县| 安福县| 从江县| 舒兰市| 聂荣县| 呼和浩特市| 枣阳市| 梅河口市| 亚东县| 夏邑县| 乌兰县| 冷水江市| 甘肃省| 芮城县| 泗阳县| 上饶县| 合川市|