1

I want to return array of objects. Sample example

[     
  {"name": "abc", "last_name": "xyz"},
  {"name": "abcdef", "last_name": "xyz"}
]

I am referring to the structured output documentation

Need help on this.

2 Answers 2

1

The cleanest way to do this in Python is to extend the BaseModel class with the type of output class you want. In your example, you're looking to get a list of objects that have a name and last_name. So we can make a class Person, with these properties, and a PersonList class that is the output we want.

The "title" on each field is shared with the LLM so that it understands the desired output structure, so use an appropriate description for your use case.

from langchain_core.pydantic_v1 import BaseModel, Field
from typing import List

class Person(BaseModel):
    name: str = Field(None, title="Name of the person")
    last_name: str = Field(None, title="Last name of the person")


class PersonList(BaseModel):
    person_list: List[str] = Field(None, title="People")

Then, assuming you already have a prompt template, you can use LCEL to build your chain that returns a list of these Person objects.

people_chain = (people_prompt
                  | your_llm.with_structured_output(PersonList)
                  )

You can learn more and see what APIs support structured output in the docs here.

Sign up to request clarification or add additional context in comments.

1 Comment

This seems to imply that the response is a dictionary, that tends contains objects. For instance "queries: List[SomeSchema]". Pydantic doc is quite terse on lists though (docs.pydantic.dev/2.0/usage/types/list_types). For a list of native values, I've been using ast.literal_eval to safely parse the output string to an actual list.
0

I think you can use the structured schema like zod, (if you use javascript). we can simply create the schema as array like this

// We can use zod to define a schema for the output using the `fromZodSchema` method of `StructuredOutputParser`.
const parser = StructuredOutputParser.fromZodSchema(
  z.object({
    answer: z.string().describe("answer to the user's question"),
    sources: z
      .array(z.string())
      .describe("sources used to answer the question, should be websites."),
  })
);

Source: https://python.langchain.com/v0.1/docs/modules/model_io/output_parsers/types/json/ https://js.langchain.com/v0.1/docs/modules/model_io/output_parsers/types/structured/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.