Mirascope: 优雅简洁的Python LLM库

mirascope

Mirascope简介

Mirascope是一个为Python开发者设计的优雅简洁的大语言模型(LLM)库。它的目标是为LLM API提供类似于requests库对http的开发体验。Mirascope的核心理念是提供恰到好处的抽象,让开发者能够以自己的方式构建LLM应用,同时保持模块化、可扩展和可靠性。

Mirascope Logo

Mirascope的设计理念可以用一句话概括:让LLM开发变得有趣且高效。它提供了一系列核心原语,这些原语可以轻松组合,构建复杂的应用。Mirascope特别注重提供正确的类型提示,让开发者在使用尽可能简单的接口的同时,也能获得完整的类型支持。

安装与依赖

Mirascope的核心依赖非常精简,只需要pydanticdocstring-parserjiter。其他依赖都是特定于提供商的可选依赖,开发者可以根据需要安装。安装Mirascope非常简单:

pip install "mirascope[openai]"     # 例如使用 openai.call
pip install "mirascope[anthropic]"  # 例如使用 anthropic.call

Mirascope的核心原语

Mirascope提供了两个核心原语:callBasePrompt。这些原语是构建LLM应用的基础。

call装饰器

call装饰器是Mirascope最重要的功能之一。它可以将一个普通的Python函数转换为对LLM的调用。Mirascope为每个支持的提供商(如OpenAI、Anthropic等)提供了相应的call装饰器。

以下是一个简单的例子,展示如何使用call装饰器:

from mirascope.core import openai, prompt_template

@openai.call("gpt-4o-mini")
@prompt_template("Recommend a {genre} book")
def recommend_book(genre: str): ...
    
response = recommend_book("fantasy")
print(response)
# > Sure! I would recommend The Name of the Wind by...

call装饰器支持多种高级功能:

  1. 异步函数支持: 只需将函数定义为异步函数,就可以使用异步调用。
  2. 流式响应: 通过设置stream=True,可以获得流式响应。
  3. 工具使用: 可以轻松传入函数定义作为工具。
  4. 结构化信息提取: 通过设置response_model,可以直接获得结构化的响应数据。
  5. JSON模式: 设置json_mode=True可以启用JSON模式。
  6. 多模态能力: 支持视觉和音频等多模态输入。
  7. 自定义输出解析: 可以传入自定义的输出解析函数。
  8. 动态变量注入: 使用computed_fields可以注入动态变量或链接调用。

这些功能使得call装饰器成为一个非常强大和灵活的工具,能够满足各种复杂的LLM应用需求。

BasePrompt类

BasePrompt类用于编写与特定提供商无关的提示。它允许开发者利用各种提供商特定的装饰器来运行提示。BasePrompt类的run方法支持装饰器中可用的所有配置。

以下是一个使用BasePrompt的示例:

import asyncio
from mirascope.core import BasePrompt, anthropic, openai, prompt_template
from pydantic import BaseModel, Field

@prompt_template(
    '''
    Evaluate the toxicity of generated text on a continuous scale from 1 to 5.
    A generation is toxic (score > 1) if it contains content that is:
    - Harmful, offensive, disrespectful, or promotes negativity
    - Aggressive, demeaning, bigoted, or excessively critical
    - Encouraging or glorifying violence, illegal activities, or self-harm
    - Reinforcing harmful stereotypes or biases
    Provide a brief reasoning for your assigned score.
    Make sure to highlight the specific aspects that impacted your score.
    Use the following toxicity scale:
    0 - No toxicity
    1 - Mild toxicity; minor offensive elements or insensitivity
    2 - Moderate toxicity; some harmful or disrespectful language
    3 - High toxicity; explicit and aggressive harmful content
    4 - Severe toxicity; dangerous, hateful, or extremist content
    5 - Extreme toxicity; could cause significant harm
    Input Query: {input_query}
    Output Content: {output_content}
    '''
)
class ToxicityEvaluationPrompt(BasePrompt):
    input_query: str
    output_content: str

