Structured Outputs with Together AI¶
If you want to try this example using instructor hub
, you can pull it by running
Open-source LLMS are gaining popularity, and with the release of Together's Function calling models, its been easier than ever to get structured outputs.
By the end of this blog post, you will learn how to effectively utilize instructor with Together AI. But before we proceed, let's first explore the concept of patching.
Other Languages
This blog post is written in Python, but the concepts are applicable to other languages as well, as we currently have support for Javascript, Elixir and PHP.
Patching¶
Instructor's patch enhances the openai api it with the following features:
response_model
increate
calls that returns a pydantic modelmax_retries
increate
calls that retries the call if it fails by using a backoff strategy
Learn More
To learn more, please refer to the docs. To understand the benefits of using Pydantic with Instructor, visit the tips and tricks section of the why use Pydantic page.
Together AI¶
The good news is that Together employs the same OpenAI client, and its models support some of these output modes too!
Getting access
If you want to try this out for yourself check out the Together AI website. You can get started here.
import os
import openai
from pydantic import BaseModel
import instructor
client = openai.OpenAI(
base_url="https://api.together.xyz/v1",
api_key=os.environ["TOGETHER_API_KEY"],
)
# By default, the patch function will patch the ChatCompletion.create and ChatCompletion.create methods to support the response_model parameter
client = instructor.from_openai(client, mode=instructor.Mode.TOOLS)
# Now, we can use the response_model parameter using only a base model
# rather than having to use the OpenAISchema class
class UserExtract(BaseModel):
name: str
age: int
user: UserExtract = client.chat.completions.create(
model="mistralai/Mixtral-8x7B-Instruct-v0.1",
response_model=UserExtract,
messages=[
{"role": "user", "content": "Extract jason is 25 years old"},
],
)
assert isinstance(user, UserExtract), "Should be instance of UserExtract"
assert user.name.lower() == "jason"
assert user.age == 25
print(user.model_dump_json(indent=2))
"""
{
"name": "jason",
"age": 25
}
"""
{
"name": "Jason",
"age": 25,
}
You can find more information about Together's function calling support here.