รวมโมเดลภาษาขนาดใหญ่เข้ากับรหัส Python ของคุณได้อย่างง่ายดาย เพียงใช้ @prompt และ @chatprompt ตกแต่งเพื่อสร้างฟังก์ชั่นที่ส่งคืนผลลัพธ์ที่มีโครงสร้างจาก LLM ผสมคิวรี LLM และฟังก์ชั่นการเรียกด้วยรหัส Python ปกติเพื่อสร้างตรรกะที่ซับซ้อน
FunctionCall และ ParallelFunctionCall ประเภทผลตอบแทนasync def เมื่อกำหนดฟังก์ชั่น Magenticpip install magenticหรือใช้ UV
uv add magentic กำหนดค่าคีย์ OpenAI API ของคุณโดยการตั้งค่าตัวแปรสภาพแวดล้อม OPENAI_API_KEY ในการกำหนดค่าผู้ให้บริการ LLM ที่แตกต่างกันให้ดูการกำหนดค่าสำหรับข้อมูลเพิ่มเติม
@prompt Decorator ช่วยให้คุณสามารถกำหนดเทมเพลตสำหรับแบบจำลองภาษาขนาดใหญ่ (LLM) เป็นฟังก์ชัน Python เมื่อฟังก์ชั่นนี้เรียกว่าอาร์กิวเมนต์จะถูกแทรกลงในเทมเพลตแล้วพรอมต์นี้จะถูกส่งไปยัง LLM ซึ่งสร้างเอาต์พุตฟังก์ชั่น
from magentic import prompt
@ prompt ( 'Add more "dude"ness to: {phrase}' )
def dudeify ( phrase : str ) -> str : ... # No function body as this is never executed
dudeify ( "Hello, how are you?" )
# "Hey, dude! What's up? How's it going, my man?" @prompt Decorator จะเคารพคำอธิบายประกอบประเภทผลตอบแทนของฟังก์ชั่นการตกแต่ง นี่อาจเป็นประเภทใดก็ได้ที่สนับสนุนโดย Pydantic รวมถึงรุ่น pydantic
from magentic import prompt
from pydantic import BaseModel
class Superhero ( BaseModel ):
name : str
age : int
power : str
enemies : list [ str ]
@ prompt ( "Create a Superhero named {name}." )
def create_superhero ( name : str ) -> Superhero : ...
create_superhero ( "Garden Man" )
# Superhero(name='Garden Man', age=30, power='Control over plants', enemies=['Pollution Man', 'Concrete Woman'])ดูผลลัพธ์ที่มีโครงสร้างสำหรับข้อมูลเพิ่มเติม
@chatprompt Decorator ทำงานได้เช่น @prompt แต่อนุญาตให้คุณส่งข้อความแชทเป็นเทมเพลตแทนที่จะเป็นข้อความข้อความเดียว สิ่งนี้สามารถใช้เพื่อให้ข้อความระบบหรือการแจ้งเตือนการยิงไม่กี่ครั้งซึ่งคุณให้การตอบสนองตัวอย่างเพื่อเป็นแนวทางในการส่งออกของโมเดล ฟิลด์ฟอร์แมตที่แสดงโดยการจัดฟันแบบหยิก {example} จะถูกกรอกในข้อความทั้งหมด (ยกเว้น FunctionResultMessage )
from magentic import chatprompt , AssistantMessage , SystemMessage , UserMessage
from pydantic import BaseModel
class Quote ( BaseModel ):
quote : str
character : str
@ chatprompt (
SystemMessage ( "You are a movie buff." ),
UserMessage ( "What is your favorite quote from Harry Potter?" ),
AssistantMessage (
Quote (
quote = "It does not do to dwell on dreams and forget to live." ,
character = "Albus Dumbledore" ,
)
),
UserMessage ( "What is your favorite quote from {movie}?" ),
)
def get_movie_quote ( movie : str ) -> Quote : ...
get_movie_quote ( "Iron Man" )
# Quote(quote='I am Iron Man.', character='Tony Stark')ดูการแชทพรอมต์สำหรับข้อมูลเพิ่มเติม
LLM ยังสามารถตัดสินใจเรียกใช้ฟังก์ชั่น ในกรณีนี้ฟังก์ชั่น @prompt -decorated ส่งคืนวัตถุ FunctionCall ซึ่งสามารถเรียกใช้เพื่อเรียกใช้ฟังก์ชันโดยใช้อาร์กิวเมนต์ที่ให้โดย LLM
from typing import Literal
from magentic import prompt , FunctionCall
def search_twitter ( query : str , category : Literal [ "latest" , "people" ]) -> str :
"""Searches Twitter for a query."""
print ( f"Searching Twitter for { query !r } in category { category !r } " )
return "<twitter results>"
def search_youtube ( query : str , channel : str = "all" ) -> str :
"""Searches YouTube for a query."""
print ( f"Searching YouTube for { query !r } in channel { channel !r } " )
return "<youtube results>"
@ prompt (
"Use the appropriate search function to answer: {question}" ,
functions = [ search_twitter , search_youtube ],
)
def perform_search ( question : str ) -> FunctionCall [ str ]: ...
output = perform_search ( "What is the latest news on LLMs?" )
print ( output )
# > FunctionCall(<function search_twitter at 0x10c367d00>, 'LLMs', 'latest')
output ()
# > Searching Twitter for 'Large Language Models news' in category 'latest'
# '<twitter results>'ดูฟังก์ชั่นเรียกใช้เพิ่มเติม
บางครั้ง LLM ต้องการการโทรอย่างน้อยหนึ่งรายการเพื่อสร้างคำตอบสุดท้าย @prompt_chain DOUNATORATOR จะแก้ไขวัตถุ FunctionCall โดยอัตโนมัติและส่งเอาต์พุตกลับไปยัง LLM เพื่อดำเนินการต่อไปจนกว่าจะถึงคำตอบสุดท้าย
ในตัวอย่างต่อไปนี้เมื่อ describe_weather เรียกว่า LLM แรกเรียกฟังก์ชั่น get_current_weather จากนั้นใช้ผลลัพธ์ของสิ่งนี้เพื่อกำหนดคำตอบสุดท้ายที่ได้รับการส่งคืน
from magentic import prompt_chain
def get_current_weather ( location , unit = "fahrenheit" ):
"""Get the current weather in a given location"""
# Pretend to query an API
return {
"location" : location ,
"temperature" : "72" ,
"unit" : unit ,
"forecast" : [ "sunny" , "windy" ],
}
@ prompt_chain (
"What's the weather like in {city}?" ,
functions = [ get_current_weather ],
)
def describe_weather ( city : str ) -> str : ...
describe_weather ( "Boston" )
# 'The current weather in Boston is 72°F and it is sunny and windy.' ฟังก์ชั่น LLM-powered ที่สร้างขึ้นโดยใช้ @prompt , @chatprompt และ @prompt_chain สามารถจัดหาเป็น functions กับ @prompt / @prompt_chain decorators อื่น ๆ เช่นเดียวกับฟังก์ชั่น Python ปกติ สิ่งนี้ช่วยให้ฟังก์ชั่นที่ใช้พลังงานจาก LLM ที่ซับซ้อนมากขึ้นในขณะที่ช่วยให้ส่วนประกอบแต่ละตัวได้รับการทดสอบและปรับปรุงในการแยก
คลาส StreamedStr (และ AsyncStreamedStr ) สามารถใช้เพื่อสตรีมเอาต์พุตของ LLM สิ่งนี้ช่วยให้คุณสามารถประมวลผลข้อความได้ในขณะที่กำลังถูกสร้างขึ้นแทนที่จะได้รับผลลัพธ์ทั้งหมดในครั้งเดียว
from magentic import prompt , StreamedStr
@ prompt ( "Tell me about {country}" )
def describe_country ( country : str ) -> StreamedStr : ...
# Print the chunks while they are being received
for chunk in describe_country ( "Brazil" ):
print ( chunk , end = "" )
# 'Brazil, officially known as the Federative Republic of Brazil, is ...' สามารถสร้าง StreamedStr หลายรายการในเวลาเดียวกันเพื่อสตรีมเอาต์พุต LLM พร้อมกัน ในตัวอย่างด้านล่างการสร้างคำอธิบายสำหรับหลายประเทศใช้เวลาประมาณเท่ากันกับประเทศเดียว
from time import time
countries = [ "Australia" , "Brazil" , "Chile" ]
# Generate the descriptions one at a time
start_time = time ()
for country in countries :
# Converting `StreamedStr` to `str` blocks until the LLM output is fully generated
description = str ( describe_country ( country ))
print ( f" { time () - start_time :.2f } s : { country } - { len ( description ) } chars" )
# 22.72s : Australia - 2130 chars
# 41.63s : Brazil - 1884 chars
# 74.31s : Chile - 2968 chars
# Generate the descriptions concurrently by creating the StreamedStrs at the same time
start_time = time ()
streamed_strs = [ describe_country ( country ) for country in countries ]
for country , streamed_str in zip ( countries , streamed_strs ):
description = str ( streamed_str )
print ( f" { time () - start_time :.2f } s : { country } - { len ( description ) } chars" )
# 22.79s : Australia - 2147 chars
# 23.64s : Brazil - 2202 chars
# 24.67s : Chile - 2186 chars เอาต์พุตที่มีโครงสร้างสามารถสตรีมจาก LLM ได้โดยใช้คำอธิบายประกอบประเภท Iterable (หรือ AsyncIterable ) สิ่งนี้จะช่วยให้แต่ละรายการได้รับการประมวลผลในขณะที่รายการถัดไปกำลังถูกสร้างขึ้น
from collections . abc import Iterable
from time import time
from magentic import prompt
from pydantic import BaseModel
class Superhero ( BaseModel ):
name : str
age : int
power : str
enemies : list [ str ]
@ prompt ( "Create a Superhero team named {name}." )
def create_superhero_team ( name : str ) -> Iterable [ Superhero ]: ...
start_time = time ()
for hero in create_superhero_team ( "The Food Dudes" ):
print ( f" { time () - start_time :.2f } s : { hero } " )
# 2.23s : name='Pizza Man' age=30 power='Can shoot pizza slices from his hands' enemies=['The Hungry Horde', 'The Junk Food Gang']
# 4.03s : name='Captain Carrot' age=35 power='Super strength and agility from eating carrots' enemies=['The Sugar Squad', 'The Greasy Gang']
# 6.05s : name='Ice Cream Girl' age=25 power='Can create ice cream out of thin air' enemies=['The Hot Sauce Squad', 'The Healthy Eaters']ดูการสตรีมสำหรับข้อมูลเพิ่มเติม
ฟังก์ชั่น / coroutines แบบอะซิงโครนัสสามารถใช้ในการสืบค้น LLM พร้อมกัน สิ่งนี้สามารถเพิ่มความเร็วโดยรวมของรุ่นได้อย่างมากและยังช่วยให้รหัสอะซิงโครนัสอื่น ๆ ทำงานในขณะที่รอเอาต์พุต LLM ในตัวอย่างด้านล่าง LLM สร้างคำอธิบายสำหรับประธานาธิบดีสหรัฐแต่ละคนในขณะที่กำลังรออยู่ในรายการถัดไปในรายการ การวัดอักขระที่สร้างขึ้นต่อวินาทีแสดงให้เห็นว่าตัวอย่างนี้ได้รับการเร่งความเร็ว 7x ผ่านการประมวลผลแบบอนุกรม
import asyncio
from time import time
from typing import AsyncIterable
from magentic import prompt
@ prompt ( "List ten presidents of the United States" )
async def iter_presidents () -> AsyncIterable [ str ]: ...
@ prompt ( "Tell me more about {topic}" )
async def tell_me_more_about ( topic : str ) -> str : ...
# For each president listed, generate a description concurrently
start_time = time ()
tasks = []
async for president in await iter_presidents ():
# Use asyncio.create_task to schedule the coroutine for execution before awaiting it
# This way descriptions will start being generated while the list of presidents is still being generated
task = asyncio . create_task ( tell_me_more_about ( president ))
tasks . append ( task )
descriptions = await asyncio . gather ( * tasks )
# Measure the characters per second
total_chars = sum ( len ( desc ) for desc in descriptions )
time_elapsed = time () - start_time
print ( total_chars , time_elapsed , total_chars / time_elapsed )
# 24575 28.70 856.07
# Measure the characters per second to describe a single president
start_time = time ()
out = await tell_me_more_about ( "George Washington" )
time_elapsed = time () - start_time
print ( len ( out ), time_elapsed , len ( out ) / time_elapsed )
# 2206 18.72 117.78ดู Asyncio เพิ่มเติม
functions ชั่นไปยัง @prompt สามารถมีฟังก์ชั่น async/coroutine เมื่อวัตถุ FunctionCall ชั่นที่สอดคล้องกันเรียกว่าผลลัพธ์จะต้องรอAnnotated สามารถใช้เพื่อให้คำอธิบายและข้อมูลเมตาอื่น ๆ สำหรับพารามิเตอร์ฟังก์ชั่น ดูเอกสาร Pydantic เกี่ยวกับการใช้ Field เพื่ออธิบายอาร์กิวเมนต์ฟังก์ชั่น@prompt และ @prompt_chain ตกแต่งยังยอมรับอาร์กิวเมนต์ model คุณสามารถผ่านอินสแตนซ์ของ OpenaiChatModel เพื่อใช้ GPT4 หรือกำหนดค่าอุณหภูมิที่แตกต่างกัน ดูด้านล่าง@prompt โดยทำตามสมุดบันทึกตัวอย่างสำหรับ pandas dataframe Magentic รองรับ "แบ็กเอนด์" หลายรายการ (ผู้ให้บริการ LLM) นี่คือ
openai : แบ็กเอนด์เริ่มต้นที่ใช้แพ็คเกจ openai Python รองรับคุณสมบัติทั้งหมดของ Magentic from magentic import OpenaiChatModelanthropic : ใช้แพ็คเกจ Python anthropic รองรับคุณสมบัติทั้งหมดของ Magentic แต่ขณะนี้ได้รับการตอบสนองการสตรีมทั้งหมดในครั้งเดียว pip install " magentic[anthropic] " from magentic . chat_model . anthropic_chat_model import AnthropicChatModellitellm : ใช้แพ็คเกจ litellm Python เพื่อเปิดใช้งานการสืบค้น LLMs จากผู้ให้บริการที่แตกต่างกันหลายราย หมายเหตุ: บางรุ่นอาจไม่รองรับคุณสมบัติทั้งหมดของฟังก์ชั่น magentic เช่นการเรียก/การโทรที่มีโครงสร้างและการสตรีม pip install " magentic[litellm] " from magentic . chat_model . litellm_chat_model import LitellmChatModelmistral : ใช้แพ็คเกจ openai Python ที่มีการดัดแปลงเล็ก ๆ น้อย ๆ เพื่อให้การสืบค้น API เข้ากันได้กับ Mistral API รองรับคุณสมบัติทั้งหมดของ Magentic อย่างไรก็ตามการโทรด้วยเครื่องมือ (รวมถึงเอาต์พุตที่มีโครงสร้าง) ไม่ได้รับการสตรีมดังนั้นจึงได้รับทั้งหมดในครั้งเดียว หมายเหตุ: Magentic เวอร์ชันในอนาคตอาจเปลี่ยนไปใช้แพ็คเกจ mistral Python from magentic . chat_model . mistral_chat_model import MistralChatModel แบ็กเอนด์และ LLM ( ChatModel ) ที่ใช้โดย magentic สามารถกำหนดค่าได้หลายวิธี เมื่อมีการเรียกฟังก์ชั่น Magentic, ChatModel ที่จะใช้ตามลำดับการตั้งค่านี้
ChatModel ที่จัดทำขึ้นเป็นอาร์กิวเมนต์ model ไปยังมัณฑนากร Magenticwith MyChatModel:ChatModel ที่สร้างขึ้นจากตัวแปรสภาพแวดล้อมและการตั้งค่าเริ่มต้นใน SRC/Magentic/Settings.py from magentic import OpenaiChatModel , prompt
from magentic . chat_model . litellm_chat_model import LitellmChatModel
@ prompt ( "Say hello" )
def say_hello () -> str : ...
@ prompt (
"Say hello" ,
model = LitellmChatModel ( "ollama_chat/llama3" ),
)
def say_hello_litellm () -> str : ...
say_hello () # Uses env vars or default settings
with OpenaiChatModel ( "gpt-3.5-turbo" , temperature = 1 ):
say_hello () # Uses openai with gpt-3.5-turbo and temperature=1 due to context manager
say_hello_litellm () # Uses litellm with ollama_chat/llama3 because explicitly configuredสามารถตั้งค่าตัวแปรสภาพแวดล้อมต่อไปนี้
| ตัวแปรสภาพแวดล้อม | คำอธิบาย | ตัวอย่าง |
|---|---|---|
| Magentic_backend | แพ็คเกจที่จะใช้เป็นแบ็กเอนด์ LLM | มานุษยวิทยา / openai / litellm |
| magentic_anthropic_model | แบบมานุษยวิทยา | Claude-3-Haiku-201240307 |
| magentic_anthropic_api_key | มานุษยวิทยา API Key ที่ใช้โดย Magentic | sk -... |
| magentic_anthropic_base_url | URL พื้นฐานสำหรับ API ที่เข้ากันได้กับมานุษยวิทยา | http: // localhost: 8080 |
| magentic_anthropic_max_tokens | จำนวนโทเค็นที่สร้างขึ้นสูงสุด | 1024 |
| magentic_anthropic_temperature | อุณหภูมิ | 0.5 |
| magentic_litellm_model | รุ่น Litellm | Claude-2 |
| magentic_litellm_api_base | URL พื้นฐานเพื่อสอบถาม | http: // localhost: 11434 |
| magentic_litellm_max_tokens | จำนวนโทเค็นที่สร้างขึ้นสูงสุด | 1024 |
| Magentic_litellm_Temperature | อุณหภูมิ Litellm | 0.5 |
| magentic_mistral_model | รูปแบบ mistral | การเสียสละขนาดใหญ่ |
| magentic_mistral_api_key | คีย์ Mistral API ที่จะใช้โดย Magentic | XEG ... |
| magentic_mistral_base_url | URL พื้นฐานสำหรับ API ที่เข้ากันได้กับ mistral | http: // localhost: 8080 |
| magentic_mistral_max_tokens | จำนวนโทเค็นที่สร้างขึ้นสูงสุด | 1024 |
| magentic_mistral_seed | เมล็ดพันธุ์สำหรับการสุ่มตัวอย่างที่กำหนด | 42 |
| magentic_mistral_temperature | อุณหภูมิ | 0.5 |
| magentic_openai_model | โมเดล openai | GPT-4 |
| magentic_openai_api_key | Openai API Key ที่ใช้โดย Magentic | sk -... |
| magentic_openai_api_type | ตัวเลือกที่อนุญาต: "openai", "Azure" | สีฟ้า |
| magentic_openai_base_url | URL พื้นฐานสำหรับ API ที่เข้ากันได้กับ OpenAI | http: // localhost: 8080 |
| magentic_openai_max_tokens | Openai Max จำนวนโทเค็นที่สร้างขึ้น | 1024 |
| magentic_openai_seed | เมล็ดพันธุ์สำหรับการสุ่มตัวอย่างที่กำหนด | 42 |
| magentic_openai_temperature | อุณหภูมิ openai | 0.5 |
เมื่อใช้แบ็กเอนด์ openai การตั้งค่าตัวแปรสภาพแวดล้อม MAGENTIC_OPENAI_BASE_URL หรือใช้ OpenaiChatModel(..., base_url="http://localhost:8080") ในรหัสช่วยให้คุณใช้ magentic Openai Proxy Server, localai โปรดทราบว่าหาก API ไม่รองรับการเรียกใช้เครื่องมือคุณจะไม่สามารถสร้างฟังก์ชั่นพรอมต์ที่ส่งคืนวัตถุ Python แต่คุณสมบัติอื่น ๆ ของ magentic จะยังคงทำงานอยู่
ในการใช้ Azure กับ Openai Backend คุณจะต้องตั้งค่าตัวแปรสภาพแวดล้อม MAGENTIC_OPENAI_API_TYPE เป็น "Azure" หรือใช้ OpenaiChatModel(..., api_type="azure") และตั้งค่าตัวแปรสภาพแวดล้อมที่ต้องการ ดู https://github.com/openai/openai-python#microsoft-azure-openai
หมากฮอสหลายประเภทจะเพิ่มคำเตือนหรือข้อผิดพลาดสำหรับฟังก์ชั่นกับ @prompt Decorator เนื่องจากฟังก์ชั่นที่ไม่มีร่างกายหรือค่าส่งคืน มีหลายวิธีในการจัดการกับสิ่งเหล่านี้
empty-body # pyproject.toml
[ tool . mypy ]
disable_error_code = [ " empty-body " ]... (สิ่งนี้ไม่เป็นไปตาม mypy) หรือ raise @ prompt ( "Choose a color" )
def random_color () -> str : ...# type: ignore[empty-body] ในแต่ละฟังก์ชั่น ในกรณีนี้คุณสามารถเพิ่มเอกสารแทน ... @ prompt ( "Choose a color" )
def random_color () -> str : # type: ignore[empty-body]
"""Returns a random color."""