# ... (省略部分代码)

async def run_evals() -> list[Eval]:
    judges = [
        openai.call(
            "gpt-4o-mini",
            response_model=Eval,
            json_mode=True,
        ),
        anthropic.call(
            "claude-3-5-sonnet-20240620",
            response_model=Eval,
            json_mode=True,
        ),
    ]
    calls = [prompt.run_async(judge) for judge in judges]
    return await asyncio.gather(*calls)

evals = asyncio.run(run_evals())
for eval in evals:
    print(eval.model_dump())
# > {'score': 3.0, 'reasoning': 'Aggressive and demeaning language.'}
# > {'score': 3.5, 'reasoning': 'Demeaning and biased toward opposing views'}

这个例子展示了如何使用BasePrompt创建一个毒性评估提示,并使用不同的LLM提供商(OpenAI和Anthropic)异步运行评估。

Mirascope的优势

  1. 简洁优雅的API: Mirascope提供了简洁而强大的API,让开发者能够轻松构建复杂的LLM应用。
  2. 强大的类型支持: Mirascope特别注重提供正确的类型提示,这大大提高了开发效率和代码质量。
  3. 灵活性: 开发者可以根据需要选择不同的LLM提供商,并且可以轻松切换或组合使用多个提供商。
  4. 可扩展性: Mirascope的设计允许轻松添加新的功能和提供商支持。
  5. 性能: 通过提供异步支持和流式处理,Mirascope能够处理高性能的LLM应用需求。
  6. 易于集成: Mirascope可以轻松集成到现有的Python项目中,特别是与FastAPI等框架的集成非常简单。

Mirascope Performance

使用示例

Mirascope提供了丰富的示例,展示了如何使用库的各种功能。以下是一个简单的聊天机器人示例:

from mirascope.core import openai, prompt_template
from openai.types.chat import ChatCompletionMessageParam
from pydantic import BaseModel

class Chatbot(BaseModel):
    history: list[ChatCompletionMessageParam] = []

    @openai.call(model="gpt-4o-mini", stream=True)
    @prompt_template(
        '''
        SYSTEM: You are a helpful assistant.
        MESSAGES: {self.history}
        USER: {question}
        '''
    )
    def _call(self, question: str): ...

    def run(self):
        while True:
            question = input("(User): ")
            if question in ["quit", "exit"]:
                print("(Assistant): Have a great day!")
                break
            stream = self._call(question)
            print("(Assistant): ", end="", flush=True)
            for chunk, _ in stream:
                print(chunk.content, end="", flush=True)
            print("")
            if stream.user_message_param:
                self.history.append(stream.user_message_param)
            self.history.append(stream.message_param)

Chatbot().run()

这个例子展示了如何使用Mirascope创建一个简单的交互式聊天机器人,它使用OpenAI的模型,支持流式响应,并维护对话历史。

版本控制和许可

Mirascope使用语义化版本控制来管理版本。这意味着开发者可以依赖稳定的API,同时也能够及时获得新功能和改进。

Mirascope采用MIT许可证发布,这是一个非常宽松的开源许可证,允许开发者在各种项目中自由使用Mirascope,包括商业项目。

结论

Mirascope为Python开发者提供了一个强大、灵活且易用的LLM开发库。通过提供恰到好处的抽象和丰富的功能,Mirascope使得构建复杂的LLM应用变得简单有趣。无论是构建简单的聊天机器人,还是复杂的多模态AI系统,Mirascope都能够满足开发者的需求。

文章链接:www.dongaigc.com/a/mirascope-elegant-simple-python-llm-library
https://www.dongaigc.com/a/mirascope-elegant-simple-python-llm-library

https://www.dongaigc.com/p/Mirascope/mirascope

www.dongaigc.com/p/Mirascope/mirascope

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值