Skip to content

Commit

Permalink
Merge pull request #876 from parea-ai/feat-add-instructor-blog-example
Browse files Browse the repository at this point in the history
docs: add more instructor cookbooks
  • Loading branch information
joschkabraun committed May 16, 2024
2 parents 61a8403 + d941edd commit acbf9e4
Show file tree
Hide file tree
Showing 5 changed files with 140 additions and 2 deletions.
67 changes: 67 additions & 0 deletions parea/cookbook/instructor/instructor_blog_example_simple.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import os
import re

import instructor
import requests
from dotenv import load_dotenv
from openai import OpenAI
from pydantic import BaseModel, Field, field_validator

from parea import Parea

load_dotenv()

client = OpenAI()

p = Parea(api_key=os.getenv("PAREA_API_KEY"))
p.wrap_openai_client(client, "instructor")

client = instructor.from_openai(client)


class Email(BaseModel):
subject: str
body: str = Field(
...,
description="Email body, Should contain links to instructor documentation. ",
)

@field_validator("body")
def check_urls(cls, v):
urls = re.findall(r"https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+", v)
errors = []
for url in urls:
if not url.startswith("https://python.useinstructor.com"):
errors.append(f"URL {url} is not from useinstructor.com, Only include URLs that include use instructor.com. ")
response = requests.get(url)
if response.status_code != 200:
errors.append(f"URL {url} returned status code {response.status_code}. Only include valid URLs that exist.")
elif "404" in response.text:
errors.append(f"URL {url} contained '404' in the body. Only include valid URLs that exist.")
if errors:
raise ValueError("\n".join(errors))
return v


def main():
email = client.messages.create(
model="gpt-3.5-turbo",
max_tokens=1024,
max_retries=3,
messages=[
{
"role": "user",
"content": "I'm responding to a student's question. Here is the link to the documentation: {{doc_link1}} and {{doc_link2}}",
}
],
template_inputs={
"doc_link1": "https://python.useinstructor.com/docs/tutorial/tutorial-1",
"doc_link2": "https://jxnl.github.io/docs/tutorial/tutorial-2",
},
response_model=Email,
)
print(email)


if __name__ == "__main__":
main()
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
from typing import Annotated

import os
import re

import instructor
import requests
from dotenv import load_dotenv
from openai import OpenAI
from pydantic import AfterValidator, BaseModel, ValidationInfo

from parea import Parea

load_dotenv()

client = OpenAI()

p = Parea(api_key=os.getenv("PAREA_API_KEY"))
p.wrap_openai_client(client, "instructor")

client = instructor.from_openai(client)


def check_urls(v, info: ValidationInfo):
urls = re.findall(r"https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+", v)
domain = info.context.get("domain") if info and info.context else None
errors = []
for url in urls:
if domain and not url.startswith(domain):
errors.append(f"URL {url} is not from useinstructor.com, Only include URLs that include use instructor.com. ")
response = requests.get(url)
if response.status_code != 200:
errors.append(f"URL {url} returned status code {response.status_code}. Only include valid URLs that exist.")
elif "404" in response.text:
errors.append(f"URL {url} contained '404' in the body. Only include valid URLs that exist.")
if errors:
raise ValueError("\n".join(errors))
return v


Body = Annotated[str, AfterValidator(check_urls)]


class Email(BaseModel):
subject: str
body: Body


def main():
email = client.messages.create(
model="gpt-3.5-turbo",
max_tokens=1024,
max_retries=3,
messages=[
{
"role": "user",
"content": "I'm responding to a student's question. Here is the link to the documentation: {{doc_link1}} and {{doc_link2}}",
}
],
template_inputs={
"doc_link1": "https://python.useinstructor.com/docs/tutorial/tutorial-1",
"doc_link2": "https://jxnl.github.io/docs/tutorial/tutorial-2",
},
response_model=Email,
validation_context={"domain": "https://python.useinstructor.com"},
)
print(email)


if __name__ == "__main__":
main()
File renamed without changes.
2 changes: 1 addition & 1 deletion parea/utils/trace_integrations/instructor.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def report_instructor_validation_errors() -> None:
if reason:
reason = "\n" + reason
instructor_score = EvaluationResult(
name="instruction_validation_error_count",
name="instructor_validation_error_count",
score=instructor_val_err_count.get(),
reason=reason,
)
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ build-backend = "poetry.core.masonry.api"
[tool.poetry]
name = "parea-ai"
packages = [{ include = "parea" }]
version = "0.2.153"
version = "0.2.154"
description = "Parea python sdk"
readme = "README.md"
authors = ["joel-parea-ai <[email protected]>"]
Expand Down

0 comments on commit acbf9e4

Please sign in to comment.