
Проверьте, оцените и контролируйте приложение для ИИ
? Twitter/x • ? Discord • Parea ai • ? Документация
Parea AI предоставляет SDK для оценки и мониторинга ваших приложений AI. Ниже вы можете увидеть QuickStarts:
Наши полные документы здесь.
pip install -U parea-ai или установить с Poetry
poetry add parea-aiТестирование вашего приложения для ИИ означает выполнение его по набору данных и оценить его с помощью функции оценки. Это делается в Parea путем определения и проведения экспериментов. Ниже вы можете увидеть пример того, как проверить приветствующий бот с метрикой расстояния Levenshtein.
from parea import Parea , trace
from parea . evals . general import levenshtein
p = Parea ( api_key = "<<PAREA_API_KEY>>" ) # replace with Parea AI API key
# use the trace decorator to score the output with the Levenshtein distance
@ trace ( eval_funcs = [ levenshtein ])
def greeting ( name : str ) -> str :
return f"Hello { name } "
data = [
{ "name" : "Foo" , "target" : "Hi Foo" },
{ "name" : "Bar" , "target" : "Hello Bar" },
]
p . experiment (
name = "Greeting" ,
data = data ,
func = greeting ,
). run () В приведенном выше фрагменте мы использовали декоратор trace , чтобы захватить любые входы и выходы функции. Этот декоратор также позволяет набрать результат, выполнив Eval levenshtein Eval на заднем плане. Затем мы определили эксперимент через p.experiment для оценки нашей функции ( greeting ) по набору данных (здесь список словарей). Наконец, вызов run выполнит эксперимент и создаст отчет о выходах, оценках и трассах для любой выборки набора данных. Вы можете найти ссылку на выполненный эксперимент здесь. (TODO: эксперимент заполнения)
Узнайте больше о том, как писать, запустить и анализировать эксперименты в наших документах.
Обертывая соответствующих клиентов, вы можете автоматически регистрировать все ваши вызовы LLM в Openai & Anpropic. Кроме того, используя декоратор trace вы можете создать иерархические следы вашего приложения LLM для EG Associate LLM -вызовов с шагом поиска тряпичного трубопровода. Вы можете увидеть полную документацию по наблюдению здесь и наши интеграции в Langchain, инструктор, DSPY, Litellm и многое другое здесь.
Чтобы автоматически регистрировать любой вызов Openai, вы можете обернуть клиент Openai с клиентом Parea, используя метод wrap_openai_client .
from openai import OpenAI
from parea import Parea
client = OpenAI ( api_key = "OPENAI_API_KEY" )
# All you need to do is add these two lines
p = Parea ( api_key = "PAREA_API_KEY" ) # replace with your API key
p . wrap_openai_client ( client )
response = client . chat . completions . create (
model = "gpt-4o" ,
messages = [
{
"role" : "user" ,
"content" : "Write a Hello World program in Python using FastAPI." ,
}
],
)
print ( response . choices [ 0 ]. message . content ) Чтобы автоматически регистрировать любой антропный вызов, вы можете обернуть антропный клиент с клиентом PAREA, используя метод wrap_anthropic_client .
import anthropic
from parea import Parea
p = Parea ( api_key = "PAREA_API_KEY" ) # replace with your API key
client = anthropic . Anthropic ()
p . wrap_anthropic_client ( client )
message = client . messages . create (
model = "claude-3-opus-20240229" ,
max_tokens = 1024 ,
messages = [
{
"role" : "user" ,
"content" : "Write a Hello World program in Python using FastAPI." ,
}
],
)
print ( message . content [ 0 ]. text ) Используя trace Decorator, вы можете создать иерархические следы вашего приложения LLM.
from openai import OpenAI
from parea import Parea , trace
client = OpenAI ( api_key = "OPENAI_API_KEY" ) # replace with your API key
p = Parea ( api_key = "PAREA_API_KEY" ) # replace with your API key
p . wrap_openai_client ( client )
# We generally recommend creating a helper function to make LLM API calls.
def llm ( messages : list [ dict [ str , str ]]) -> str :
response = client . chat . completions . create ( model = "gpt-4o" , messages = messages )
return response . choices [ 0 ]. message . content
# This will give the Span the name of the function.
# Without the decorator the default name for all LLM call logs is `llm-openai`
@ trace
def hello_world ( lang : str , framework : str ):
return llm ([{ "role" : "user" , "content" : f"Write a Hello World program in { lang } using { framework } ." }])
@ trace
def critique_code ( code : str ):
return llm ([{ "role" : "user" , "content" : f"How can we improve this code: n { code } " }])
# Our top level function is called chain. By adding the trace decorator here,
# all sub-functions will automatically be logged and associated with this trace.
# Notice, you can also add metadata to the trace, we'll revisit this functionality later.
@ trace ( metadata = { "purpose" : "example" }, end_user_identifier = "John Doe" )
def chain ( lang : str , framework : str ) -> str :
return critique_code ( hello_world ( lang , framework ))
print ( chain ( "Python" , "FastAPI" ))Развернутые подсказки обеспечивают сотрудничество с не инженерами, такими как менеджеры по продуктам и эксперты по предмету. Пользователи могут итерации, уточнить и тестировать подсказки на детской площадке Parea. После Tinkering вы можете развернуть эту подсказку, что означает, что она выставлена через конечную точку API для интеграции в ваше приложение. Проверьте наши полные документы здесь.
from parea import Parea
from parea . schemas . models import Completion , UseDeployedPrompt , CompletionResponse , UseDeployedPromptResponse
p = Parea ( api_key = "<PAREA_API_KEY>" )
# You will find this deployment_id in the Parea dashboard
deployment_id = '<DEPLOYMENT_ID>'
# Assuming your deployed prompt's message is:
# {"role": "user", "content": "Write a hello world program using {{x}} and the {{y}} framework."}
inputs = { "x" : "Golang" , "y" : "Fiber" }
# You can easily unpack a dictionary into an attrs class
test_completion = Completion (
** {
"deployment_id" : deployment_id ,
"llm_inputs" : inputs ,
"metadata" : { "purpose" : "testing" }
}
)
# By passing in my inputs, in addition to the raw message with unfilled variables {{x}} and {{y}},
# you we will also get the filled-in prompt:
# {"role": "user", "content": "Write a hello world program using Golang and the Fiber framework."}
test_get_prompt = UseDeployedPrompt ( deployment_id = deployment_id , llm_inputs = inputs )
def main ():
completion_response : CompletionResponse = p . completion ( data = test_completion )
print ( completion_response )
deployed_prompt : UseDeployedPromptResponse = p . get_prompt ( data = test_get_prompt )
print ( " n n " )
print ( deployed_prompt ) Этот проект лицензирован в соответствии с условиями лицензии Apache Software License 2.0 . Смотрите лицензию для более подробной информации.
@misc { parea-sdk ,
author = { joel-parea-ai,joschkabraun } ,
title = { Parea python sdk } ,
year = { 2023 } ,
publisher = { GitHub } ,
journal = { GitHub repository } ,
howpublished = { url{https://github.com/parea-ai/parea-sdk} }
}