From 5fc522c72ff4e45ed17c91b8a5123b7e91438bb2 Mon Sep 17 00:00:00 2001 From: Matt Apperson Date: Thu, 13 Nov 2025 10:56:25 -0500 Subject: [PATCH] Initial commit: OpenRouter Python SDK Auto-generated Python SDK for OpenRouter API, providing comprehensive client library with: - Chat completions and streaming support - Embeddings API - Model and provider information - API key management - Analytics and usage tracking - OAuth authentication flows - Full type hints and error handling --- .devcontainer/README.md | 30 + .devcontainer/devcontainer.json | 40 + .devcontainer/setup.sh | 14 + .gitattributes | 2 + .gitignore | 13 + .speakeasy/gen.lock | 1096 +++ .speakeasy/gen.yaml | 77 + .speakeasy/out.openapi.yaml | 8371 +++++++++++++++++ .speakeasy/workflow.lock | 34 + .speakeasy/workflow.yaml | 19 + .vscode/settings.json | 6 + CONTRIBUTING.md | 26 + README.md | 1251 +++ USAGE.md | 153 + docs/errors/badgatewayresponseerror.md | 11 + docs/errors/badrequestresponseerror.md | 11 + docs/errors/chaterror.md | 8 + .../errors/edgenetworktimeoutresponseerror.md | 11 + docs/errors/forbiddenresponseerror.md | 11 + docs/errors/internalserverresponseerror.md | 11 + docs/errors/notfoundresponseerror.md | 11 + docs/errors/payloadtoolargeresponseerror.md | 11 + docs/errors/paymentrequiredresponseerror.md | 11 + .../errors/provideroverloadedresponseerror.md | 11 + docs/errors/requesttimeoutresponseerror.md | 11 + .../errors/serviceunavailableresponseerror.md | 11 + docs/errors/toomanyrequestsresponseerror.md | 11 + docs/errors/unauthorizedresponseerror.md | 11 + .../unprocessableentityresponseerror.md | 11 + docs/models/activityitem.md | 18 + docs/models/apitype.md | 11 + docs/models/architecture.md | 14 + docs/models/assistantmessage.md | 13 + docs/models/assistantmessagecontent.md | 17 + docs/models/badgatewayresponseerrordata.md | 12 + docs/models/badrequestresponseerrordata.md | 12 + docs/models/calldata.md | 17 + docs/models/chainid.md | 10 + docs/models/chatcompletionfinishreason.md | 12 + docs/models/chaterrorerror.md | 11 + docs/models/chatgenerationparams.md | 29 + ...enerationparamsresponseformatjsonobject.md | 8 + ...hatgenerationparamsresponseformatpython.md | 8 + .../chatgenerationparamsresponseformattext.md | 8 + ...chatgenerationparamsresponseformatunion.md | 35 + docs/models/chatgenerationparamsstop.md | 17 + docs/models/chatgenerationtokenusage.md | 12 + docs/models/chatmessagecontentitem.md | 29 + docs/models/chatmessagecontentitemaudio.md | 9 + .../chatmessagecontentitemaudioformat.md | 14 + .../chatmessagecontentitemaudioinputaudio.md | 9 + docs/models/chatmessagecontentitemimage.md | 9 + .../chatmessagecontentitemimagedetail.md | 10 + docs/models/chatmessagecontentitemtext.md | 9 + docs/models/chatmessagecontentitemvideo.md | 9 + docs/models/chatmessagetokenlogprob.md | 11 + docs/models/chatmessagetokenlogprobs.md | 9 + docs/models/chatmessagetoolcall.md | 10 + docs/models/chatmessagetoolcallfunction.md | 9 + docs/models/chatresponse.md | 14 + docs/models/chatresponsechoice.md | 11 + docs/models/chatstreamingchoice.md | 11 + docs/models/chatstreamingmessagechunk.md | 12 + docs/models/chatstreamingmessagechunkrole.md | 8 + docs/models/chatstreamingmessagetoolcall.md | 11 + .../chatstreamingmessagetoolcallfunction.md | 9 + docs/models/chatstreamingresponsechunk.md | 8 + docs/models/chatstreamingresponsechunkdata.md | 15 + .../models/chatstreamingresponsechunkerror.md | 9 + docs/models/chatstreamoptions.md | 8 + docs/models/code.md | 17 + docs/models/codeenum.md | 25 + docs/models/completionchoice.md | 11 + docs/models/completioncreateparams.md | 28 + ...ioncreateparamsresponseformatjsonobject.md | 8 + ...pletioncreateparamsresponseformatpython.md | 8 + ...ompletioncreateparamsresponseformattext.md | 8 + ...mpletioncreateparamsresponseformatunion.md | 35 + docs/models/completioncreateparamsstop.md | 17 + docs/models/completionfinishreason.md | 10 + docs/models/completionlogprobs.md | 11 + docs/models/completionresponse.md | 14 + docs/models/completiontokensdetails.md | 11 + docs/models/completionusage.md | 10 + docs/models/costdetails.md | 10 + .../createauthkeyscodecodechallengemethod.md | 11 + docs/models/createauthkeyscodedata.md | 12 + docs/models/createauthkeyscoderequest.md | 12 + docs/models/createauthkeyscoderesponse.md | 10 + docs/models/createchargerequest.md | 12 + docs/models/createcoinbasechargedata.md | 11 + docs/models/createcoinbasechargeresponse.md | 10 + docs/models/createcoinbasechargesecurity.md | 8 + docs/models/createembeddingsdata.md | 10 + docs/models/createembeddingsdatacollection.md | 14 + docs/models/createembeddingsignore.md | 17 + docs/models/createembeddingsmaxprice.md | 14 + docs/models/createembeddingsobject.md | 8 + docs/models/createembeddingsonly.md | 17 + docs/models/createembeddingsorder.md | 17 + docs/models/createembeddingsprovider.md | 18 + docs/models/createembeddingsrequest.md | 12 + docs/models/createembeddingsresponse.md | 17 + docs/models/createembeddingsresponsebody.md | 14 + docs/models/createembeddingssort.md | 12 + docs/models/createkeysdata.md | 28 + docs/models/createkeyslimitreset.md | 12 + docs/models/createkeysrequest.md | 12 + docs/models/createkeysresponse.md | 11 + docs/models/createresponsesresponse.md | 17 + docs/models/createresponsesresponsebody.md | 10 + docs/models/datacollection.md | 14 + docs/models/defaultparameters.md | 12 + docs/models/deletekeysrequest.md | 8 + docs/models/deletekeysresponse.md | 10 + .../edgenetworktimeoutresponseerrordata.md | 12 + docs/models/effort.md | 11 + docs/models/embedding.md | 17 + docs/models/encodingformat.md | 17 + docs/models/encodingformatbase64.md | 8 + docs/models/encodingformatfloat.md | 8 + docs/models/endpointslistendpointsresponse.md | 10 + docs/models/endpointstatus.md | 13 + docs/models/engine.md | 9 + ...ngeauthcodeforapikeycodechallengemethod.md | 11 + .../exchangeauthcodeforapikeyrequest.md | 10 + .../exchangeauthcodeforapikeyresponse.md | 11 + docs/models/filecitation.md | 11 + docs/models/filecitationtype.md | 8 + docs/models/filepath.md | 10 + docs/models/filepathtype.md | 8 + docs/models/forbiddenresponseerrordata.md | 12 + docs/models/getcreditsresponse.md | 9 + docs/models/getcurrentkeydata.md | 26 + docs/models/getcurrentkeyresponse.md | 10 + docs/models/getgenerationdata.md | 41 + docs/models/getgenerationrequest.md | 8 + docs/models/getgenerationresponse.md | 10 + docs/models/getkeydata.md | 28 + docs/models/getkeyrequest.md | 8 + docs/models/getkeyresponse.md | 10 + docs/models/getmodelsrequest.md | 9 + docs/models/getparametersdata.md | 11 + docs/models/getparametersprovider.md | 75 + docs/models/getparametersrequest.md | 10 + docs/models/getparametersresponse.md | 10 + docs/models/getparameterssecurity.md | 8 + docs/models/getuseractivityrequest.md | 8 + docs/models/getuseractivityresponse.md | 10 + docs/models/idfileparser.md | 8 + docs/models/idmoderation.md | 8 + docs/models/idweb.md | 8 + docs/models/ignore.md | 17 + docs/models/imagegenerationstatus.md | 11 + docs/models/imageurl.md | 9 + docs/models/input.md | 29 + docs/models/inputmodality.md | 12 + docs/models/inputtokensdetails.md | 8 + docs/models/instructtype.md | 31 + .../models/internalserverresponseerrordata.md | 12 + docs/models/jsonschemaconfig.md | 11 + docs/models/listdata.md | 26 + docs/models/listendpointsrequest.md | 9 + docs/models/listendpointsresponse.md | 15 + docs/models/listendpointszdrresponse.md | 10 + docs/models/listmodelsusersecurity.md | 8 + docs/models/listprovidersdata.md | 12 + docs/models/listprovidersresponse.md | 10 + docs/models/listrequest.md | 9 + docs/models/listresponse.md | 10 + docs/models/maxprice.md | 14 + docs/models/message.md | 35 + docs/models/messagecontent.md | 17 + docs/models/messagedeveloper.md | 10 + docs/models/metadata.md | 10 + docs/models/model.md | 22 + docs/models/modelarchitecture.md | 14 + docs/models/modelarchitectureinstructtype.md | 31 + docs/models/modelgroup.md | 28 + docs/models/modelscountresponse.md | 10 + docs/models/modelscountresponsedata.md | 10 + docs/models/modelslistresponse.md | 10 + docs/models/namedtoolchoice.md | 9 + docs/models/namedtoolchoicefunction.md | 8 + docs/models/notfoundresponseerrordata.md | 12 + docs/models/object.md | 8 + docs/models/objectembedding.md | 8 + docs/models/only.md | 17 + docs/models/openairesponsesannotation.md | 23 + docs/models/openairesponsesincludable.md | 12 + .../openairesponsesincompletedetails.md | 8 + docs/models/openairesponsesinputcontent1.md | 29 + docs/models/openairesponsesinputcontent2.md | 17 + docs/models/openairesponsesinputcontent3.md | 29 + .../openairesponsesinputfunctioncall.md | 13 + .../openairesponsesinputfunctioncalloutput.md | 12 + docs/models/openairesponsesinputmessage1.md | 10 + docs/models/openairesponsesinputmessage2.md | 11 + .../openairesponsesinputroleassistant.md | 8 + .../openairesponsesinputroledeveloper1.md | 8 + .../openairesponsesinputroledeveloper2.md | 8 + .../models/openairesponsesinputrolesystem1.md | 8 + .../models/openairesponsesinputrolesystem2.md | 8 + docs/models/openairesponsesinputroleunion1.md | 29 + docs/models/openairesponsesinputroleunion2.md | 23 + docs/models/openairesponsesinputroleuser1.md | 8 + docs/models/openairesponsesinputroleuser2.md | 8 + .../openairesponsesinputtypefunctioncall.md | 8 + ...nairesponsesinputtypefunctioncalloutput.md | 8 + .../openairesponsesinputtypemessage1.md | 8 + .../openairesponsesinputtypemessage2.md | 8 + docs/models/openairesponsesinputunion.md | 23 + docs/models/openairesponsesinputunion1.md | 41 + docs/models/openairesponsesprompt.md | 9 + docs/models/openairesponsesreasoningconfig.md | 9 + docs/models/openairesponsesreasoningeffort.md | 11 + docs/models/openairesponsesrefusalcontent.md | 9 + .../openairesponsesrefusalcontenttype.md | 8 + docs/models/openairesponsesresponsestatus.md | 13 + docs/models/openairesponsesservicetier.md | 12 + docs/models/openairesponsestoolchoice.md | 8 + docs/models/openairesponsestoolchoiceauto.md | 8 + .../openairesponsestoolchoicefunction.md | 9 + docs/models/openairesponsestoolchoicenone.md | 8 + .../openairesponsestoolchoicerequired.md | 8 + .../openairesponsestoolchoicetypefunction.md | 8 + ...responsestoolchoicetypewebsearchpreview.md | 8 + ...stoolchoicetypewebsearchpreview20250311.md | 8 + docs/models/openairesponsestoolchoiceunion.md | 35 + docs/models/openairesponsestruncation.md | 9 + docs/models/openresponseseasyinputmessage.md | 10 + .../openresponseseasyinputmessagecontent1.md | 29 + .../openresponseseasyinputmessagecontent2.md | 17 + ...nresponseseasyinputmessageroleassistant.md | 8 + ...nresponseseasyinputmessageroledeveloper.md | 8 + ...openresponseseasyinputmessagerolesystem.md | 8 + .../openresponseseasyinputmessageroleunion.md | 29 + .../openresponseseasyinputmessageroleuser.md | 8 + .../openresponseseasyinputmessagetype.md | 8 + docs/models/openresponseserrorevent.md | 14 + docs/models/openresponseserroreventtype.md | 8 + .../models/openresponsesfunctioncalloutput.md | 14 + .../openresponsesfunctioncalloutputtype.md | 8 + docs/models/openresponsesfunctiontoolcall.md | 15 + .../openresponsesfunctiontoolcalltype.md | 8 + .../openresponsesimagegencallcompleted.md | 13 + .../openresponsesimagegencallcompletedtype.md | 8 + .../openresponsesimagegencallgenerating.md | 13 + ...openresponsesimagegencallgeneratingtype.md | 8 + .../openresponsesimagegencallinprogress.md | 13 + ...openresponsesimagegencallinprogresstype.md | 8 + .../openresponsesimagegencallpartialimage.md | 15 + ...enresponsesimagegencallpartialimagetype.md | 8 + docs/models/openresponsesinput.md | 19 + docs/models/openresponsesinput1.md | 71 + docs/models/openresponsesinputmessageitem.md | 11 + .../openresponsesinputmessageitemcontent.md | 29 + ...nresponsesinputmessageitemroledeveloper.md | 8 + ...openresponsesinputmessageitemrolesystem.md | 8 + .../openresponsesinputmessageitemroleunion.md | 23 + .../openresponsesinputmessageitemroleuser.md | 8 + .../openresponsesinputmessageitemtype.md | 8 + docs/models/openresponseslogprobs.md | 12 + .../openresponsesnonstreamingresponse.md | 40 + ...sponsesnonstreamingresponsetoolfunction.md | 14 + ...nresponsesnonstreamingresponsetoolunion.md | 35 + .../openresponsesnonstreamingresponsetype.md | 8 + docs/models/openresponsesreasoning.md | 17 + docs/models/openresponsesreasoningconfig.md | 13 + .../openresponsesreasoningdeltaevent.md | 15 + .../openresponsesreasoningdeltaeventtype.md | 8 + .../models/openresponsesreasoningdoneevent.md | 15 + .../openresponsesreasoningdoneeventtype.md | 8 + docs/models/openresponsesreasoningformat.md | 11 + .../openresponsesreasoningstatuscompleted.md | 8 + .../openresponsesreasoningstatusincomplete.md | 8 + .../openresponsesreasoningstatusinprogress.md | 8 + .../openresponsesreasoningstatusunion.md | 23 + ...responsesreasoningsummarypartaddedevent.md | 15 + ...onsesreasoningsummarypartaddedeventtype.md | 8 + ...responsesreasoningsummarytextdeltaevent.md | 15 + ...onsesreasoningsummarytextdeltaeventtype.md | 8 + ...nresponsesreasoningsummarytextdoneevent.md | 15 + ...ponsesreasoningsummarytextdoneeventtype.md | 8 + docs/models/openresponsesreasoningtype.md | 8 + docs/models/openresponsesrequest.md | 36 + .../openresponsesrequesttoolfunction.md | 14 + docs/models/openresponsesrequesttoolunion.md | 35 + docs/models/openresponsesrequesttype.md | 8 + docs/models/openresponsesresponsetext.md | 11 + .../openresponsesresponsetextverbosity.md | 10 + docs/models/openresponsesstreamevent.md | 169 + ...enresponsesstreameventresponsecompleted.md | 12 + ...nsesstreameventresponsecontentpartadded.md | 15 + ...onsesstreameventresponsecontentpartdone.md | 15 + ...openresponsesstreameventresponsecreated.md | 12 + .../openresponsesstreameventresponsefailed.md | 12 + ...eventresponsefunctioncallargumentsdelta.md | 14 + ...meventresponsefunctioncallargumentsdone.md | 15 + ...nresponsesstreameventresponseincomplete.md | 12 + ...nresponsesstreameventresponseinprogress.md | 12 + ...onsesstreameventresponseoutputitemadded.md | 13 + ...ponsesstreameventresponseoutputitemdone.md | 13 + ...meventresponseoutputtextannotationadded.md | 16 + ...onsesstreameventresponseoutputtextdelta.md | 16 + ...ponsesstreameventresponseoutputtextdone.md | 16 + ...ameventresponsereasoningsummarypartdone.md | 15 + ...esponsesstreameventresponserefusaldelta.md | 15 + ...responsesstreameventresponserefusaldone.md | 15 + docs/models/openresponsestoplogprobs.md | 11 + docs/models/openresponsesusage.md | 17 + .../openresponseswebsearch20250826tool.md | 13 + ...enresponseswebsearch20250826toolfilters.md | 8 + .../openresponseswebsearch20250826tooltype.md | 8 + ...enresponseswebsearchpreview20250311tool.md | 12 + ...sponseswebsearchpreview20250311tooltype.md | 8 + .../openresponseswebsearchpreviewtool.md | 12 + .../openresponseswebsearchpreviewtooltype.md | 8 + docs/models/openresponseswebsearchtool.md | 13 + .../openresponseswebsearchtoolfilters.md | 8 + docs/models/openresponseswebsearchtooltype.md | 8 + docs/models/order.md | 17 + docs/models/outputitemimagegenerationcall.md | 11 + .../outputitemimagegenerationcalltype.md | 8 + docs/models/outputmessage.md | 12 + docs/models/outputmessagecontent.md | 17 + docs/models/outputmessagerole.md | 8 + docs/models/outputmessagestatuscompleted.md | 8 + docs/models/outputmessagestatusincomplete.md | 8 + docs/models/outputmessagestatusinprogress.md | 8 + docs/models/outputmessagestatusunion.md | 23 + docs/models/outputmessagetype.md | 8 + docs/models/outputmodality.md | 10 + docs/models/outputtokensdetails.md | 8 + docs/models/parameter.md | 30 + docs/models/part1.md | 23 + docs/models/part2.md | 23 + .../payloadtoolargeresponseerrordata.md | 12 + .../paymentrequiredresponseerrordata.md | 12 + docs/models/pdf.md | 8 + docs/models/pdfengine.md | 10 + docs/models/perrequestlimits.md | 11 + docs/models/plugin.md | 23 + docs/models/pluginfileparser.md | 10 + docs/models/pluginmoderation.md | 8 + docs/models/pluginweb.md | 11 + docs/models/pricing.md | 19 + docs/models/prompt.md | 29 + docs/models/prompttokensdetails.md | 10 + docs/models/provider.md | 20 + docs/models/providername.md | 93 + .../provideroverloadedresponseerrordata.md | 12 + docs/models/publicendpoint.md | 22 + docs/models/publicendpointquantization.md | 16 + docs/models/publicpricing.md | 21 + docs/models/quantization.md | 16 + docs/models/ratelimit.md | 14 + docs/models/reason.md | 9 + docs/models/reasoning.md | 9 + docs/models/reasoningsummarytext.md | 9 + docs/models/reasoningsummarytexttype.md | 8 + docs/models/reasoningsummaryverbosity.md | 10 + docs/models/reasoningtextcontent.md | 9 + docs/models/reasoningtextcontenttype.md | 8 + .../models/requesttimeoutresponseerrordata.md | 12 + docs/models/responseformatjsonschema.md | 9 + docs/models/responseformattextconfig.md | 25 + docs/models/responseformattextgrammar.md | 9 + docs/models/responseinputaudio.md | 11 + docs/models/responseinputaudioformat.md | 9 + docs/models/responseinputaudioinputaudio.md | 9 + docs/models/responseinputaudiotype.md | 8 + docs/models/responseinputfile.md | 14 + docs/models/responseinputfiletype.md | 8 + docs/models/responseinputimage.md | 12 + docs/models/responseinputimagedetail.md | 10 + docs/models/responseinputimagetype.md | 8 + docs/models/responseinputtext.md | 11 + docs/models/responseinputtexttype.md | 8 + docs/models/responseoutputtext.md | 10 + docs/models/responseoutputtexttype.md | 8 + docs/models/responseserrorfield.md | 11 + docs/models/responsesformatjsonobject.md | 10 + docs/models/responsesformatjsonobjecttype.md | 8 + docs/models/responsesformattext.md | 10 + .../responsesformattextjsonschemaconfig.md | 14 + ...responsesformattextjsonschemaconfigtype.md | 8 + docs/models/responsesformattexttype.md | 8 + docs/models/responsesimagegenerationcall.md | 11 + .../responsesimagegenerationcalltype.md | 8 + docs/models/responsesoutputitem.md | 43 + .../responsesoutputitemfilesearchcall.md | 11 + .../responsesoutputitemfilesearchcalltype.md | 8 + .../models/responsesoutputitemfunctioncall.md | 13 + ...esoutputitemfunctioncallstatuscompleted.md | 8 + ...soutputitemfunctioncallstatusincomplete.md | 8 + ...soutputitemfunctioncallstatusinprogress.md | 8 + ...ponsesoutputitemfunctioncallstatusunion.md | 23 + .../responsesoutputitemfunctioncalltype.md | 8 + docs/models/responsesoutputitemreasoning.md | 15 + ...onsesoutputitemreasoningstatuscompleted.md | 8 + ...nsesoutputitemreasoningstatusincomplete.md | 8 + ...nsesoutputitemreasoningstatusinprogress.md | 8 + ...responsesoutputitemreasoningstatusunion.md | 23 + .../responsesoutputitemreasoningtype.md | 8 + docs/models/responsesoutputmessage.md | 14 + docs/models/responsesoutputmessagecontent.md | 17 + docs/models/responsesoutputmessagerole.md | 8 + .../responsesoutputmessagestatuscompleted.md | 8 + .../responsesoutputmessagestatusincomplete.md | 8 + .../responsesoutputmessagestatusinprogress.md | 8 + .../responsesoutputmessagestatusunion.md | 23 + docs/models/responsesoutputmessagetype.md | 8 + docs/models/responsessearchcontextsize.md | 12 + docs/models/responseswebsearchcalloutput.md | 10 + .../responseswebsearchcalloutputtype.md | 8 + docs/models/responseswebsearchuserlocation.md | 14 + .../responseswebsearchuserlocationtype.md | 8 + docs/models/responsetextconfig.md | 11 + docs/models/responsetextconfigverbosity.md | 10 + docs/models/security.md | 8 + .../sendchatcompletionrequestresponse.md | 17 + docs/models/servicetier.md | 12 + .../serviceunavailableresponseerrordata.md | 12 + docs/models/sort.md | 12 + docs/models/streamoptions.md | 8 + docs/models/supportedparameter.md | 30 + docs/models/systemmessage.md | 10 + docs/models/systemmessagecontent.md | 17 + docs/models/tokenizer.md | 28 + docs/models/toolcallstatus.md | 10 + docs/models/tooldefinitionjson.md | 9 + docs/models/tooldefinitionjsonfunction.md | 11 + docs/models/toolresponsemessage.md | 10 + docs/models/toolresponsemessagecontent.md | 17 + .../toomanyrequestsresponseerrordata.md | 12 + docs/models/toplogprob.md | 10 + docs/models/topproviderinfo.md | 12 + docs/models/transferintent.md | 9 + docs/models/truncation.md | 9 + docs/models/type.md | 17 + docs/models/typeresponsecompleted.md | 8 + docs/models/typeresponsecontentpartadded.md | 8 + docs/models/typeresponsecontentpartdone.md | 8 + docs/models/typeresponsecreated.md | 8 + docs/models/typeresponsefailed.md | 8 + .../typeresponsefunctioncallargumentsdelta.md | 8 + .../typeresponsefunctioncallargumentsdone.md | 8 + docs/models/typeresponseincomplete.md | 8 + docs/models/typeresponseinprogress.md | 8 + docs/models/typeresponseoutputitemadded.md | 8 + docs/models/typeresponseoutputitemdone.md | 8 + .../typeresponseoutputtextannotationadded.md | 8 + docs/models/typeresponseoutputtextdelta.md | 8 + docs/models/typeresponseoutputtextdone.md | 8 + .../typeresponsereasoningsummarypartdone.md | 8 + docs/models/typeresponserefusaldelta.md | 8 + docs/models/typeresponserefusaldone.md | 8 + docs/models/unauthorizedresponseerrordata.md | 12 + .../unprocessableentityresponseerrordata.md | 12 + docs/models/updatekeysdata.md | 28 + docs/models/updatekeyslimitreset.md | 12 + docs/models/updatekeysrequest.md | 9 + docs/models/updatekeysrequestbody.md | 12 + docs/models/updatekeysresponse.md | 10 + docs/models/urlcitation.md | 12 + docs/models/urlcitationtype.md | 8 + docs/models/usage.md | 10 + docs/models/usermessage.md | 10 + docs/models/usermessagecontent.md | 17 + docs/models/utils/retryconfig.md | 24 + docs/models/variables.md | 29 + docs/models/videourl.md | 8 + docs/models/web3data.md | 8 + .../websearchpreviewtooluserlocation.md | 12 + .../websearchpreviewtooluserlocationtype.md | 8 + docs/models/websearchstatus.md | 11 + docs/sdks/analytics/README.md | 54 + docs/sdks/apikeys/README.md | 287 + docs/sdks/chat/README.md | 73 + docs/sdks/completions/README.md | 70 + docs/sdks/credits/README.md | 100 + docs/sdks/embeddings/README.md | 123 + docs/sdks/endpoints/README.md | 94 + docs/sdks/generations/README.md | 58 + docs/sdks/models/README.md | 137 + docs/sdks/oauth/README.md | 103 + docs/sdks/parameters/README.md | 56 + docs/sdks/providers/README.md | 50 + docs/sdks/responses/README.md | 145 + py.typed | 1 + pylintrc | 663 ++ pyproject.toml | 52 + scripts/publish.sh | 4 + src/openrouter/__init__.py | 17 + src/openrouter/_hooks/__init__.py | 5 + src/openrouter/_hooks/registration.py | 13 + src/openrouter/_hooks/sdkhooks.py | 76 + src/openrouter/_hooks/types.py | 112 + src/openrouter/_version.py | 15 + src/openrouter/analytics.py | 229 + src/openrouter/api_keys.py | 1332 +++ src/openrouter/basesdk.py | 368 + src/openrouter/beta.py | 21 + src/openrouter/chat.py | 751 ++ src/openrouter/completions.py | 359 + src/openrouter/credits.py | 453 + src/openrouter/embeddings.py | 567 ++ src/openrouter/endpoints.py | 383 + src/openrouter/errors/__init__.py | 177 + .../errors/badgatewayresponse_error.py | 36 + .../errors/badrequestresponse_error.py | 36 + src/openrouter/errors/chaterror.py | 29 + .../edgenetworktimeoutresponse_error.py | 38 + .../errors/forbiddenresponse_error.py | 36 + .../errors/internalserverresponse_error.py | 36 + src/openrouter/errors/no_response_error.py | 17 + .../errors/notfoundresponse_error.py | 36 + .../errors/openrouterdefaulterror.py | 40 + src/openrouter/errors/openroutererror.py | 30 + .../errors/payloadtoolargeresponse_error.py | 36 + .../errors/paymentrequiredresponse_error.py | 36 + .../provideroverloadedresponse_error.py | 38 + .../errors/requesttimeoutresponse_error.py | 36 + .../errors/responsevalidationerror.py | 27 + .../serviceunavailableresponse_error.py | 38 + .../errors/toomanyrequestsresponse_error.py | 36 + .../errors/unauthorizedresponse_error.py | 36 + .../unprocessableentityresponse_error.py | 38 + src/openrouter/generations.py | 287 + src/openrouter/httpclient.py | 125 + src/openrouter/models/__init__.py | 2463 +++++ src/openrouter/models/activityitem.py | 66 + src/openrouter/models/assistantmessage.py | 88 + .../models/badgatewayresponseerrordata.py | 61 + .../models/badrequestresponseerrordata.py | 61 + .../models/chatcompletionfinishreason.py | 17 + src/openrouter/models/chaterror.py | 66 + src/openrouter/models/chatgenerationparams.py | 291 + .../models/chatgenerationtokenusage.py | 134 + .../models/chatmessagecontentitem.py | 45 + .../models/chatmessagecontentitemaudio.py | 55 + .../models/chatmessagecontentitemimage.py | 47 + .../models/chatmessagecontentitemtext.py | 23 + .../models/chatmessagecontentitemvideo.py | 33 + .../models/chatmessagetokenlogprob.py | 99 + .../models/chatmessagetokenlogprobs.py | 52 + src/openrouter/models/chatmessagetoolcall.py | 37 + src/openrouter/models/chatresponse.py | 83 + src/openrouter/models/chatresponsechoice.py | 69 + src/openrouter/models/chatstreamingchoice.py | 72 + .../models/chatstreamingmessagechunk.py | 70 + .../models/chatstreamingmessagetoolcall.py | 42 + .../models/chatstreamingresponsechunk.py | 105 + src/openrouter/models/chatstreamoptions.py | 14 + src/openrouter/models/completionchoice.py | 69 + .../models/completioncreateparams.py | 277 + src/openrouter/models/completionlogprobs.py | 54 + src/openrouter/models/completionresponse.py | 43 + src/openrouter/models/completionusage.py | 19 + src/openrouter/models/createauthkeyscodeop.py | 133 + src/openrouter/models/createchargerequest.py | 36 + .../models/createcoinbasechargeop.py | 121 + src/openrouter/models/createembeddingsop.py | 366 + src/openrouter/models/createkeysop.py | 255 + src/openrouter/models/createresponsesop.py | 53 + src/openrouter/models/defaultparameters.py | 60 + src/openrouter/models/deletekeysop.py | 38 + .../edgenetworktimeoutresponseerrordata.py | 61 + src/openrouter/models/endpointstatus.py | 18 + .../models/exchangeauthcodeforapikeyop.py | 130 + src/openrouter/models/filecitation.py | 26 + src/openrouter/models/filepath.py | 23 + .../models/forbiddenresponseerrordata.py | 61 + src/openrouter/models/getcreditsop.py | 13 + src/openrouter/models/getcurrentkeyop.py | 187 + src/openrouter/models/getgenerationop.py | 268 + src/openrouter/models/getkeyop.py | 180 + src/openrouter/models/getmodelsop.py | 24 + src/openrouter/models/getparametersop.py | 195 + src/openrouter/models/getuseractivityop.py | 37 + .../models/imagegenerationstatus.py | 16 + src/openrouter/models/inputmodality.py | 17 + src/openrouter/models/instructtype.py | 35 + .../models/internalserverresponseerrordata.py | 61 + src/openrouter/models/jsonschemaconfig.py | 61 + src/openrouter/models/listendpointsop.py | 36 + .../models/listendpointsresponse.py | 145 + src/openrouter/models/listendpointszdrop.py | 19 + src/openrouter/models/listmodelsuserop.py | 24 + src/openrouter/models/listop.py | 186 + src/openrouter/models/listprovidersop.py | 89 + src/openrouter/models/message.py | 68 + src/openrouter/models/model.py | 132 + src/openrouter/models/modelarchitecture.py | 122 + src/openrouter/models/modelgroup.py | 32 + src/openrouter/models/modelscountresponse.py | 33 + src/openrouter/models/modelslistresponse.py | 21 + src/openrouter/models/namedtoolchoice.py | 31 + .../models/notfoundresponseerrordata.py | 61 + .../models/openairesponsesannotation.py | 19 + .../models/openairesponsesincludable.py | 17 + .../openairesponsesincompletedetails.py | 27 + .../models/openairesponsesinput_union.py | 330 + .../models/openairesponsesprompt.py | 73 + .../models/openairesponsesreasoningconfig.py | 63 + .../models/openairesponsesreasoningeffort.py | 16 + .../models/openairesponsesrefusalcontent.py | 20 + .../models/openairesponsesresponsestatus.py | 18 + .../models/openairesponsesservicetier.py | 17 + .../models/openairesponsestoolchoice_union.py | 87 + .../models/openairesponsestruncation.py | 14 + .../models/openresponseseasyinputmessage.py | 97 + .../models/openresponseserrorevent.py | 64 + .../models/openresponsesfunctioncalloutput.py | 75 + .../models/openresponsesfunctiontoolcall.py | 78 + .../openresponsesimagegencallcompleted.py | 32 + .../openresponsesimagegencallgenerating.py | 32 + .../openresponsesimagegencallinprogress.py | 32 + .../openresponsesimagegencallpartialimage.py | 38 + src/openrouter/models/openresponsesinput.py | 97 + .../models/openresponsesinputmessageitem.py | 83 + .../models/openresponseslogprobs.py | 28 + .../openresponsesnonstreamingresponse.py | 324 + .../models/openresponsesreasoning.py | 137 + .../models/openresponsesreasoningconfig.py | 73 + .../openresponsesreasoningdeltaevent.py | 36 + .../models/openresponsesreasoningdoneevent.py | 36 + ...responsesreasoningsummarypartaddedevent.py | 39 + ...responsesreasoningsummarytextdeltaevent.py | 38 + ...nresponsesreasoningsummarytextdoneevent.py | 38 + src/openrouter/models/openresponsesrequest.py | 654 ++ .../models/openresponsesresponsetext.py | 83 + .../models/openresponsesstreamevent.py | 644 ++ .../models/openresponsestoplogprobs.py | 21 + src/openrouter/models/openresponsesusage.py | 140 + .../openresponseswebsearch20250826tool.py | 118 + ...enresponseswebsearchpreview20250311tool.py | 77 + .../openresponseswebsearchpreviewtool.py | 75 + .../models/openresponseswebsearchtool.py | 118 + .../models/outputitemimagegenerationcall.py | 60 + src/openrouter/models/outputmessage.py | 77 + src/openrouter/models/outputmodality.py | 15 + src/openrouter/models/parameter.py | 35 + .../payloadtoolargeresponseerrordata.py | 61 + .../paymentrequiredresponseerrordata.py | 61 + src/openrouter/models/perrequestlimits.py | 24 + src/openrouter/models/providername.py | 98 + .../provideroverloadedresponseerrordata.py | 61 + src/openrouter/models/publicendpoint.py | 180 + src/openrouter/models/publicpricing.py | 73 + src/openrouter/models/quantization.py | 21 + src/openrouter/models/reasoningsummarytext.py | 20 + .../models/reasoningsummaryverbosity.py | 15 + src/openrouter/models/reasoningtextcontent.py | 20 + .../models/requesttimeoutresponseerrordata.py | 61 + .../models/responseformatjsonschema.py | 26 + .../models/responseformattextconfig.py | 36 + .../models/responseformattextgrammar.py | 23 + src/openrouter/models/responseinputaudio.py | 50 + src/openrouter/models/responseinputfile.py | 70 + src/openrouter/models/responseinputimage.py | 79 + src/openrouter/models/responseinputtext.py | 24 + src/openrouter/models/responseoutputtext.py | 27 + src/openrouter/models/responseserrorfield.py | 48 + .../models/responsesformatjsonobject.py | 21 + src/openrouter/models/responsesformattext.py | 21 + .../responsesformattextjsonschemaconfig.py | 71 + .../models/responsesimagegenerationcall.py | 60 + src/openrouter/models/responsesoutputitem.py | 57 + .../responsesoutputitemfilesearchcall.py | 29 + .../models/responsesoutputitemfunctioncall.py | 61 + .../models/responsesoutputitemreasoning.py | 104 + .../models/responsesoutputmessage.py | 82 + .../models/responsessearchcontextsize.py | 16 + .../models/responseswebsearchcalloutput.py | 26 + .../models/responseswebsearchuserlocation.py | 70 + src/openrouter/models/responsetextconfig.py | 83 + src/openrouter/models/security.py | 25 + .../models/sendchatcompletionrequestop.py | 35 + .../serviceunavailableresponseerrordata.py | 61 + src/openrouter/models/systemmessage.py | 41 + src/openrouter/models/toolcallstatus.py | 15 + src/openrouter/models/tooldefinitionjson.py | 77 + src/openrouter/models/toolresponsemessage.py | 41 + .../toomanyrequestsresponseerrordata.py | 61 + src/openrouter/models/topproviderinfo.py | 66 + .../models/unauthorizedresponseerrordata.py | 61 + .../unprocessableentityresponseerrordata.py | 61 + src/openrouter/models/updatekeysop.py | 274 + src/openrouter/models/urlcitation.py | 29 + src/openrouter/models/usermessage.py | 40 + .../websearchpreviewtooluserlocation.py | 66 + src/openrouter/models/websearchstatus.py | 16 + src/openrouter/models_.py | 561 ++ src/openrouter/oauth.py | 486 + src/openrouter/parameters.py | 231 + src/openrouter/providers.py | 181 + src/openrouter/py.typed | 1 + src/openrouter/responses.py | 1107 +++ src/openrouter/sdk.py | 224 + src/openrouter/sdkconfiguration.py | 53 + src/openrouter/types/__init__.py | 21 + src/openrouter/types/basemodel.py | 39 + src/openrouter/utils/__init__.py | 200 + src/openrouter/utils/annotations.py | 79 + src/openrouter/utils/datetimes.py | 23 + src/openrouter/utils/enums.py | 74 + src/openrouter/utils/eventstreaming.py | 248 + src/openrouter/utils/forms.py | 223 + src/openrouter/utils/headers.py | 136 + src/openrouter/utils/logger.py | 27 + src/openrouter/utils/metadata.py | 118 + src/openrouter/utils/queryparams.py | 205 + src/openrouter/utils/requestbodies.py | 66 + src/openrouter/utils/retries.py | 217 + src/openrouter/utils/security.py | 192 + src/openrouter/utils/serializers.py | 249 + .../utils/unmarshal_json_response.py | 24 + src/openrouter/utils/url.py | 155 + src/openrouter/utils/values.py | 137 + 721 files changed, 45654 insertions(+) create mode 100644 .devcontainer/README.md create mode 100644 .devcontainer/devcontainer.json create mode 100644 .devcontainer/setup.sh create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 .speakeasy/gen.lock create mode 100644 .speakeasy/gen.yaml create mode 100644 .speakeasy/out.openapi.yaml create mode 100644 .speakeasy/workflow.lock create mode 100644 .speakeasy/workflow.yaml create mode 100644 .vscode/settings.json create mode 100644 CONTRIBUTING.md create mode 100644 README.md create mode 100644 USAGE.md create mode 100644 docs/errors/badgatewayresponseerror.md create mode 100644 docs/errors/badrequestresponseerror.md create mode 100644 docs/errors/chaterror.md create mode 100644 docs/errors/edgenetworktimeoutresponseerror.md create mode 100644 docs/errors/forbiddenresponseerror.md create mode 100644 docs/errors/internalserverresponseerror.md create mode 100644 docs/errors/notfoundresponseerror.md create mode 100644 docs/errors/payloadtoolargeresponseerror.md create mode 100644 docs/errors/paymentrequiredresponseerror.md create mode 100644 docs/errors/provideroverloadedresponseerror.md create mode 100644 docs/errors/requesttimeoutresponseerror.md create mode 100644 docs/errors/serviceunavailableresponseerror.md create mode 100644 docs/errors/toomanyrequestsresponseerror.md create mode 100644 docs/errors/unauthorizedresponseerror.md create mode 100644 docs/errors/unprocessableentityresponseerror.md create mode 100644 docs/models/activityitem.md create mode 100644 docs/models/apitype.md create mode 100644 docs/models/architecture.md create mode 100644 docs/models/assistantmessage.md create mode 100644 docs/models/assistantmessagecontent.md create mode 100644 docs/models/badgatewayresponseerrordata.md create mode 100644 docs/models/badrequestresponseerrordata.md create mode 100644 docs/models/calldata.md create mode 100644 docs/models/chainid.md create mode 100644 docs/models/chatcompletionfinishreason.md create mode 100644 docs/models/chaterrorerror.md create mode 100644 docs/models/chatgenerationparams.md create mode 100644 docs/models/chatgenerationparamsresponseformatjsonobject.md create mode 100644 docs/models/chatgenerationparamsresponseformatpython.md create mode 100644 docs/models/chatgenerationparamsresponseformattext.md create mode 100644 docs/models/chatgenerationparamsresponseformatunion.md create mode 100644 docs/models/chatgenerationparamsstop.md create mode 100644 docs/models/chatgenerationtokenusage.md create mode 100644 docs/models/chatmessagecontentitem.md create mode 100644 docs/models/chatmessagecontentitemaudio.md create mode 100644 docs/models/chatmessagecontentitemaudioformat.md create mode 100644 docs/models/chatmessagecontentitemaudioinputaudio.md create mode 100644 docs/models/chatmessagecontentitemimage.md create mode 100644 docs/models/chatmessagecontentitemimagedetail.md create mode 100644 docs/models/chatmessagecontentitemtext.md create mode 100644 docs/models/chatmessagecontentitemvideo.md create mode 100644 docs/models/chatmessagetokenlogprob.md create mode 100644 docs/models/chatmessagetokenlogprobs.md create mode 100644 docs/models/chatmessagetoolcall.md create mode 100644 docs/models/chatmessagetoolcallfunction.md create mode 100644 docs/models/chatresponse.md create mode 100644 docs/models/chatresponsechoice.md create mode 100644 docs/models/chatstreamingchoice.md create mode 100644 docs/models/chatstreamingmessagechunk.md create mode 100644 docs/models/chatstreamingmessagechunkrole.md create mode 100644 docs/models/chatstreamingmessagetoolcall.md create mode 100644 docs/models/chatstreamingmessagetoolcallfunction.md create mode 100644 docs/models/chatstreamingresponsechunk.md create mode 100644 docs/models/chatstreamingresponsechunkdata.md create mode 100644 docs/models/chatstreamingresponsechunkerror.md create mode 100644 docs/models/chatstreamoptions.md create mode 100644 docs/models/code.md create mode 100644 docs/models/codeenum.md create mode 100644 docs/models/completionchoice.md create mode 100644 docs/models/completioncreateparams.md create mode 100644 docs/models/completioncreateparamsresponseformatjsonobject.md create mode 100644 docs/models/completioncreateparamsresponseformatpython.md create mode 100644 docs/models/completioncreateparamsresponseformattext.md create mode 100644 docs/models/completioncreateparamsresponseformatunion.md create mode 100644 docs/models/completioncreateparamsstop.md create mode 100644 docs/models/completionfinishreason.md create mode 100644 docs/models/completionlogprobs.md create mode 100644 docs/models/completionresponse.md create mode 100644 docs/models/completiontokensdetails.md create mode 100644 docs/models/completionusage.md create mode 100644 docs/models/costdetails.md create mode 100644 docs/models/createauthkeyscodecodechallengemethod.md create mode 100644 docs/models/createauthkeyscodedata.md create mode 100644 docs/models/createauthkeyscoderequest.md create mode 100644 docs/models/createauthkeyscoderesponse.md create mode 100644 docs/models/createchargerequest.md create mode 100644 docs/models/createcoinbasechargedata.md create mode 100644 docs/models/createcoinbasechargeresponse.md create mode 100644 docs/models/createcoinbasechargesecurity.md create mode 100644 docs/models/createembeddingsdata.md create mode 100644 docs/models/createembeddingsdatacollection.md create mode 100644 docs/models/createembeddingsignore.md create mode 100644 docs/models/createembeddingsmaxprice.md create mode 100644 docs/models/createembeddingsobject.md create mode 100644 docs/models/createembeddingsonly.md create mode 100644 docs/models/createembeddingsorder.md create mode 100644 docs/models/createembeddingsprovider.md create mode 100644 docs/models/createembeddingsrequest.md create mode 100644 docs/models/createembeddingsresponse.md create mode 100644 docs/models/createembeddingsresponsebody.md create mode 100644 docs/models/createembeddingssort.md create mode 100644 docs/models/createkeysdata.md create mode 100644 docs/models/createkeyslimitreset.md create mode 100644 docs/models/createkeysrequest.md create mode 100644 docs/models/createkeysresponse.md create mode 100644 docs/models/createresponsesresponse.md create mode 100644 docs/models/createresponsesresponsebody.md create mode 100644 docs/models/datacollection.md create mode 100644 docs/models/defaultparameters.md create mode 100644 docs/models/deletekeysrequest.md create mode 100644 docs/models/deletekeysresponse.md create mode 100644 docs/models/edgenetworktimeoutresponseerrordata.md create mode 100644 docs/models/effort.md create mode 100644 docs/models/embedding.md create mode 100644 docs/models/encodingformat.md create mode 100644 docs/models/encodingformatbase64.md create mode 100644 docs/models/encodingformatfloat.md create mode 100644 docs/models/endpointslistendpointsresponse.md create mode 100644 docs/models/endpointstatus.md create mode 100644 docs/models/engine.md create mode 100644 docs/models/exchangeauthcodeforapikeycodechallengemethod.md create mode 100644 docs/models/exchangeauthcodeforapikeyrequest.md create mode 100644 docs/models/exchangeauthcodeforapikeyresponse.md create mode 100644 docs/models/filecitation.md create mode 100644 docs/models/filecitationtype.md create mode 100644 docs/models/filepath.md create mode 100644 docs/models/filepathtype.md create mode 100644 docs/models/forbiddenresponseerrordata.md create mode 100644 docs/models/getcreditsresponse.md create mode 100644 docs/models/getcurrentkeydata.md create mode 100644 docs/models/getcurrentkeyresponse.md create mode 100644 docs/models/getgenerationdata.md create mode 100644 docs/models/getgenerationrequest.md create mode 100644 docs/models/getgenerationresponse.md create mode 100644 docs/models/getkeydata.md create mode 100644 docs/models/getkeyrequest.md create mode 100644 docs/models/getkeyresponse.md create mode 100644 docs/models/getmodelsrequest.md create mode 100644 docs/models/getparametersdata.md create mode 100644 docs/models/getparametersprovider.md create mode 100644 docs/models/getparametersrequest.md create mode 100644 docs/models/getparametersresponse.md create mode 100644 docs/models/getparameterssecurity.md create mode 100644 docs/models/getuseractivityrequest.md create mode 100644 docs/models/getuseractivityresponse.md create mode 100644 docs/models/idfileparser.md create mode 100644 docs/models/idmoderation.md create mode 100644 docs/models/idweb.md create mode 100644 docs/models/ignore.md create mode 100644 docs/models/imagegenerationstatus.md create mode 100644 docs/models/imageurl.md create mode 100644 docs/models/input.md create mode 100644 docs/models/inputmodality.md create mode 100644 docs/models/inputtokensdetails.md create mode 100644 docs/models/instructtype.md create mode 100644 docs/models/internalserverresponseerrordata.md create mode 100644 docs/models/jsonschemaconfig.md create mode 100644 docs/models/listdata.md create mode 100644 docs/models/listendpointsrequest.md create mode 100644 docs/models/listendpointsresponse.md create mode 100644 docs/models/listendpointszdrresponse.md create mode 100644 docs/models/listmodelsusersecurity.md create mode 100644 docs/models/listprovidersdata.md create mode 100644 docs/models/listprovidersresponse.md create mode 100644 docs/models/listrequest.md create mode 100644 docs/models/listresponse.md create mode 100644 docs/models/maxprice.md create mode 100644 docs/models/message.md create mode 100644 docs/models/messagecontent.md create mode 100644 docs/models/messagedeveloper.md create mode 100644 docs/models/metadata.md create mode 100644 docs/models/model.md create mode 100644 docs/models/modelarchitecture.md create mode 100644 docs/models/modelarchitectureinstructtype.md create mode 100644 docs/models/modelgroup.md create mode 100644 docs/models/modelscountresponse.md create mode 100644 docs/models/modelscountresponsedata.md create mode 100644 docs/models/modelslistresponse.md create mode 100644 docs/models/namedtoolchoice.md create mode 100644 docs/models/namedtoolchoicefunction.md create mode 100644 docs/models/notfoundresponseerrordata.md create mode 100644 docs/models/object.md create mode 100644 docs/models/objectembedding.md create mode 100644 docs/models/only.md create mode 100644 docs/models/openairesponsesannotation.md create mode 100644 docs/models/openairesponsesincludable.md create mode 100644 docs/models/openairesponsesincompletedetails.md create mode 100644 docs/models/openairesponsesinputcontent1.md create mode 100644 docs/models/openairesponsesinputcontent2.md create mode 100644 docs/models/openairesponsesinputcontent3.md create mode 100644 docs/models/openairesponsesinputfunctioncall.md create mode 100644 docs/models/openairesponsesinputfunctioncalloutput.md create mode 100644 docs/models/openairesponsesinputmessage1.md create mode 100644 docs/models/openairesponsesinputmessage2.md create mode 100644 docs/models/openairesponsesinputroleassistant.md create mode 100644 docs/models/openairesponsesinputroledeveloper1.md create mode 100644 docs/models/openairesponsesinputroledeveloper2.md create mode 100644 docs/models/openairesponsesinputrolesystem1.md create mode 100644 docs/models/openairesponsesinputrolesystem2.md create mode 100644 docs/models/openairesponsesinputroleunion1.md create mode 100644 docs/models/openairesponsesinputroleunion2.md create mode 100644 docs/models/openairesponsesinputroleuser1.md create mode 100644 docs/models/openairesponsesinputroleuser2.md create mode 100644 docs/models/openairesponsesinputtypefunctioncall.md create mode 100644 docs/models/openairesponsesinputtypefunctioncalloutput.md create mode 100644 docs/models/openairesponsesinputtypemessage1.md create mode 100644 docs/models/openairesponsesinputtypemessage2.md create mode 100644 docs/models/openairesponsesinputunion.md create mode 100644 docs/models/openairesponsesinputunion1.md create mode 100644 docs/models/openairesponsesprompt.md create mode 100644 docs/models/openairesponsesreasoningconfig.md create mode 100644 docs/models/openairesponsesreasoningeffort.md create mode 100644 docs/models/openairesponsesrefusalcontent.md create mode 100644 docs/models/openairesponsesrefusalcontenttype.md create mode 100644 docs/models/openairesponsesresponsestatus.md create mode 100644 docs/models/openairesponsesservicetier.md create mode 100644 docs/models/openairesponsestoolchoice.md create mode 100644 docs/models/openairesponsestoolchoiceauto.md create mode 100644 docs/models/openairesponsestoolchoicefunction.md create mode 100644 docs/models/openairesponsestoolchoicenone.md create mode 100644 docs/models/openairesponsestoolchoicerequired.md create mode 100644 docs/models/openairesponsestoolchoicetypefunction.md create mode 100644 docs/models/openairesponsestoolchoicetypewebsearchpreview.md create mode 100644 docs/models/openairesponsestoolchoicetypewebsearchpreview20250311.md create mode 100644 docs/models/openairesponsestoolchoiceunion.md create mode 100644 docs/models/openairesponsestruncation.md create mode 100644 docs/models/openresponseseasyinputmessage.md create mode 100644 docs/models/openresponseseasyinputmessagecontent1.md create mode 100644 docs/models/openresponseseasyinputmessagecontent2.md create mode 100644 docs/models/openresponseseasyinputmessageroleassistant.md create mode 100644 docs/models/openresponseseasyinputmessageroledeveloper.md create mode 100644 docs/models/openresponseseasyinputmessagerolesystem.md create mode 100644 docs/models/openresponseseasyinputmessageroleunion.md create mode 100644 docs/models/openresponseseasyinputmessageroleuser.md create mode 100644 docs/models/openresponseseasyinputmessagetype.md create mode 100644 docs/models/openresponseserrorevent.md create mode 100644 docs/models/openresponseserroreventtype.md create mode 100644 docs/models/openresponsesfunctioncalloutput.md create mode 100644 docs/models/openresponsesfunctioncalloutputtype.md create mode 100644 docs/models/openresponsesfunctiontoolcall.md create mode 100644 docs/models/openresponsesfunctiontoolcalltype.md create mode 100644 docs/models/openresponsesimagegencallcompleted.md create mode 100644 docs/models/openresponsesimagegencallcompletedtype.md create mode 100644 docs/models/openresponsesimagegencallgenerating.md create mode 100644 docs/models/openresponsesimagegencallgeneratingtype.md create mode 100644 docs/models/openresponsesimagegencallinprogress.md create mode 100644 docs/models/openresponsesimagegencallinprogresstype.md create mode 100644 docs/models/openresponsesimagegencallpartialimage.md create mode 100644 docs/models/openresponsesimagegencallpartialimagetype.md create mode 100644 docs/models/openresponsesinput.md create mode 100644 docs/models/openresponsesinput1.md create mode 100644 docs/models/openresponsesinputmessageitem.md create mode 100644 docs/models/openresponsesinputmessageitemcontent.md create mode 100644 docs/models/openresponsesinputmessageitemroledeveloper.md create mode 100644 docs/models/openresponsesinputmessageitemrolesystem.md create mode 100644 docs/models/openresponsesinputmessageitemroleunion.md create mode 100644 docs/models/openresponsesinputmessageitemroleuser.md create mode 100644 docs/models/openresponsesinputmessageitemtype.md create mode 100644 docs/models/openresponseslogprobs.md create mode 100644 docs/models/openresponsesnonstreamingresponse.md create mode 100644 docs/models/openresponsesnonstreamingresponsetoolfunction.md create mode 100644 docs/models/openresponsesnonstreamingresponsetoolunion.md create mode 100644 docs/models/openresponsesnonstreamingresponsetype.md create mode 100644 docs/models/openresponsesreasoning.md create mode 100644 docs/models/openresponsesreasoningconfig.md create mode 100644 docs/models/openresponsesreasoningdeltaevent.md create mode 100644 docs/models/openresponsesreasoningdeltaeventtype.md create mode 100644 docs/models/openresponsesreasoningdoneevent.md create mode 100644 docs/models/openresponsesreasoningdoneeventtype.md create mode 100644 docs/models/openresponsesreasoningformat.md create mode 100644 docs/models/openresponsesreasoningstatuscompleted.md create mode 100644 docs/models/openresponsesreasoningstatusincomplete.md create mode 100644 docs/models/openresponsesreasoningstatusinprogress.md create mode 100644 docs/models/openresponsesreasoningstatusunion.md create mode 100644 docs/models/openresponsesreasoningsummarypartaddedevent.md create mode 100644 docs/models/openresponsesreasoningsummarypartaddedeventtype.md create mode 100644 docs/models/openresponsesreasoningsummarytextdeltaevent.md create mode 100644 docs/models/openresponsesreasoningsummarytextdeltaeventtype.md create mode 100644 docs/models/openresponsesreasoningsummarytextdoneevent.md create mode 100644 docs/models/openresponsesreasoningsummarytextdoneeventtype.md create mode 100644 docs/models/openresponsesreasoningtype.md create mode 100644 docs/models/openresponsesrequest.md create mode 100644 docs/models/openresponsesrequesttoolfunction.md create mode 100644 docs/models/openresponsesrequesttoolunion.md create mode 100644 docs/models/openresponsesrequesttype.md create mode 100644 docs/models/openresponsesresponsetext.md create mode 100644 docs/models/openresponsesresponsetextverbosity.md create mode 100644 docs/models/openresponsesstreamevent.md create mode 100644 docs/models/openresponsesstreameventresponsecompleted.md create mode 100644 docs/models/openresponsesstreameventresponsecontentpartadded.md create mode 100644 docs/models/openresponsesstreameventresponsecontentpartdone.md create mode 100644 docs/models/openresponsesstreameventresponsecreated.md create mode 100644 docs/models/openresponsesstreameventresponsefailed.md create mode 100644 docs/models/openresponsesstreameventresponsefunctioncallargumentsdelta.md create mode 100644 docs/models/openresponsesstreameventresponsefunctioncallargumentsdone.md create mode 100644 docs/models/openresponsesstreameventresponseincomplete.md create mode 100644 docs/models/openresponsesstreameventresponseinprogress.md create mode 100644 docs/models/openresponsesstreameventresponseoutputitemadded.md create mode 100644 docs/models/openresponsesstreameventresponseoutputitemdone.md create mode 100644 docs/models/openresponsesstreameventresponseoutputtextannotationadded.md create mode 100644 docs/models/openresponsesstreameventresponseoutputtextdelta.md create mode 100644 docs/models/openresponsesstreameventresponseoutputtextdone.md create mode 100644 docs/models/openresponsesstreameventresponsereasoningsummarypartdone.md create mode 100644 docs/models/openresponsesstreameventresponserefusaldelta.md create mode 100644 docs/models/openresponsesstreameventresponserefusaldone.md create mode 100644 docs/models/openresponsestoplogprobs.md create mode 100644 docs/models/openresponsesusage.md create mode 100644 docs/models/openresponseswebsearch20250826tool.md create mode 100644 docs/models/openresponseswebsearch20250826toolfilters.md create mode 100644 docs/models/openresponseswebsearch20250826tooltype.md create mode 100644 docs/models/openresponseswebsearchpreview20250311tool.md create mode 100644 docs/models/openresponseswebsearchpreview20250311tooltype.md create mode 100644 docs/models/openresponseswebsearchpreviewtool.md create mode 100644 docs/models/openresponseswebsearchpreviewtooltype.md create mode 100644 docs/models/openresponseswebsearchtool.md create mode 100644 docs/models/openresponseswebsearchtoolfilters.md create mode 100644 docs/models/openresponseswebsearchtooltype.md create mode 100644 docs/models/order.md create mode 100644 docs/models/outputitemimagegenerationcall.md create mode 100644 docs/models/outputitemimagegenerationcalltype.md create mode 100644 docs/models/outputmessage.md create mode 100644 docs/models/outputmessagecontent.md create mode 100644 docs/models/outputmessagerole.md create mode 100644 docs/models/outputmessagestatuscompleted.md create mode 100644 docs/models/outputmessagestatusincomplete.md create mode 100644 docs/models/outputmessagestatusinprogress.md create mode 100644 docs/models/outputmessagestatusunion.md create mode 100644 docs/models/outputmessagetype.md create mode 100644 docs/models/outputmodality.md create mode 100644 docs/models/outputtokensdetails.md create mode 100644 docs/models/parameter.md create mode 100644 docs/models/part1.md create mode 100644 docs/models/part2.md create mode 100644 docs/models/payloadtoolargeresponseerrordata.md create mode 100644 docs/models/paymentrequiredresponseerrordata.md create mode 100644 docs/models/pdf.md create mode 100644 docs/models/pdfengine.md create mode 100644 docs/models/perrequestlimits.md create mode 100644 docs/models/plugin.md create mode 100644 docs/models/pluginfileparser.md create mode 100644 docs/models/pluginmoderation.md create mode 100644 docs/models/pluginweb.md create mode 100644 docs/models/pricing.md create mode 100644 docs/models/prompt.md create mode 100644 docs/models/prompttokensdetails.md create mode 100644 docs/models/provider.md create mode 100644 docs/models/providername.md create mode 100644 docs/models/provideroverloadedresponseerrordata.md create mode 100644 docs/models/publicendpoint.md create mode 100644 docs/models/publicendpointquantization.md create mode 100644 docs/models/publicpricing.md create mode 100644 docs/models/quantization.md create mode 100644 docs/models/ratelimit.md create mode 100644 docs/models/reason.md create mode 100644 docs/models/reasoning.md create mode 100644 docs/models/reasoningsummarytext.md create mode 100644 docs/models/reasoningsummarytexttype.md create mode 100644 docs/models/reasoningsummaryverbosity.md create mode 100644 docs/models/reasoningtextcontent.md create mode 100644 docs/models/reasoningtextcontenttype.md create mode 100644 docs/models/requesttimeoutresponseerrordata.md create mode 100644 docs/models/responseformatjsonschema.md create mode 100644 docs/models/responseformattextconfig.md create mode 100644 docs/models/responseformattextgrammar.md create mode 100644 docs/models/responseinputaudio.md create mode 100644 docs/models/responseinputaudioformat.md create mode 100644 docs/models/responseinputaudioinputaudio.md create mode 100644 docs/models/responseinputaudiotype.md create mode 100644 docs/models/responseinputfile.md create mode 100644 docs/models/responseinputfiletype.md create mode 100644 docs/models/responseinputimage.md create mode 100644 docs/models/responseinputimagedetail.md create mode 100644 docs/models/responseinputimagetype.md create mode 100644 docs/models/responseinputtext.md create mode 100644 docs/models/responseinputtexttype.md create mode 100644 docs/models/responseoutputtext.md create mode 100644 docs/models/responseoutputtexttype.md create mode 100644 docs/models/responseserrorfield.md create mode 100644 docs/models/responsesformatjsonobject.md create mode 100644 docs/models/responsesformatjsonobjecttype.md create mode 100644 docs/models/responsesformattext.md create mode 100644 docs/models/responsesformattextjsonschemaconfig.md create mode 100644 docs/models/responsesformattextjsonschemaconfigtype.md create mode 100644 docs/models/responsesformattexttype.md create mode 100644 docs/models/responsesimagegenerationcall.md create mode 100644 docs/models/responsesimagegenerationcalltype.md create mode 100644 docs/models/responsesoutputitem.md create mode 100644 docs/models/responsesoutputitemfilesearchcall.md create mode 100644 docs/models/responsesoutputitemfilesearchcalltype.md create mode 100644 docs/models/responsesoutputitemfunctioncall.md create mode 100644 docs/models/responsesoutputitemfunctioncallstatuscompleted.md create mode 100644 docs/models/responsesoutputitemfunctioncallstatusincomplete.md create mode 100644 docs/models/responsesoutputitemfunctioncallstatusinprogress.md create mode 100644 docs/models/responsesoutputitemfunctioncallstatusunion.md create mode 100644 docs/models/responsesoutputitemfunctioncalltype.md create mode 100644 docs/models/responsesoutputitemreasoning.md create mode 100644 docs/models/responsesoutputitemreasoningstatuscompleted.md create mode 100644 docs/models/responsesoutputitemreasoningstatusincomplete.md create mode 100644 docs/models/responsesoutputitemreasoningstatusinprogress.md create mode 100644 docs/models/responsesoutputitemreasoningstatusunion.md create mode 100644 docs/models/responsesoutputitemreasoningtype.md create mode 100644 docs/models/responsesoutputmessage.md create mode 100644 docs/models/responsesoutputmessagecontent.md create mode 100644 docs/models/responsesoutputmessagerole.md create mode 100644 docs/models/responsesoutputmessagestatuscompleted.md create mode 100644 docs/models/responsesoutputmessagestatusincomplete.md create mode 100644 docs/models/responsesoutputmessagestatusinprogress.md create mode 100644 docs/models/responsesoutputmessagestatusunion.md create mode 100644 docs/models/responsesoutputmessagetype.md create mode 100644 docs/models/responsessearchcontextsize.md create mode 100644 docs/models/responseswebsearchcalloutput.md create mode 100644 docs/models/responseswebsearchcalloutputtype.md create mode 100644 docs/models/responseswebsearchuserlocation.md create mode 100644 docs/models/responseswebsearchuserlocationtype.md create mode 100644 docs/models/responsetextconfig.md create mode 100644 docs/models/responsetextconfigverbosity.md create mode 100644 docs/models/security.md create mode 100644 docs/models/sendchatcompletionrequestresponse.md create mode 100644 docs/models/servicetier.md create mode 100644 docs/models/serviceunavailableresponseerrordata.md create mode 100644 docs/models/sort.md create mode 100644 docs/models/streamoptions.md create mode 100644 docs/models/supportedparameter.md create mode 100644 docs/models/systemmessage.md create mode 100644 docs/models/systemmessagecontent.md create mode 100644 docs/models/tokenizer.md create mode 100644 docs/models/toolcallstatus.md create mode 100644 docs/models/tooldefinitionjson.md create mode 100644 docs/models/tooldefinitionjsonfunction.md create mode 100644 docs/models/toolresponsemessage.md create mode 100644 docs/models/toolresponsemessagecontent.md create mode 100644 docs/models/toomanyrequestsresponseerrordata.md create mode 100644 docs/models/toplogprob.md create mode 100644 docs/models/topproviderinfo.md create mode 100644 docs/models/transferintent.md create mode 100644 docs/models/truncation.md create mode 100644 docs/models/type.md create mode 100644 docs/models/typeresponsecompleted.md create mode 100644 docs/models/typeresponsecontentpartadded.md create mode 100644 docs/models/typeresponsecontentpartdone.md create mode 100644 docs/models/typeresponsecreated.md create mode 100644 docs/models/typeresponsefailed.md create mode 100644 docs/models/typeresponsefunctioncallargumentsdelta.md create mode 100644 docs/models/typeresponsefunctioncallargumentsdone.md create mode 100644 docs/models/typeresponseincomplete.md create mode 100644 docs/models/typeresponseinprogress.md create mode 100644 docs/models/typeresponseoutputitemadded.md create mode 100644 docs/models/typeresponseoutputitemdone.md create mode 100644 docs/models/typeresponseoutputtextannotationadded.md create mode 100644 docs/models/typeresponseoutputtextdelta.md create mode 100644 docs/models/typeresponseoutputtextdone.md create mode 100644 docs/models/typeresponsereasoningsummarypartdone.md create mode 100644 docs/models/typeresponserefusaldelta.md create mode 100644 docs/models/typeresponserefusaldone.md create mode 100644 docs/models/unauthorizedresponseerrordata.md create mode 100644 docs/models/unprocessableentityresponseerrordata.md create mode 100644 docs/models/updatekeysdata.md create mode 100644 docs/models/updatekeyslimitreset.md create mode 100644 docs/models/updatekeysrequest.md create mode 100644 docs/models/updatekeysrequestbody.md create mode 100644 docs/models/updatekeysresponse.md create mode 100644 docs/models/urlcitation.md create mode 100644 docs/models/urlcitationtype.md create mode 100644 docs/models/usage.md create mode 100644 docs/models/usermessage.md create mode 100644 docs/models/usermessagecontent.md create mode 100644 docs/models/utils/retryconfig.md create mode 100644 docs/models/variables.md create mode 100644 docs/models/videourl.md create mode 100644 docs/models/web3data.md create mode 100644 docs/models/websearchpreviewtooluserlocation.md create mode 100644 docs/models/websearchpreviewtooluserlocationtype.md create mode 100644 docs/models/websearchstatus.md create mode 100644 docs/sdks/analytics/README.md create mode 100644 docs/sdks/apikeys/README.md create mode 100644 docs/sdks/chat/README.md create mode 100644 docs/sdks/completions/README.md create mode 100644 docs/sdks/credits/README.md create mode 100644 docs/sdks/embeddings/README.md create mode 100644 docs/sdks/endpoints/README.md create mode 100644 docs/sdks/generations/README.md create mode 100644 docs/sdks/models/README.md create mode 100644 docs/sdks/oauth/README.md create mode 100644 docs/sdks/parameters/README.md create mode 100644 docs/sdks/providers/README.md create mode 100644 docs/sdks/responses/README.md create mode 100644 py.typed create mode 100644 pylintrc create mode 100644 pyproject.toml create mode 100644 scripts/publish.sh create mode 100644 src/openrouter/__init__.py create mode 100644 src/openrouter/_hooks/__init__.py create mode 100644 src/openrouter/_hooks/registration.py create mode 100644 src/openrouter/_hooks/sdkhooks.py create mode 100644 src/openrouter/_hooks/types.py create mode 100644 src/openrouter/_version.py create mode 100644 src/openrouter/analytics.py create mode 100644 src/openrouter/api_keys.py create mode 100644 src/openrouter/basesdk.py create mode 100644 src/openrouter/beta.py create mode 100644 src/openrouter/chat.py create mode 100644 src/openrouter/completions.py create mode 100644 src/openrouter/credits.py create mode 100644 src/openrouter/embeddings.py create mode 100644 src/openrouter/endpoints.py create mode 100644 src/openrouter/errors/__init__.py create mode 100644 src/openrouter/errors/badgatewayresponse_error.py create mode 100644 src/openrouter/errors/badrequestresponse_error.py create mode 100644 src/openrouter/errors/chaterror.py create mode 100644 src/openrouter/errors/edgenetworktimeoutresponse_error.py create mode 100644 src/openrouter/errors/forbiddenresponse_error.py create mode 100644 src/openrouter/errors/internalserverresponse_error.py create mode 100644 src/openrouter/errors/no_response_error.py create mode 100644 src/openrouter/errors/notfoundresponse_error.py create mode 100644 src/openrouter/errors/openrouterdefaulterror.py create mode 100644 src/openrouter/errors/openroutererror.py create mode 100644 src/openrouter/errors/payloadtoolargeresponse_error.py create mode 100644 src/openrouter/errors/paymentrequiredresponse_error.py create mode 100644 src/openrouter/errors/provideroverloadedresponse_error.py create mode 100644 src/openrouter/errors/requesttimeoutresponse_error.py create mode 100644 src/openrouter/errors/responsevalidationerror.py create mode 100644 src/openrouter/errors/serviceunavailableresponse_error.py create mode 100644 src/openrouter/errors/toomanyrequestsresponse_error.py create mode 100644 src/openrouter/errors/unauthorizedresponse_error.py create mode 100644 src/openrouter/errors/unprocessableentityresponse_error.py create mode 100644 src/openrouter/generations.py create mode 100644 src/openrouter/httpclient.py create mode 100644 src/openrouter/models/__init__.py create mode 100644 src/openrouter/models/activityitem.py create mode 100644 src/openrouter/models/assistantmessage.py create mode 100644 src/openrouter/models/badgatewayresponseerrordata.py create mode 100644 src/openrouter/models/badrequestresponseerrordata.py create mode 100644 src/openrouter/models/chatcompletionfinishreason.py create mode 100644 src/openrouter/models/chaterror.py create mode 100644 src/openrouter/models/chatgenerationparams.py create mode 100644 src/openrouter/models/chatgenerationtokenusage.py create mode 100644 src/openrouter/models/chatmessagecontentitem.py create mode 100644 src/openrouter/models/chatmessagecontentitemaudio.py create mode 100644 src/openrouter/models/chatmessagecontentitemimage.py create mode 100644 src/openrouter/models/chatmessagecontentitemtext.py create mode 100644 src/openrouter/models/chatmessagecontentitemvideo.py create mode 100644 src/openrouter/models/chatmessagetokenlogprob.py create mode 100644 src/openrouter/models/chatmessagetokenlogprobs.py create mode 100644 src/openrouter/models/chatmessagetoolcall.py create mode 100644 src/openrouter/models/chatresponse.py create mode 100644 src/openrouter/models/chatresponsechoice.py create mode 100644 src/openrouter/models/chatstreamingchoice.py create mode 100644 src/openrouter/models/chatstreamingmessagechunk.py create mode 100644 src/openrouter/models/chatstreamingmessagetoolcall.py create mode 100644 src/openrouter/models/chatstreamingresponsechunk.py create mode 100644 src/openrouter/models/chatstreamoptions.py create mode 100644 src/openrouter/models/completionchoice.py create mode 100644 src/openrouter/models/completioncreateparams.py create mode 100644 src/openrouter/models/completionlogprobs.py create mode 100644 src/openrouter/models/completionresponse.py create mode 100644 src/openrouter/models/completionusage.py create mode 100644 src/openrouter/models/createauthkeyscodeop.py create mode 100644 src/openrouter/models/createchargerequest.py create mode 100644 src/openrouter/models/createcoinbasechargeop.py create mode 100644 src/openrouter/models/createembeddingsop.py create mode 100644 src/openrouter/models/createkeysop.py create mode 100644 src/openrouter/models/createresponsesop.py create mode 100644 src/openrouter/models/defaultparameters.py create mode 100644 src/openrouter/models/deletekeysop.py create mode 100644 src/openrouter/models/edgenetworktimeoutresponseerrordata.py create mode 100644 src/openrouter/models/endpointstatus.py create mode 100644 src/openrouter/models/exchangeauthcodeforapikeyop.py create mode 100644 src/openrouter/models/filecitation.py create mode 100644 src/openrouter/models/filepath.py create mode 100644 src/openrouter/models/forbiddenresponseerrordata.py create mode 100644 src/openrouter/models/getcreditsop.py create mode 100644 src/openrouter/models/getcurrentkeyop.py create mode 100644 src/openrouter/models/getgenerationop.py create mode 100644 src/openrouter/models/getkeyop.py create mode 100644 src/openrouter/models/getmodelsop.py create mode 100644 src/openrouter/models/getparametersop.py create mode 100644 src/openrouter/models/getuseractivityop.py create mode 100644 src/openrouter/models/imagegenerationstatus.py create mode 100644 src/openrouter/models/inputmodality.py create mode 100644 src/openrouter/models/instructtype.py create mode 100644 src/openrouter/models/internalserverresponseerrordata.py create mode 100644 src/openrouter/models/jsonschemaconfig.py create mode 100644 src/openrouter/models/listendpointsop.py create mode 100644 src/openrouter/models/listendpointsresponse.py create mode 100644 src/openrouter/models/listendpointszdrop.py create mode 100644 src/openrouter/models/listmodelsuserop.py create mode 100644 src/openrouter/models/listop.py create mode 100644 src/openrouter/models/listprovidersop.py create mode 100644 src/openrouter/models/message.py create mode 100644 src/openrouter/models/model.py create mode 100644 src/openrouter/models/modelarchitecture.py create mode 100644 src/openrouter/models/modelgroup.py create mode 100644 src/openrouter/models/modelscountresponse.py create mode 100644 src/openrouter/models/modelslistresponse.py create mode 100644 src/openrouter/models/namedtoolchoice.py create mode 100644 src/openrouter/models/notfoundresponseerrordata.py create mode 100644 src/openrouter/models/openairesponsesannotation.py create mode 100644 src/openrouter/models/openairesponsesincludable.py create mode 100644 src/openrouter/models/openairesponsesincompletedetails.py create mode 100644 src/openrouter/models/openairesponsesinput_union.py create mode 100644 src/openrouter/models/openairesponsesprompt.py create mode 100644 src/openrouter/models/openairesponsesreasoningconfig.py create mode 100644 src/openrouter/models/openairesponsesreasoningeffort.py create mode 100644 src/openrouter/models/openairesponsesrefusalcontent.py create mode 100644 src/openrouter/models/openairesponsesresponsestatus.py create mode 100644 src/openrouter/models/openairesponsesservicetier.py create mode 100644 src/openrouter/models/openairesponsestoolchoice_union.py create mode 100644 src/openrouter/models/openairesponsestruncation.py create mode 100644 src/openrouter/models/openresponseseasyinputmessage.py create mode 100644 src/openrouter/models/openresponseserrorevent.py create mode 100644 src/openrouter/models/openresponsesfunctioncalloutput.py create mode 100644 src/openrouter/models/openresponsesfunctiontoolcall.py create mode 100644 src/openrouter/models/openresponsesimagegencallcompleted.py create mode 100644 src/openrouter/models/openresponsesimagegencallgenerating.py create mode 100644 src/openrouter/models/openresponsesimagegencallinprogress.py create mode 100644 src/openrouter/models/openresponsesimagegencallpartialimage.py create mode 100644 src/openrouter/models/openresponsesinput.py create mode 100644 src/openrouter/models/openresponsesinputmessageitem.py create mode 100644 src/openrouter/models/openresponseslogprobs.py create mode 100644 src/openrouter/models/openresponsesnonstreamingresponse.py create mode 100644 src/openrouter/models/openresponsesreasoning.py create mode 100644 src/openrouter/models/openresponsesreasoningconfig.py create mode 100644 src/openrouter/models/openresponsesreasoningdeltaevent.py create mode 100644 src/openrouter/models/openresponsesreasoningdoneevent.py create mode 100644 src/openrouter/models/openresponsesreasoningsummarypartaddedevent.py create mode 100644 src/openrouter/models/openresponsesreasoningsummarytextdeltaevent.py create mode 100644 src/openrouter/models/openresponsesreasoningsummarytextdoneevent.py create mode 100644 src/openrouter/models/openresponsesrequest.py create mode 100644 src/openrouter/models/openresponsesresponsetext.py create mode 100644 src/openrouter/models/openresponsesstreamevent.py create mode 100644 src/openrouter/models/openresponsestoplogprobs.py create mode 100644 src/openrouter/models/openresponsesusage.py create mode 100644 src/openrouter/models/openresponseswebsearch20250826tool.py create mode 100644 src/openrouter/models/openresponseswebsearchpreview20250311tool.py create mode 100644 src/openrouter/models/openresponseswebsearchpreviewtool.py create mode 100644 src/openrouter/models/openresponseswebsearchtool.py create mode 100644 src/openrouter/models/outputitemimagegenerationcall.py create mode 100644 src/openrouter/models/outputmessage.py create mode 100644 src/openrouter/models/outputmodality.py create mode 100644 src/openrouter/models/parameter.py create mode 100644 src/openrouter/models/payloadtoolargeresponseerrordata.py create mode 100644 src/openrouter/models/paymentrequiredresponseerrordata.py create mode 100644 src/openrouter/models/perrequestlimits.py create mode 100644 src/openrouter/models/providername.py create mode 100644 src/openrouter/models/provideroverloadedresponseerrordata.py create mode 100644 src/openrouter/models/publicendpoint.py create mode 100644 src/openrouter/models/publicpricing.py create mode 100644 src/openrouter/models/quantization.py create mode 100644 src/openrouter/models/reasoningsummarytext.py create mode 100644 src/openrouter/models/reasoningsummaryverbosity.py create mode 100644 src/openrouter/models/reasoningtextcontent.py create mode 100644 src/openrouter/models/requesttimeoutresponseerrordata.py create mode 100644 src/openrouter/models/responseformatjsonschema.py create mode 100644 src/openrouter/models/responseformattextconfig.py create mode 100644 src/openrouter/models/responseformattextgrammar.py create mode 100644 src/openrouter/models/responseinputaudio.py create mode 100644 src/openrouter/models/responseinputfile.py create mode 100644 src/openrouter/models/responseinputimage.py create mode 100644 src/openrouter/models/responseinputtext.py create mode 100644 src/openrouter/models/responseoutputtext.py create mode 100644 src/openrouter/models/responseserrorfield.py create mode 100644 src/openrouter/models/responsesformatjsonobject.py create mode 100644 src/openrouter/models/responsesformattext.py create mode 100644 src/openrouter/models/responsesformattextjsonschemaconfig.py create mode 100644 src/openrouter/models/responsesimagegenerationcall.py create mode 100644 src/openrouter/models/responsesoutputitem.py create mode 100644 src/openrouter/models/responsesoutputitemfilesearchcall.py create mode 100644 src/openrouter/models/responsesoutputitemfunctioncall.py create mode 100644 src/openrouter/models/responsesoutputitemreasoning.py create mode 100644 src/openrouter/models/responsesoutputmessage.py create mode 100644 src/openrouter/models/responsessearchcontextsize.py create mode 100644 src/openrouter/models/responseswebsearchcalloutput.py create mode 100644 src/openrouter/models/responseswebsearchuserlocation.py create mode 100644 src/openrouter/models/responsetextconfig.py create mode 100644 src/openrouter/models/security.py create mode 100644 src/openrouter/models/sendchatcompletionrequestop.py create mode 100644 src/openrouter/models/serviceunavailableresponseerrordata.py create mode 100644 src/openrouter/models/systemmessage.py create mode 100644 src/openrouter/models/toolcallstatus.py create mode 100644 src/openrouter/models/tooldefinitionjson.py create mode 100644 src/openrouter/models/toolresponsemessage.py create mode 100644 src/openrouter/models/toomanyrequestsresponseerrordata.py create mode 100644 src/openrouter/models/topproviderinfo.py create mode 100644 src/openrouter/models/unauthorizedresponseerrordata.py create mode 100644 src/openrouter/models/unprocessableentityresponseerrordata.py create mode 100644 src/openrouter/models/updatekeysop.py create mode 100644 src/openrouter/models/urlcitation.py create mode 100644 src/openrouter/models/usermessage.py create mode 100644 src/openrouter/models/websearchpreviewtooluserlocation.py create mode 100644 src/openrouter/models/websearchstatus.py create mode 100644 src/openrouter/models_.py create mode 100644 src/openrouter/oauth.py create mode 100644 src/openrouter/parameters.py create mode 100644 src/openrouter/providers.py create mode 100644 src/openrouter/py.typed create mode 100644 src/openrouter/responses.py create mode 100644 src/openrouter/sdk.py create mode 100644 src/openrouter/sdkconfiguration.py create mode 100644 src/openrouter/types/__init__.py create mode 100644 src/openrouter/types/basemodel.py create mode 100644 src/openrouter/utils/__init__.py create mode 100644 src/openrouter/utils/annotations.py create mode 100644 src/openrouter/utils/datetimes.py create mode 100644 src/openrouter/utils/enums.py create mode 100644 src/openrouter/utils/eventstreaming.py create mode 100644 src/openrouter/utils/forms.py create mode 100644 src/openrouter/utils/headers.py create mode 100644 src/openrouter/utils/logger.py create mode 100644 src/openrouter/utils/metadata.py create mode 100644 src/openrouter/utils/queryparams.py create mode 100644 src/openrouter/utils/requestbodies.py create mode 100644 src/openrouter/utils/retries.py create mode 100644 src/openrouter/utils/security.py create mode 100644 src/openrouter/utils/serializers.py create mode 100644 src/openrouter/utils/unmarshal_json_response.py create mode 100644 src/openrouter/utils/url.py create mode 100644 src/openrouter/utils/values.py diff --git a/.devcontainer/README.md b/.devcontainer/README.md new file mode 100644 index 0000000..396929a --- /dev/null +++ b/.devcontainer/README.md @@ -0,0 +1,30 @@ + +> **Remember to shutdown a GitHub Codespace when it is not in use!** + +# Dev Containers Quick Start + +The default location for usage snippets is the `samples` directory. + +## Running a Usage Sample + +A sample usage example has been provided in a `root.py` file. As you work with the SDK, it's expected that you will modify these samples to fit your needs. To execute this particular snippet, use the command below. + +``` +python root.py +``` + +## Generating Additional Usage Samples + +The speakeasy CLI allows you to generate more usage snippets. Here's how: + +- To generate a sample for a specific operation by providing an operation ID, use: + +``` +speakeasy generate usage -s .speakeasy/out.openapi.yaml -l python -i {INPUT_OPERATION_ID} -o ./samples +``` + +- To generate samples for an entire namespace (like a tag or group name), use: + +``` +speakeasy generate usage -s .speakeasy/out.openapi.yaml -l python -n {INPUT_TAG_NAME} -o ./samples +``` diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000..75edff5 --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,40 @@ +// For format details, see https://aka.ms/devcontainer.json. For config options, see the +// README at: https://github.com/devcontainers/images/tree/main/src/python +{ + "name": "Python", + "image": "mcr.microsoft.com/devcontainers/python:1-3.11-bullseye", + // Features to add to the dev container. More info: https://containers.dev/features. + "features": { + "ghcr.io/astral-sh/devcontainer-features/uv:latest": {} + }, + // Use 'forwardPorts' to make a list of ports inside the container available locally. + // "forwardPorts": [], + // Use 'postCreateCommand' to run commands after the container is created. + "postCreateCommand": "sudo chmod +x ./.devcontainer/setup.sh && ./.devcontainer/setup.sh", + "customizations": { + "vscode": { + "extensions": [ + "ms-python.python", + "ms-python.vscode-pylance", + "github.vscode-pull-request-github" + ], + "settings": { + "files.eol": "\n", + "editor.formatOnSave": true, + "python.formatting.provider": "black", + "python.linting.enabled": true, + "python.linting.pylintEnabled": true, + "python.linting.flake8Enabled": true, + "python.linting.banditEnabled": true, + "python.testing.pytestEnabled": true + } + }, + "codespaces": { + "openFiles": [ + ".devcontainer/README.md" + ] + } + } + // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root. + // "remoteUser": "root" +} diff --git a/.devcontainer/setup.sh b/.devcontainer/setup.sh new file mode 100644 index 0000000..b39c28c --- /dev/null +++ b/.devcontainer/setup.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +# Install the speakeasy CLI +curl -fsSL https://raw.githubusercontent.com/speakeasy-api/speakeasy/main/install.sh | sh + +# Setup samples directory +rmdir samples || true +mkdir samples + + +uv sync --dev + +# Generate starter usage sample with speakeasy +speakeasy generate usage -s .speakeasy/out.openapi.yaml -l python -o samples/root.py \ No newline at end of file diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..4d75d59 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# This allows generated code to be indexed correctly +*.py linguist-generated=false \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d69301d --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +.venv/ +venv/ +src/*.egg-info/ +**/__pycache__/ +.pytest_cache/ +.python-version +.DS_Store +pyrightconfig.json +**/.speakeasy/temp/ +**/.speakeasy/logs/ +.speakeasy/reports +.env +.env.local diff --git a/.speakeasy/gen.lock b/.speakeasy/gen.lock new file mode 100644 index 0000000..e7e3af7 --- /dev/null +++ b/.speakeasy/gen.lock @@ -0,0 +1,1096 @@ +lockVersion: 2.0.0 +id: cfd52247-6a25-4c6d-bbce-fe6fce0cd69d +management: + docChecksum: b1b97e85c6e3464e1fd6e2163c4ebc87 + docVersion: 1.0.0 + speakeasyVersion: 1.656.2 + generationVersion: 2.753.6 + releaseVersion: 0.0.1 + configChecksum: 1d12f047ab1c8a906d4cd3f99af8d8f3 +features: + python: + acceptHeaders: 3.0.0 + additionalDependencies: 1.0.0 + constsAndDefaults: 1.0.5 + core: 5.23.6 + defaultEnabledRetries: 0.2.0 + deprecations: 3.0.2 + devContainers: 3.0.0 + enumUnions: 0.1.0 + envVarSecurityUsage: 0.3.2 + flatRequests: 1.0.1 + flattening: 3.1.1 + globalSecurity: 3.0.4 + globalSecurityCallbacks: 1.0.0 + globalSecurityFlattening: 1.0.0 + globalServerURLs: 3.2.0 + groups: 3.0.1 + methodArguments: 1.0.2 + methodSecurity: 3.0.1 + nameOverrides: 3.0.1 + nullables: 1.0.1 + openEnums: 1.0.1 + responseFormat: 1.0.1 + retries: 3.0.2 + sdkHooks: 1.1.0 + serverEvents: 1.0.11 + serverEventsSentinels: 0.1.0 + serverIDs: 3.0.0 + unions: 3.1.0 +generatedFiles: + - .devcontainer/README.md + - .devcontainer/devcontainer.json + - .devcontainer/setup.sh + - .gitattributes + - .vscode/settings.json + - USAGE.md + - docs/errors/badgatewayresponseerror.md + - docs/errors/badrequestresponseerror.md + - docs/errors/chaterror.md + - docs/errors/edgenetworktimeoutresponseerror.md + - docs/errors/forbiddenresponseerror.md + - docs/errors/internalserverresponseerror.md + - docs/errors/notfoundresponseerror.md + - docs/errors/payloadtoolargeresponseerror.md + - docs/errors/paymentrequiredresponseerror.md + - docs/errors/provideroverloadedresponseerror.md + - docs/errors/requesttimeoutresponseerror.md + - docs/errors/serviceunavailableresponseerror.md + - docs/errors/toomanyrequestsresponseerror.md + - docs/errors/unauthorizedresponseerror.md + - docs/errors/unprocessableentityresponseerror.md + - docs/models/activityitem.md + - docs/models/apitype.md + - docs/models/architecture.md + - docs/models/assistantmessage.md + - docs/models/assistantmessagecontent.md + - docs/models/badgatewayresponseerrordata.md + - docs/models/badrequestresponseerrordata.md + - docs/models/calldata.md + - docs/models/chainid.md + - docs/models/chatcompletionfinishreason.md + - docs/models/chaterrorerror.md + - docs/models/chatgenerationparams.md + - docs/models/chatgenerationparamsresponseformatjsonobject.md + - docs/models/chatgenerationparamsresponseformatpython.md + - docs/models/chatgenerationparamsresponseformattext.md + - docs/models/chatgenerationparamsresponseformatunion.md + - docs/models/chatgenerationparamsstop.md + - docs/models/chatgenerationtokenusage.md + - docs/models/chatmessagecontentitem.md + - docs/models/chatmessagecontentitemaudio.md + - docs/models/chatmessagecontentitemaudioformat.md + - docs/models/chatmessagecontentitemaudioinputaudio.md + - docs/models/chatmessagecontentitemimage.md + - docs/models/chatmessagecontentitemimagedetail.md + - docs/models/chatmessagecontentitemtext.md + - docs/models/chatmessagecontentitemvideo.md + - docs/models/chatmessagetokenlogprob.md + - docs/models/chatmessagetokenlogprobs.md + - docs/models/chatmessagetoolcall.md + - docs/models/chatmessagetoolcallfunction.md + - docs/models/chatresponse.md + - docs/models/chatresponsechoice.md + - docs/models/chatstreamingchoice.md + - docs/models/chatstreamingmessagechunk.md + - docs/models/chatstreamingmessagechunkrole.md + - docs/models/chatstreamingmessagetoolcall.md + - docs/models/chatstreamingmessagetoolcallfunction.md + - docs/models/chatstreamingresponsechunk.md + - docs/models/chatstreamingresponsechunkdata.md + - docs/models/chatstreamingresponsechunkerror.md + - docs/models/chatstreamoptions.md + - docs/models/code.md + - docs/models/codeenum.md + - docs/models/completionchoice.md + - docs/models/completioncreateparams.md + - docs/models/completioncreateparamsresponseformatjsonobject.md + - docs/models/completioncreateparamsresponseformatpython.md + - docs/models/completioncreateparamsresponseformattext.md + - docs/models/completioncreateparamsresponseformatunion.md + - docs/models/completioncreateparamsstop.md + - docs/models/completionfinishreason.md + - docs/models/completionlogprobs.md + - docs/models/completionresponse.md + - docs/models/completiontokensdetails.md + - docs/models/completionusage.md + - docs/models/costdetails.md + - docs/models/createauthkeyscodecodechallengemethod.md + - docs/models/createauthkeyscodedata.md + - docs/models/createauthkeyscoderequest.md + - docs/models/createauthkeyscoderesponse.md + - docs/models/createchargerequest.md + - docs/models/createcoinbasechargedata.md + - docs/models/createcoinbasechargeresponse.md + - docs/models/createcoinbasechargesecurity.md + - docs/models/createembeddingsdata.md + - docs/models/createembeddingsdatacollection.md + - docs/models/createembeddingsignore.md + - docs/models/createembeddingsmaxprice.md + - docs/models/createembeddingsobject.md + - docs/models/createembeddingsonly.md + - docs/models/createembeddingsorder.md + - docs/models/createembeddingsprovider.md + - docs/models/createembeddingsrequest.md + - docs/models/createembeddingsresponse.md + - docs/models/createembeddingsresponsebody.md + - docs/models/createembeddingssort.md + - docs/models/createkeysdata.md + - docs/models/createkeyslimitreset.md + - docs/models/createkeysrequest.md + - docs/models/createkeysresponse.md + - docs/models/createresponsesresponse.md + - docs/models/createresponsesresponsebody.md + - docs/models/datacollection.md + - docs/models/defaultparameters.md + - docs/models/deletekeysrequest.md + - docs/models/deletekeysresponse.md + - docs/models/edgenetworktimeoutresponseerrordata.md + - docs/models/effort.md + - docs/models/embedding.md + - docs/models/encodingformat.md + - docs/models/encodingformatbase64.md + - docs/models/encodingformatfloat.md + - docs/models/endpointslistendpointsresponse.md + - docs/models/endpointstatus.md + - docs/models/engine.md + - docs/models/exchangeauthcodeforapikeycodechallengemethod.md + - docs/models/exchangeauthcodeforapikeyrequest.md + - docs/models/exchangeauthcodeforapikeyresponse.md + - docs/models/filecitation.md + - docs/models/filecitationtype.md + - docs/models/filepath.md + - docs/models/filepathtype.md + - docs/models/forbiddenresponseerrordata.md + - docs/models/getcreditsresponse.md + - docs/models/getcurrentkeydata.md + - docs/models/getcurrentkeyresponse.md + - docs/models/getgenerationdata.md + - docs/models/getgenerationrequest.md + - docs/models/getgenerationresponse.md + - docs/models/getkeydata.md + - docs/models/getkeyrequest.md + - docs/models/getkeyresponse.md + - docs/models/getmodelsrequest.md + - docs/models/getparametersdata.md + - docs/models/getparametersprovider.md + - docs/models/getparametersrequest.md + - docs/models/getparametersresponse.md + - docs/models/getparameterssecurity.md + - docs/models/getuseractivityrequest.md + - docs/models/getuseractivityresponse.md + - docs/models/idfileparser.md + - docs/models/idmoderation.md + - docs/models/idweb.md + - docs/models/ignore.md + - docs/models/imagegenerationstatus.md + - docs/models/imageurl.md + - docs/models/input.md + - docs/models/inputmodality.md + - docs/models/inputtokensdetails.md + - docs/models/instructtype.md + - docs/models/internalserverresponseerrordata.md + - docs/models/jsonschemaconfig.md + - docs/models/listdata.md + - docs/models/listendpointsrequest.md + - docs/models/listendpointsresponse.md + - docs/models/listendpointszdrresponse.md + - docs/models/listmodelsusersecurity.md + - docs/models/listprovidersdata.md + - docs/models/listprovidersresponse.md + - docs/models/listrequest.md + - docs/models/listresponse.md + - docs/models/maxprice.md + - docs/models/message.md + - docs/models/messagecontent.md + - docs/models/messagedeveloper.md + - docs/models/metadata.md + - docs/models/model.md + - docs/models/modelarchitecture.md + - docs/models/modelarchitectureinstructtype.md + - docs/models/modelgroup.md + - docs/models/modelscountresponse.md + - docs/models/modelscountresponsedata.md + - docs/models/modelslistresponse.md + - docs/models/namedtoolchoice.md + - docs/models/namedtoolchoicefunction.md + - docs/models/notfoundresponseerrordata.md + - docs/models/object.md + - docs/models/objectembedding.md + - docs/models/only.md + - docs/models/openairesponsesannotation.md + - docs/models/openairesponsesincludable.md + - docs/models/openairesponsesincompletedetails.md + - docs/models/openairesponsesinputcontent1.md + - docs/models/openairesponsesinputcontent2.md + - docs/models/openairesponsesinputcontent3.md + - docs/models/openairesponsesinputfunctioncall.md + - docs/models/openairesponsesinputfunctioncalloutput.md + - docs/models/openairesponsesinputmessage1.md + - docs/models/openairesponsesinputmessage2.md + - docs/models/openairesponsesinputroleassistant.md + - docs/models/openairesponsesinputroledeveloper1.md + - docs/models/openairesponsesinputroledeveloper2.md + - docs/models/openairesponsesinputrolesystem1.md + - docs/models/openairesponsesinputrolesystem2.md + - docs/models/openairesponsesinputroleunion1.md + - docs/models/openairesponsesinputroleunion2.md + - docs/models/openairesponsesinputroleuser1.md + - docs/models/openairesponsesinputroleuser2.md + - docs/models/openairesponsesinputtypefunctioncall.md + - docs/models/openairesponsesinputtypefunctioncalloutput.md + - docs/models/openairesponsesinputtypemessage1.md + - docs/models/openairesponsesinputtypemessage2.md + - docs/models/openairesponsesinputunion.md + - docs/models/openairesponsesinputunion1.md + - docs/models/openairesponsesprompt.md + - docs/models/openairesponsesreasoningconfig.md + - docs/models/openairesponsesreasoningeffort.md + - docs/models/openairesponsesrefusalcontent.md + - docs/models/openairesponsesrefusalcontenttype.md + - docs/models/openairesponsesresponsestatus.md + - docs/models/openairesponsesservicetier.md + - docs/models/openairesponsestoolchoice.md + - docs/models/openairesponsestoolchoiceauto.md + - docs/models/openairesponsestoolchoicefunction.md + - docs/models/openairesponsestoolchoicenone.md + - docs/models/openairesponsestoolchoicerequired.md + - docs/models/openairesponsestoolchoicetypefunction.md + - docs/models/openairesponsestoolchoicetypewebsearchpreview.md + - docs/models/openairesponsestoolchoicetypewebsearchpreview20250311.md + - docs/models/openairesponsestoolchoiceunion.md + - docs/models/openairesponsestruncation.md + - docs/models/openresponseseasyinputmessage.md + - docs/models/openresponseseasyinputmessagecontent1.md + - docs/models/openresponseseasyinputmessagecontent2.md + - docs/models/openresponseseasyinputmessageroleassistant.md + - docs/models/openresponseseasyinputmessageroledeveloper.md + - docs/models/openresponseseasyinputmessagerolesystem.md + - docs/models/openresponseseasyinputmessageroleunion.md + - docs/models/openresponseseasyinputmessageroleuser.md + - docs/models/openresponseseasyinputmessagetype.md + - docs/models/openresponseserrorevent.md + - docs/models/openresponseserroreventtype.md + - docs/models/openresponsesfunctioncalloutput.md + - docs/models/openresponsesfunctioncalloutputtype.md + - docs/models/openresponsesfunctiontoolcall.md + - docs/models/openresponsesfunctiontoolcalltype.md + - docs/models/openresponsesimagegencallcompleted.md + - docs/models/openresponsesimagegencallcompletedtype.md + - docs/models/openresponsesimagegencallgenerating.md + - docs/models/openresponsesimagegencallgeneratingtype.md + - docs/models/openresponsesimagegencallinprogress.md + - docs/models/openresponsesimagegencallinprogresstype.md + - docs/models/openresponsesimagegencallpartialimage.md + - docs/models/openresponsesimagegencallpartialimagetype.md + - docs/models/openresponsesinput.md + - docs/models/openresponsesinput1.md + - docs/models/openresponsesinputmessageitem.md + - docs/models/openresponsesinputmessageitemcontent.md + - docs/models/openresponsesinputmessageitemroledeveloper.md + - docs/models/openresponsesinputmessageitemrolesystem.md + - docs/models/openresponsesinputmessageitemroleunion.md + - docs/models/openresponsesinputmessageitemroleuser.md + - docs/models/openresponsesinputmessageitemtype.md + - docs/models/openresponseslogprobs.md + - docs/models/openresponsesnonstreamingresponse.md + - docs/models/openresponsesnonstreamingresponsetoolfunction.md + - docs/models/openresponsesnonstreamingresponsetoolunion.md + - docs/models/openresponsesnonstreamingresponsetype.md + - docs/models/openresponsesreasoning.md + - docs/models/openresponsesreasoningconfig.md + - docs/models/openresponsesreasoningdeltaevent.md + - docs/models/openresponsesreasoningdeltaeventtype.md + - docs/models/openresponsesreasoningdoneevent.md + - docs/models/openresponsesreasoningdoneeventtype.md + - docs/models/openresponsesreasoningformat.md + - docs/models/openresponsesreasoningstatuscompleted.md + - docs/models/openresponsesreasoningstatusincomplete.md + - docs/models/openresponsesreasoningstatusinprogress.md + - docs/models/openresponsesreasoningstatusunion.md + - docs/models/openresponsesreasoningsummarypartaddedevent.md + - docs/models/openresponsesreasoningsummarypartaddedeventtype.md + - docs/models/openresponsesreasoningsummarytextdeltaevent.md + - docs/models/openresponsesreasoningsummarytextdeltaeventtype.md + - docs/models/openresponsesreasoningsummarytextdoneevent.md + - docs/models/openresponsesreasoningsummarytextdoneeventtype.md + - docs/models/openresponsesreasoningtype.md + - docs/models/openresponsesrequest.md + - docs/models/openresponsesrequesttoolfunction.md + - docs/models/openresponsesrequesttoolunion.md + - docs/models/openresponsesrequesttype.md + - docs/models/openresponsesresponsetext.md + - docs/models/openresponsesresponsetextverbosity.md + - docs/models/openresponsesstreamevent.md + - docs/models/openresponsesstreameventresponsecompleted.md + - docs/models/openresponsesstreameventresponsecontentpartadded.md + - docs/models/openresponsesstreameventresponsecontentpartdone.md + - docs/models/openresponsesstreameventresponsecreated.md + - docs/models/openresponsesstreameventresponsefailed.md + - docs/models/openresponsesstreameventresponsefunctioncallargumentsdelta.md + - docs/models/openresponsesstreameventresponsefunctioncallargumentsdone.md + - docs/models/openresponsesstreameventresponseincomplete.md + - docs/models/openresponsesstreameventresponseinprogress.md + - docs/models/openresponsesstreameventresponseoutputitemadded.md + - docs/models/openresponsesstreameventresponseoutputitemdone.md + - docs/models/openresponsesstreameventresponseoutputtextannotationadded.md + - docs/models/openresponsesstreameventresponseoutputtextdelta.md + - docs/models/openresponsesstreameventresponseoutputtextdone.md + - docs/models/openresponsesstreameventresponsereasoningsummarypartdone.md + - docs/models/openresponsesstreameventresponserefusaldelta.md + - docs/models/openresponsesstreameventresponserefusaldone.md + - docs/models/openresponsestoplogprobs.md + - docs/models/openresponsesusage.md + - docs/models/openresponseswebsearch20250826tool.md + - docs/models/openresponseswebsearch20250826toolfilters.md + - docs/models/openresponseswebsearch20250826tooltype.md + - docs/models/openresponseswebsearchpreview20250311tool.md + - docs/models/openresponseswebsearchpreview20250311tooltype.md + - docs/models/openresponseswebsearchpreviewtool.md + - docs/models/openresponseswebsearchpreviewtooltype.md + - docs/models/openresponseswebsearchtool.md + - docs/models/openresponseswebsearchtoolfilters.md + - docs/models/openresponseswebsearchtooltype.md + - docs/models/order.md + - docs/models/outputitemimagegenerationcall.md + - docs/models/outputitemimagegenerationcalltype.md + - docs/models/outputmessage.md + - docs/models/outputmessagecontent.md + - docs/models/outputmessagerole.md + - docs/models/outputmessagestatuscompleted.md + - docs/models/outputmessagestatusincomplete.md + - docs/models/outputmessagestatusinprogress.md + - docs/models/outputmessagestatusunion.md + - docs/models/outputmessagetype.md + - docs/models/outputmodality.md + - docs/models/outputtokensdetails.md + - docs/models/parameter.md + - docs/models/part1.md + - docs/models/part2.md + - docs/models/payloadtoolargeresponseerrordata.md + - docs/models/paymentrequiredresponseerrordata.md + - docs/models/pdf.md + - docs/models/pdfengine.md + - docs/models/perrequestlimits.md + - docs/models/plugin.md + - docs/models/pluginfileparser.md + - docs/models/pluginmoderation.md + - docs/models/pluginweb.md + - docs/models/pricing.md + - docs/models/prompt.md + - docs/models/prompttokensdetails.md + - docs/models/provider.md + - docs/models/providername.md + - docs/models/provideroverloadedresponseerrordata.md + - docs/models/publicendpoint.md + - docs/models/publicendpointquantization.md + - docs/models/publicpricing.md + - docs/models/quantization.md + - docs/models/ratelimit.md + - docs/models/reason.md + - docs/models/reasoning.md + - docs/models/reasoningsummarytext.md + - docs/models/reasoningsummarytexttype.md + - docs/models/reasoningsummaryverbosity.md + - docs/models/reasoningtextcontent.md + - docs/models/reasoningtextcontenttype.md + - docs/models/requesttimeoutresponseerrordata.md + - docs/models/responseformatjsonschema.md + - docs/models/responseformattextconfig.md + - docs/models/responseformattextgrammar.md + - docs/models/responseinputaudio.md + - docs/models/responseinputaudioformat.md + - docs/models/responseinputaudioinputaudio.md + - docs/models/responseinputaudiotype.md + - docs/models/responseinputfile.md + - docs/models/responseinputfiletype.md + - docs/models/responseinputimage.md + - docs/models/responseinputimagedetail.md + - docs/models/responseinputimagetype.md + - docs/models/responseinputtext.md + - docs/models/responseinputtexttype.md + - docs/models/responseoutputtext.md + - docs/models/responseoutputtexttype.md + - docs/models/responseserrorfield.md + - docs/models/responsesformatjsonobject.md + - docs/models/responsesformatjsonobjecttype.md + - docs/models/responsesformattext.md + - docs/models/responsesformattextjsonschemaconfig.md + - docs/models/responsesformattextjsonschemaconfigtype.md + - docs/models/responsesformattexttype.md + - docs/models/responsesimagegenerationcall.md + - docs/models/responsesimagegenerationcalltype.md + - docs/models/responsesoutputitem.md + - docs/models/responsesoutputitemfilesearchcall.md + - docs/models/responsesoutputitemfilesearchcalltype.md + - docs/models/responsesoutputitemfunctioncall.md + - docs/models/responsesoutputitemfunctioncallstatuscompleted.md + - docs/models/responsesoutputitemfunctioncallstatusincomplete.md + - docs/models/responsesoutputitemfunctioncallstatusinprogress.md + - docs/models/responsesoutputitemfunctioncallstatusunion.md + - docs/models/responsesoutputitemfunctioncalltype.md + - docs/models/responsesoutputitemreasoning.md + - docs/models/responsesoutputitemreasoningstatuscompleted.md + - docs/models/responsesoutputitemreasoningstatusincomplete.md + - docs/models/responsesoutputitemreasoningstatusinprogress.md + - docs/models/responsesoutputitemreasoningstatusunion.md + - docs/models/responsesoutputitemreasoningtype.md + - docs/models/responsesoutputmessage.md + - docs/models/responsesoutputmessagecontent.md + - docs/models/responsesoutputmessagerole.md + - docs/models/responsesoutputmessagestatuscompleted.md + - docs/models/responsesoutputmessagestatusincomplete.md + - docs/models/responsesoutputmessagestatusinprogress.md + - docs/models/responsesoutputmessagestatusunion.md + - docs/models/responsesoutputmessagetype.md + - docs/models/responsessearchcontextsize.md + - docs/models/responseswebsearchcalloutput.md + - docs/models/responseswebsearchcalloutputtype.md + - docs/models/responseswebsearchuserlocation.md + - docs/models/responseswebsearchuserlocationtype.md + - docs/models/responsetextconfig.md + - docs/models/responsetextconfigverbosity.md + - docs/models/security.md + - docs/models/sendchatcompletionrequestresponse.md + - docs/models/servicetier.md + - docs/models/serviceunavailableresponseerrordata.md + - docs/models/sort.md + - docs/models/streamoptions.md + - docs/models/supportedparameter.md + - docs/models/systemmessage.md + - docs/models/systemmessagecontent.md + - docs/models/tokenizer.md + - docs/models/toolcallstatus.md + - docs/models/tooldefinitionjson.md + - docs/models/tooldefinitionjsonfunction.md + - docs/models/toolresponsemessage.md + - docs/models/toolresponsemessagecontent.md + - docs/models/toomanyrequestsresponseerrordata.md + - docs/models/toplogprob.md + - docs/models/topproviderinfo.md + - docs/models/transferintent.md + - docs/models/truncation.md + - docs/models/type.md + - docs/models/typeresponsecompleted.md + - docs/models/typeresponsecontentpartadded.md + - docs/models/typeresponsecontentpartdone.md + - docs/models/typeresponsecreated.md + - docs/models/typeresponsefailed.md + - docs/models/typeresponsefunctioncallargumentsdelta.md + - docs/models/typeresponsefunctioncallargumentsdone.md + - docs/models/typeresponseincomplete.md + - docs/models/typeresponseinprogress.md + - docs/models/typeresponseoutputitemadded.md + - docs/models/typeresponseoutputitemdone.md + - docs/models/typeresponseoutputtextannotationadded.md + - docs/models/typeresponseoutputtextdelta.md + - docs/models/typeresponseoutputtextdone.md + - docs/models/typeresponsereasoningsummarypartdone.md + - docs/models/typeresponserefusaldelta.md + - docs/models/typeresponserefusaldone.md + - docs/models/unauthorizedresponseerrordata.md + - docs/models/unprocessableentityresponseerrordata.md + - docs/models/updatekeysdata.md + - docs/models/updatekeyslimitreset.md + - docs/models/updatekeysrequest.md + - docs/models/updatekeysrequestbody.md + - docs/models/updatekeysresponse.md + - docs/models/urlcitation.md + - docs/models/urlcitationtype.md + - docs/models/usage.md + - docs/models/usermessage.md + - docs/models/usermessagecontent.md + - docs/models/utils/retryconfig.md + - docs/models/variables.md + - docs/models/videourl.md + - docs/models/web3data.md + - docs/models/websearchpreviewtooluserlocation.md + - docs/models/websearchpreviewtooluserlocationtype.md + - docs/models/websearchstatus.md + - docs/sdks/analytics/README.md + - docs/sdks/apikeys/README.md + - docs/sdks/chat/README.md + - docs/sdks/completions/README.md + - docs/sdks/credits/README.md + - docs/sdks/embeddings/README.md + - docs/sdks/endpoints/README.md + - docs/sdks/generations/README.md + - docs/sdks/models/README.md + - docs/sdks/oauth/README.md + - docs/sdks/parameters/README.md + - docs/sdks/providers/README.md + - docs/sdks/responses/README.md + - py.typed + - pylintrc + - pyproject.toml + - scripts/publish.sh + - src/openrouter/__init__.py + - src/openrouter/_hooks/__init__.py + - src/openrouter/_hooks/sdkhooks.py + - src/openrouter/_hooks/types.py + - src/openrouter/_version.py + - src/openrouter/analytics.py + - src/openrouter/api_keys.py + - src/openrouter/basesdk.py + - src/openrouter/beta.py + - src/openrouter/chat.py + - src/openrouter/completions.py + - src/openrouter/credits.py + - src/openrouter/embeddings.py + - src/openrouter/endpoints.py + - src/openrouter/errors/__init__.py + - src/openrouter/errors/badgatewayresponse_error.py + - src/openrouter/errors/badrequestresponse_error.py + - src/openrouter/errors/chaterror.py + - src/openrouter/errors/edgenetworktimeoutresponse_error.py + - src/openrouter/errors/forbiddenresponse_error.py + - src/openrouter/errors/internalserverresponse_error.py + - src/openrouter/errors/no_response_error.py + - src/openrouter/errors/notfoundresponse_error.py + - src/openrouter/errors/openrouterdefaulterror.py + - src/openrouter/errors/openroutererror.py + - src/openrouter/errors/payloadtoolargeresponse_error.py + - src/openrouter/errors/paymentrequiredresponse_error.py + - src/openrouter/errors/provideroverloadedresponse_error.py + - src/openrouter/errors/requesttimeoutresponse_error.py + - src/openrouter/errors/responsevalidationerror.py + - src/openrouter/errors/serviceunavailableresponse_error.py + - src/openrouter/errors/toomanyrequestsresponse_error.py + - src/openrouter/errors/unauthorizedresponse_error.py + - src/openrouter/errors/unprocessableentityresponse_error.py + - src/openrouter/generations.py + - src/openrouter/httpclient.py + - src/openrouter/models/__init__.py + - src/openrouter/models/activityitem.py + - src/openrouter/models/assistantmessage.py + - src/openrouter/models/badgatewayresponseerrordata.py + - src/openrouter/models/badrequestresponseerrordata.py + - src/openrouter/models/chatcompletionfinishreason.py + - src/openrouter/models/chaterror.py + - src/openrouter/models/chatgenerationparams.py + - src/openrouter/models/chatgenerationtokenusage.py + - src/openrouter/models/chatmessagecontentitem.py + - src/openrouter/models/chatmessagecontentitemaudio.py + - src/openrouter/models/chatmessagecontentitemimage.py + - src/openrouter/models/chatmessagecontentitemtext.py + - src/openrouter/models/chatmessagecontentitemvideo.py + - src/openrouter/models/chatmessagetokenlogprob.py + - src/openrouter/models/chatmessagetokenlogprobs.py + - src/openrouter/models/chatmessagetoolcall.py + - src/openrouter/models/chatresponse.py + - src/openrouter/models/chatresponsechoice.py + - src/openrouter/models/chatstreamingchoice.py + - src/openrouter/models/chatstreamingmessagechunk.py + - src/openrouter/models/chatstreamingmessagetoolcall.py + - src/openrouter/models/chatstreamingresponsechunk.py + - src/openrouter/models/chatstreamoptions.py + - src/openrouter/models/completionchoice.py + - src/openrouter/models/completioncreateparams.py + - src/openrouter/models/completionlogprobs.py + - src/openrouter/models/completionresponse.py + - src/openrouter/models/completionusage.py + - src/openrouter/models/createauthkeyscodeop.py + - src/openrouter/models/createchargerequest.py + - src/openrouter/models/createcoinbasechargeop.py + - src/openrouter/models/createembeddingsop.py + - src/openrouter/models/createkeysop.py + - src/openrouter/models/createresponsesop.py + - src/openrouter/models/defaultparameters.py + - src/openrouter/models/deletekeysop.py + - src/openrouter/models/edgenetworktimeoutresponseerrordata.py + - src/openrouter/models/endpointstatus.py + - src/openrouter/models/exchangeauthcodeforapikeyop.py + - src/openrouter/models/filecitation.py + - src/openrouter/models/filepath.py + - src/openrouter/models/forbiddenresponseerrordata.py + - src/openrouter/models/getcreditsop.py + - src/openrouter/models/getcurrentkeyop.py + - src/openrouter/models/getgenerationop.py + - src/openrouter/models/getkeyop.py + - src/openrouter/models/getmodelsop.py + - src/openrouter/models/getparametersop.py + - src/openrouter/models/getuseractivityop.py + - src/openrouter/models/imagegenerationstatus.py + - src/openrouter/models/inputmodality.py + - src/openrouter/models/instructtype.py + - src/openrouter/models/internalserverresponseerrordata.py + - src/openrouter/models/jsonschemaconfig.py + - src/openrouter/models/listendpointsop.py + - src/openrouter/models/listendpointsresponse.py + - src/openrouter/models/listendpointszdrop.py + - src/openrouter/models/listmodelsuserop.py + - src/openrouter/models/listop.py + - src/openrouter/models/listprovidersop.py + - src/openrouter/models/message.py + - src/openrouter/models/model.py + - src/openrouter/models/modelarchitecture.py + - src/openrouter/models/modelgroup.py + - src/openrouter/models/modelscountresponse.py + - src/openrouter/models/modelslistresponse.py + - src/openrouter/models/namedtoolchoice.py + - src/openrouter/models/notfoundresponseerrordata.py + - src/openrouter/models/openairesponsesannotation.py + - src/openrouter/models/openairesponsesincludable.py + - src/openrouter/models/openairesponsesincompletedetails.py + - src/openrouter/models/openairesponsesinput_union.py + - src/openrouter/models/openairesponsesprompt.py + - src/openrouter/models/openairesponsesreasoningconfig.py + - src/openrouter/models/openairesponsesreasoningeffort.py + - src/openrouter/models/openairesponsesrefusalcontent.py + - src/openrouter/models/openairesponsesresponsestatus.py + - src/openrouter/models/openairesponsesservicetier.py + - src/openrouter/models/openairesponsestoolchoice_union.py + - src/openrouter/models/openairesponsestruncation.py + - src/openrouter/models/openresponseseasyinputmessage.py + - src/openrouter/models/openresponseserrorevent.py + - src/openrouter/models/openresponsesfunctioncalloutput.py + - src/openrouter/models/openresponsesfunctiontoolcall.py + - src/openrouter/models/openresponsesimagegencallcompleted.py + - src/openrouter/models/openresponsesimagegencallgenerating.py + - src/openrouter/models/openresponsesimagegencallinprogress.py + - src/openrouter/models/openresponsesimagegencallpartialimage.py + - src/openrouter/models/openresponsesinput.py + - src/openrouter/models/openresponsesinputmessageitem.py + - src/openrouter/models/openresponseslogprobs.py + - src/openrouter/models/openresponsesnonstreamingresponse.py + - src/openrouter/models/openresponsesreasoning.py + - src/openrouter/models/openresponsesreasoningconfig.py + - src/openrouter/models/openresponsesreasoningdeltaevent.py + - src/openrouter/models/openresponsesreasoningdoneevent.py + - src/openrouter/models/openresponsesreasoningsummarypartaddedevent.py + - src/openrouter/models/openresponsesreasoningsummarytextdeltaevent.py + - src/openrouter/models/openresponsesreasoningsummarytextdoneevent.py + - src/openrouter/models/openresponsesrequest.py + - src/openrouter/models/openresponsesresponsetext.py + - src/openrouter/models/openresponsesstreamevent.py + - src/openrouter/models/openresponsestoplogprobs.py + - src/openrouter/models/openresponsesusage.py + - src/openrouter/models/openresponseswebsearch20250826tool.py + - src/openrouter/models/openresponseswebsearchpreview20250311tool.py + - src/openrouter/models/openresponseswebsearchpreviewtool.py + - src/openrouter/models/openresponseswebsearchtool.py + - src/openrouter/models/outputitemimagegenerationcall.py + - src/openrouter/models/outputmessage.py + - src/openrouter/models/outputmodality.py + - src/openrouter/models/parameter.py + - src/openrouter/models/payloadtoolargeresponseerrordata.py + - src/openrouter/models/paymentrequiredresponseerrordata.py + - src/openrouter/models/perrequestlimits.py + - src/openrouter/models/providername.py + - src/openrouter/models/provideroverloadedresponseerrordata.py + - src/openrouter/models/publicendpoint.py + - src/openrouter/models/publicpricing.py + - src/openrouter/models/quantization.py + - src/openrouter/models/reasoningsummarytext.py + - src/openrouter/models/reasoningsummaryverbosity.py + - src/openrouter/models/reasoningtextcontent.py + - src/openrouter/models/requesttimeoutresponseerrordata.py + - src/openrouter/models/responseformatjsonschema.py + - src/openrouter/models/responseformattextconfig.py + - src/openrouter/models/responseformattextgrammar.py + - src/openrouter/models/responseinputaudio.py + - src/openrouter/models/responseinputfile.py + - src/openrouter/models/responseinputimage.py + - src/openrouter/models/responseinputtext.py + - src/openrouter/models/responseoutputtext.py + - src/openrouter/models/responseserrorfield.py + - src/openrouter/models/responsesformatjsonobject.py + - src/openrouter/models/responsesformattext.py + - src/openrouter/models/responsesformattextjsonschemaconfig.py + - src/openrouter/models/responsesimagegenerationcall.py + - src/openrouter/models/responsesoutputitem.py + - src/openrouter/models/responsesoutputitemfilesearchcall.py + - src/openrouter/models/responsesoutputitemfunctioncall.py + - src/openrouter/models/responsesoutputitemreasoning.py + - src/openrouter/models/responsesoutputmessage.py + - src/openrouter/models/responsessearchcontextsize.py + - src/openrouter/models/responseswebsearchcalloutput.py + - src/openrouter/models/responseswebsearchuserlocation.py + - src/openrouter/models/responsetextconfig.py + - src/openrouter/models/security.py + - src/openrouter/models/sendchatcompletionrequestop.py + - src/openrouter/models/serviceunavailableresponseerrordata.py + - src/openrouter/models/systemmessage.py + - src/openrouter/models/toolcallstatus.py + - src/openrouter/models/tooldefinitionjson.py + - src/openrouter/models/toolresponsemessage.py + - src/openrouter/models/toomanyrequestsresponseerrordata.py + - src/openrouter/models/topproviderinfo.py + - src/openrouter/models/unauthorizedresponseerrordata.py + - src/openrouter/models/unprocessableentityresponseerrordata.py + - src/openrouter/models/updatekeysop.py + - src/openrouter/models/urlcitation.py + - src/openrouter/models/usermessage.py + - src/openrouter/models/websearchpreviewtooluserlocation.py + - src/openrouter/models/websearchstatus.py + - src/openrouter/models_.py + - src/openrouter/oauth.py + - src/openrouter/parameters.py + - src/openrouter/providers.py + - src/openrouter/py.typed + - src/openrouter/responses.py + - src/openrouter/sdk.py + - src/openrouter/sdkconfiguration.py + - src/openrouter/types/__init__.py + - src/openrouter/types/basemodel.py + - src/openrouter/utils/__init__.py + - src/openrouter/utils/annotations.py + - src/openrouter/utils/datetimes.py + - src/openrouter/utils/enums.py + - src/openrouter/utils/eventstreaming.py + - src/openrouter/utils/forms.py + - src/openrouter/utils/headers.py + - src/openrouter/utils/logger.py + - src/openrouter/utils/metadata.py + - src/openrouter/utils/queryparams.py + - src/openrouter/utils/requestbodies.py + - src/openrouter/utils/retries.py + - src/openrouter/utils/security.py + - src/openrouter/utils/serializers.py + - src/openrouter/utils/unmarshal_json_response.py + - src/openrouter/utils/url.py + - src/openrouter/utils/values.py +examples: + createResponses: + speakeasy-default-create-responses: + requestBody: + application/json: {"input": [{"type": "message", "role": "user", "content": "Hello, how are you?"}], "tools": [{"type": "function", "name": "get_current_weather", "description": "Get the current weather in a given location", "parameters": {"type": "object", "properties": {"location": {"type": "string"}}}}], "model": "anthropic/claude-4.5-sonnet-20250929", "temperature": 0.7, "top_p": 0.9, "stream": false} + responses: + "200": + application/json: {"id": "resp-abc123", "object": "response", "created_at": 1704067200, "model": "gpt-4", "status": "completed", "output": [{"id": "msg-abc123", "role": "assistant", "type": "message", "status": "completed", "content": [{"type": "output_text", "text": "Hello! How can I help you today?", "annotations": []}]}], "error": null, "incomplete_details": null, "usage": {"input_tokens": 10, "input_tokens_details": {"cached_tokens": 0}, "output_tokens": 25, "output_tokens_details": {"reasoning_tokens": 0}, "total_tokens": 35}, "max_output_tokens": null, "temperature": null, "top_p": null, "instructions": null, "metadata": null, "tools": [], "tool_choice": "auto", "parallel_tool_calls": true} + "400": + application/json: {"error": {"code": 400, "message": "Invalid request parameters"}} + "401": + application/json: {"error": {"code": 401, "message": "Missing Authentication header"}} + "402": + application/json: {"error": {"code": 402, "message": "Insufficient credits. Add more using https://openrouter.ai/credits"}} + "404": + application/json: {"error": {"code": 404, "message": "Resource not found"}} + "408": + application/json: {"error": {"code": 408, "message": "Operation timed out. Please try again later."}} + "413": + application/json: {"error": {"code": 413, "message": "Request payload too large"}} + "422": + application/json: {"error": {"code": 422, "message": "Invalid argument"}} + "429": + application/json: {"error": {"code": 429, "message": "Rate limit exceeded"}} + "500": + application/json: {"error": {"code": 500, "message": "Internal Server Error"}} + "502": + application/json: {"error": {"code": 502, "message": "Provider returned error"}} + "503": + application/json: {"error": {"code": 503, "message": "Service temporarily unavailable"}} + "524": + application/json: {"error": {"code": 524, "message": "Request timed out. Please try again later."}} + "529": + application/json: {"error": {"code": 529, "message": "Provider returned error"}} + getUserActivity: + speakeasy-default-get-user-activity: + parameters: + query: + date: "2025-08-24" + responses: + "200": + application/json: {"data": [{"date": "2025-08-24", "model": "openai/gpt-4.1", "model_permaslug": "openai/gpt-4.1-2025-04-14", "endpoint_id": "550e8400-e29b-41d4-a716-446655440000", "provider_name": "OpenAI", "usage": 0.015, "byok_usage_inference": 0.012, "requests": 5, "prompt_tokens": 50, "completion_tokens": 125, "reasoning_tokens": 25}]} + "400": + application/json: {"error": {"code": 400, "message": "Invalid request parameters"}} + "401": + application/json: {"error": {"code": 401, "message": "Missing Authentication header"}} + "403": + application/json: {"error": {"code": 403, "message": "Only provisioning keys can perform this operation"}} + "500": + application/json: {"error": {"code": 500, "message": "Internal Server Error"}} + getCredits: + speakeasy-default-get-credits: + responses: + "200": + application/json: {} + "401": + application/json: {"error": {"code": 401, "message": "Missing Authentication header"}} + "403": + application/json: {"error": {"code": 403, "message": "Only provisioning keys can perform this operation"}} + "500": + application/json: {"error": {"code": 500, "message": "Internal Server Error"}} + createCoinbaseCharge: + speakeasy-default-create-coinbase-charge: + requestBody: + application/json: {"amount": 100, "sender": "0x1234567890123456789012345678901234567890", "chain_id": 1} + responses: + "200": + application/json: {"data": {"id": "", "created_at": "1706396327532", "expires_at": "1739956049454", "web3_data": {"transfer_intent": {"call_data": {"deadline": "", "fee_amount": "", "id": "", "operator": "", "prefix": "", "recipient": "", "recipient_amount": "", "recipient_currency": "", "refund_destination": "", "signature": ""}, "metadata": {"chain_id": 3470.69, "contract_address": "", "sender": ""}}}}} + "400": + application/json: {"error": {"code": 400, "message": "Invalid request parameters"}} + "401": + application/json: {"error": {"code": 401, "message": "Missing Authentication header"}} + "429": + application/json: {"error": {"code": 429, "message": "Rate limit exceeded"}} + "500": + application/json: {"error": {"code": 500, "message": "Internal Server Error"}} + createEmbeddings: + speakeasy-default-create-embeddings: + requestBody: + application/json: {"input": "", "model": "Taurus", "provider": {"data_collection": "deny", "zdr": true, "enforce_distillable_text": true, "order": ["OpenAI"], "only": ["OpenAI"], "ignore": ["OpenAI"], "quantizations": ["fp16"], "sort": "price"}} + responses: + "200": + application/json: {"object": "list", "data": [], "model": "Land Cruiser"} + text/event-stream: "" + "400": + application/json: {"error": {"code": 400, "message": "Invalid request parameters"}} + "401": + application/json: {"error": {"code": 401, "message": "Missing Authentication header"}} + "402": + application/json: {"error": {"code": 402, "message": "Insufficient credits. Add more using https://openrouter.ai/credits"}} + "404": + application/json: {"error": {"code": 404, "message": "Resource not found"}} + "429": + application/json: {"error": {"code": 429, "message": "Rate limit exceeded"}} + "500": + application/json: {"error": {"code": 500, "message": "Internal Server Error"}} + "502": + application/json: {"error": {"code": 502, "message": "Provider returned error"}} + "503": + application/json: {"error": {"code": 503, "message": "Service temporarily unavailable"}} + "524": + application/json: {"error": {"code": 524, "message": "Request timed out. Please try again later."}} + "529": + application/json: {"error": {"code": 529, "message": "Provider returned error"}} + listEmbeddingsModels: + speakeasy-default-list-embeddings-models: + responses: + "200": + application/json: {"data": [{"id": "openai/gpt-4", "canonical_slug": "openai/gpt-4", "name": "GPT-4", "created": 1692901234, "description": "GPT-4 is a large multimodal model that can solve difficult problems with greater accuracy.", "pricing": {"prompt": "0.00003", "completion": "0.00006", "request": "0", "image": "0"}, "context_length": 8192, "architecture": {"tokenizer": "GPT", "instruct_type": "chatml", "modality": "text->text", "input_modalities": ["text"], "output_modalities": ["text"]}, "top_provider": {"context_length": 8192, "max_completion_tokens": 4096, "is_moderated": true}, "per_request_limits": null, "supported_parameters": ["temperature", "top_p", "max_tokens", "frequency_penalty", "presence_penalty"], "default_parameters": null}]} + "400": + application/json: {"error": {"code": 400, "message": "Invalid request parameters"}} + "500": + application/json: {"error": {"code": 500, "message": "Internal Server Error"}} + getGeneration: + speakeasy-default-get-generation: + parameters: + query: + id: "" + responses: + "200": + application/json: {"data": {"id": "gen-3bhGkxlo4XFrqiabUM7NDtwDzWwG", "upstream_id": "chatcmpl-791bcf62-080e-4568-87d0-94c72e3b4946", "total_cost": 0.0015, "cache_discount": 0.0002, "upstream_inference_cost": 0.0012, "created_at": "2024-07-15T23:33:19.433273+00:00", "model": "sao10k/l3-stheno-8b", "app_id": 12345, "streamed": true, "cancelled": false, "provider_name": "Infermatic", "latency": 1250, "moderation_latency": 50, "generation_time": 1200, "finish_reason": "stop", "tokens_prompt": 10, "tokens_completion": 25, "native_tokens_prompt": 10, "native_tokens_completion": 25, "native_tokens_completion_images": 0, "native_tokens_reasoning": 5, "native_tokens_cached": 3, "num_media_prompt": 1, "num_input_audio_prompt": 0, "num_media_completion": 0, "num_search_results": 5, "origin": "https://openrouter.ai/", "usage": 0.0015, "is_byok": false, "native_finish_reason": "stop", "external_user": "user-123", "api_type": "completions"}} + "401": + application/json: {"error": {"code": 401, "message": "Missing Authentication header"}} + "402": + application/json: {"error": {"code": 402, "message": "Insufficient credits. Add more using https://openrouter.ai/credits"}} + "404": + application/json: {"error": {"code": 404, "message": "Resource not found"}} + "429": + application/json: {"error": {"code": 429, "message": "Rate limit exceeded"}} + "500": + application/json: {"error": {"code": 500, "message": "Internal Server Error"}} + "502": + application/json: {"error": {"code": 502, "message": "Provider returned error"}} + "524": + application/json: {"error": {"code": 524, "message": "Request timed out. Please try again later."}} + "529": + application/json: {"error": {"code": 529, "message": "Provider returned error"}} + listModelsCount: + speakeasy-default-list-models-count: + responses: + "200": + application/json: {"data": {"count": 150}} + "500": + application/json: {"error": {"code": 500, "message": "Internal Server Error"}} + getModels: + speakeasy-default-get-models: + responses: + "200": + application/json: {"data": [{"id": "openai/gpt-4", "canonical_slug": "openai/gpt-4", "name": "GPT-4", "created": 1692901234, "description": "GPT-4 is a large multimodal model that can solve difficult problems with greater accuracy.", "pricing": {"prompt": "0.00003", "completion": "0.00006", "request": "0", "image": "0"}, "context_length": 8192, "architecture": {"tokenizer": "GPT", "instruct_type": "chatml", "modality": "text->text", "input_modalities": ["text"], "output_modalities": ["text"]}, "top_provider": {"context_length": 8192, "max_completion_tokens": 4096, "is_moderated": true}, "per_request_limits": null, "supported_parameters": ["temperature", "top_p", "max_tokens", "frequency_penalty", "presence_penalty"], "default_parameters": null}]} + "400": + application/json: {"error": {"code": 400, "message": "Invalid request parameters"}} + "500": + application/json: {"error": {"code": 500, "message": "Internal Server Error"}} + listModelsUser: + speakeasy-default-list-models-user: + responses: + "200": + application/json: {"data": [{"id": "openai/gpt-4", "canonical_slug": "openai/gpt-4", "name": "GPT-4", "created": 1692901234, "description": "GPT-4 is a large multimodal model that can solve difficult problems with greater accuracy.", "pricing": {"prompt": "0.00003", "completion": "0.00006", "request": "0", "image": "0"}, "context_length": 8192, "architecture": {"tokenizer": "GPT", "instruct_type": "chatml", "modality": "text->text", "input_modalities": ["text"], "output_modalities": ["text"]}, "top_provider": {"context_length": 8192, "max_completion_tokens": 4096, "is_moderated": true}, "per_request_limits": null, "supported_parameters": ["temperature", "top_p", "max_tokens", "frequency_penalty", "presence_penalty"], "default_parameters": null}]} + "401": + application/json: {"error": {"code": 401, "message": "Missing Authentication header"}} + "500": + application/json: {"error": {"code": 500, "message": "Internal Server Error"}} + listEndpoints: + speakeasy-default-list-endpoints: + parameters: + path: + author: "" + slug: "" + responses: + "200": + application/json: {"data": {"id": "openai/gpt-4", "name": "GPT-4", "created": 1692901234, "description": "GPT-4 is a large multimodal model that can solve difficult problems with greater accuracy.", "architecture": {"tokenizer": "GPT", "instruct_type": "chatml", "modality": "text->text", "input_modalities": ["text"], "output_modalities": ["text"]}, "endpoints": [{"name": "OpenAI: GPT-4", "model_name": "GPT-4", "context_length": 8192, "pricing": {"prompt": "0.00003", "completion": "0.00006", "request": "0", "image": "0"}, "provider_name": "OpenAI", "tag": "openai", "quantization": "fp16", "max_completion_tokens": 4096, "max_prompt_tokens": 8192, "supported_parameters": ["temperature", "top_p", "max_tokens", "frequency_penalty", "presence_penalty"], "status": -3, "uptime_last_30m": 99.5, "supports_implicit_caching": true}]}} + "404": + application/json: {"error": {"code": 404, "message": "Resource not found"}} + "500": + application/json: {"error": {"code": 500, "message": "Internal Server Error"}} + listEndpointsZdr: + speakeasy-default-list-endpoints-zdr: + responses: + "200": + application/json: {"data": [{"name": "OpenAI: GPT-4", "model_name": "GPT-4", "context_length": 8192, "pricing": {"prompt": "0.00003", "completion": "0.00006", "request": "0", "image": "0"}, "provider_name": "OpenAI", "tag": "openai", "quantization": "fp16", "max_completion_tokens": 4096, "max_prompt_tokens": 8192, "supported_parameters": ["temperature", "top_p", "max_tokens"], "status": 0, "uptime_last_30m": 99.5, "supports_implicit_caching": true}]} + "500": + application/json: {"error": {"code": 500, "message": "Internal Server Error"}} + getParameters: + speakeasy-default-get-parameters: + parameters: + path: + author: "" + slug: "" + responses: + "200": + application/json: {"data": {"model": "openai/gpt-4", "supported_parameters": ["temperature", "top_p", "max_tokens"]}} + "401": + application/json: {"error": {"code": 401, "message": "Missing Authentication header"}} + "404": + application/json: {"error": {"code": 404, "message": "Resource not found"}} + "500": + application/json: {"error": {"code": 500, "message": "Internal Server Error"}} + listProviders: + speakeasy-default-list-providers: + responses: + "200": + application/json: {"data": [{"name": "OpenAI", "slug": "openai", "privacy_policy_url": "https://openai.com/privacy", "terms_of_service_url": "https://openai.com/terms", "status_page_url": "https://status.openai.com"}]} + "500": + application/json: {"error": {"code": 500, "message": "Internal Server Error"}} + list: + speakeasy-default-list: + parameters: + query: + include_disabled: "false" + offset: "0" + responses: + "200": + application/json: {"data": [{"hash": "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", "name": "My Production Key", "label": "Production API Key", "disabled": false, "limit": 100, "limit_remaining": 74.5, "limit_reset": "monthly", "include_byok_in_limit": false, "usage": 25.5, "usage_daily": 25.5, "usage_weekly": 25.5, "usage_monthly": 25.5, "byok_usage": 17.38, "byok_usage_daily": 17.38, "byok_usage_weekly": 17.38, "byok_usage_monthly": 17.38, "created_at": "2025-08-24T10:30:00Z", "updated_at": "2025-08-24T15:45:00Z", "expires_at": "2027-12-31T23:59:59Z"}]} + "401": + application/json: {"error": {"code": 401, "message": "Missing Authentication header"}} + "429": + application/json: {"error": {"code": 429, "message": "Rate limit exceeded"}} + "500": + application/json: {"error": {"code": 500, "message": "Internal Server Error"}} + createKeys: + speakeasy-default-create-keys: + requestBody: + application/json: {"name": "My New API Key", "limit": 50, "limit_reset": "monthly", "include_byok_in_limit": true, "expires_at": "2027-12-31T23:59:59Z"} + responses: + "201": + application/json: {"data": {"hash": "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", "name": "My New API Key", "label": "My New API Key", "disabled": false, "limit": 50, "limit_remaining": 50, "limit_reset": "monthly", "include_byok_in_limit": true, "usage": 0, "usage_daily": 0, "usage_weekly": 0, "usage_monthly": 0, "byok_usage": 0, "byok_usage_daily": 0, "byok_usage_weekly": 0, "byok_usage_monthly": 0, "created_at": "2025-08-24T10:30:00Z", "updated_at": null, "expires_at": "2027-12-31T23:59:59Z"}, "key": "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"} + "400": + application/json: {"error": {"code": 400, "message": "Invalid request parameters"}} + "401": + application/json: {"error": {"code": 401, "message": "Missing Authentication header"}} + "429": + application/json: {"error": {"code": 429, "message": "Rate limit exceeded"}} + "500": + application/json: {"error": {"code": 500, "message": "Internal Server Error"}} + updateKeys: + speakeasy-default-update-keys: + parameters: + path: + hash: "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" + requestBody: + application/json: {"name": "Updated API Key Name", "disabled": false, "limit": 75, "limit_reset": "daily", "include_byok_in_limit": true} + responses: + "200": + application/json: {"data": {"hash": "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", "name": "Updated API Key Name", "label": "Updated API Key Name", "disabled": false, "limit": 75, "limit_remaining": 49.5, "limit_reset": "daily", "include_byok_in_limit": true, "usage": 25.5, "usage_daily": 25.5, "usage_weekly": 25.5, "usage_monthly": 25.5, "byok_usage": 17.38, "byok_usage_daily": 17.38, "byok_usage_weekly": 17.38, "byok_usage_monthly": 17.38, "created_at": "2025-08-24T10:30:00Z", "updated_at": "2025-08-24T16:00:00Z", "expires_at": null}} + "400": + application/json: {"error": {"code": 400, "message": "Invalid request parameters"}} + "401": + application/json: {"error": {"code": 401, "message": "Missing Authentication header"}} + "404": + application/json: {"error": {"code": 404, "message": "Resource not found"}} + "429": + application/json: {"error": {"code": 429, "message": "Rate limit exceeded"}} + "500": + application/json: {"error": {"code": 500, "message": "Internal Server Error"}} + deleteKeys: + speakeasy-default-delete-keys: + parameters: + path: + hash: "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" + responses: + "200": + application/json: {"deleted": true} + "401": + application/json: {"error": {"code": 401, "message": "Missing Authentication header"}} + "404": + application/json: {"error": {"code": 404, "message": "Resource not found"}} + "429": + application/json: {"error": {"code": 429, "message": "Rate limit exceeded"}} + "500": + application/json: {"error": {"code": 500, "message": "Internal Server Error"}} + getKey: + speakeasy-default-get-key: + parameters: + path: + hash: "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" + responses: + "200": + application/json: {"data": {"hash": "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", "name": "My Production Key", "label": "Production API Key", "disabled": false, "limit": 100, "limit_remaining": 74.5, "limit_reset": "monthly", "include_byok_in_limit": false, "usage": 25.5, "usage_daily": 25.5, "usage_weekly": 25.5, "usage_monthly": 25.5, "byok_usage": 17.38, "byok_usage_daily": 17.38, "byok_usage_weekly": 17.38, "byok_usage_monthly": 17.38, "created_at": "2025-08-24T10:30:00Z", "updated_at": "2025-08-24T15:45:00Z", "expires_at": "2027-12-31T23:59:59Z"}} + "401": + application/json: {"error": {"code": 401, "message": "Missing Authentication header"}} + "404": + application/json: {"error": {"code": 404, "message": "Resource not found"}} + "429": + application/json: {"error": {"code": 429, "message": "Rate limit exceeded"}} + "500": + application/json: {"error": {"code": 500, "message": "Internal Server Error"}} + getCurrentKey: + speakeasy-default-get-current-key: + responses: + "200": + application/json: {"data": {"label": "sk-or-v1-au78b3456789012345678901234567890", "limit": 100, "usage": 25.5, "usage_daily": 25.5, "usage_weekly": 25.5, "usage_monthly": 25.5, "byok_usage": 17.38, "byok_usage_daily": 17.38, "byok_usage_weekly": 17.38, "byok_usage_monthly": 17.38, "is_free_tier": false, "is_provisioning_key": false, "limit_remaining": 74.5, "limit_reset": "monthly", "include_byok_in_limit": false, "expires_at": "2027-12-31T23:59:59Z", "rate_limit": {"requests": 1000, "interval": "1h", "note": "This field is deprecated and safe to ignore."}}} + "401": + application/json: {"error": {"code": 401, "message": "Missing Authentication header"}} + "500": + application/json: {"error": {"code": 500, "message": "Internal Server Error"}} + exchangeAuthCodeForAPIKey: + speakeasy-default-exchange-auth-code-for-API-key: + requestBody: + application/json: {"code": "auth_code_abc123def456", "code_verifier": "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk", "code_challenge_method": "S256"} + responses: + "200": + application/json: {"key": "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", "user_id": "user_2yOPcMpKoQhcd4bVgSMlELRaIah"} + "400": + application/json: {"error": {"code": 400, "message": "Invalid request parameters"}} + "403": + application/json: {"error": {"code": 403, "message": "Only provisioning keys can perform this operation"}} + "500": + application/json: {"error": {"code": 500, "message": "Internal Server Error"}} + createAuthKeysCode: + speakeasy-default-create-auth-keys-code: + requestBody: + application/json: {"callback_url": "https://myapp.com/auth/callback", "code_challenge": "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM", "code_challenge_method": "S256", "limit": 100} + responses: + "200": + application/json: {"data": {"id": "auth_code_xyz789", "app_id": 12345, "created_at": "2025-08-24T10:30:00Z"}} + "400": + application/json: {"error": {"code": 400, "message": "Invalid request parameters"}} + "401": + application/json: {"error": {"code": 401, "message": "Missing Authentication header"}} + "500": + application/json: {"error": {"code": 500, "message": "Internal Server Error"}} + sendChatCompletionRequest: + speakeasy-default-send-chat-completion-request: + requestBody: + application/json: {"messages": [], "stream": false} + responses: + "200": + application/json: {"id": "", "choices": [], "created": 6524.91, "model": "Silverado", "object": "chat.completion"} + "400": + application/json: {"error": {"code": "", "message": ""}} + "500": + application/json: {"error": {"code": "", "message": ""}} + createCompletions: + speakeasy-default-create-completions: + requestBody: + application/json: {"prompt": [], "stream": false} + responses: + "200": + application/json: {"id": "", "object": "text_completion", "created": 7524.07, "model": "Aventador", "choices": [{"text": "", "index": 4622.44, "logprobs": {"tokens": [], "token_logprobs": [], "top_logprobs": [{"key": 6481.8, "key1": 6211.86, "key2": 4822.58}, {}, {"key": 6295.32, "key1": 8110.56, "key2": 5430.28}], "text_offset": [8533.93, 4728.06, 5798.08]}, "finish_reason": "length"}]} + "400": + application/json: {"error": {"code": "", "message": ""}} + "500": + application/json: {"error": {"code": "", "message": ""}} +examplesVersion: 1.0.2 diff --git a/.speakeasy/gen.yaml b/.speakeasy/gen.yaml new file mode 100644 index 0000000..0c1c40d --- /dev/null +++ b/.speakeasy/gen.yaml @@ -0,0 +1,77 @@ +configVersion: 2.0.0 +generation: + devContainers: + enabled: true + schemaPath: .speakeasy/out.openapi.yaml + sdkClassName: OpenRouter + maintainOpenAPIOrder: true + usageSnippets: + optionalPropertyRendering: withExample + sdkInitStyle: constructor + useClassNamesForArrayFields: true + fixes: + nameResolutionDec2023: true + nameResolutionFeb2025: true + parameterOrderingFeb2024: true + requestResponseComponentNamesFeb2024: true + securityFeb2025: true + sharedErrorComponentsApr2025: true + auth: + oAuth2ClientCredentialsEnabled: true + oAuth2PasswordEnabled: true + hoistGlobalSecurity: true + inferSSEOverload: true + sdkHooksConfigAccess: true + schemas: + allOfMergeStrategy: shallowMerge + requestBodyFieldName: body + tests: + generateTests: false + generateNewTests: true + skipResponseBodyAssertions: false +python: + version: 0.0.1 + additionalDependencies: + dev: {} + main: {} + allowedRedefinedBuiltins: + - id + - object + - input + asyncMode: both + authors: + - Speakeasy + baseErrorName: OpenRouterError + clientServerStatusCodesAsErrors: true + defaultErrorName: OpenRouterDefaultError + description: Python Client SDK Generated by Speakeasy. + enableCustomCodeRegions: false + enumFormat: union + envVarPrefix: OPENROUTER + fixFlags: + asyncPaginationSep2025: true + responseRequiredSep2024: true + flattenGlobalSecurity: true + flattenRequests: true + flatteningOrder: parameters-first + imports: + option: openapi + paths: + callbacks: "" + errors: errors + operations: "" + shared: "" + webhooks: "" + inputModelSuffix: input + legacyPyright: false + maxMethodParams: 999 + methodArguments: infer-optional-args + moduleName: "" + outputModelSuffix: output + packageManager: uv + packageName: openrouter + pytestFilterWarnings: [] + pytestTimeout: 0 + responseFormat: flat + sseFlatResponse: false + templateVersion: v2 diff --git a/.speakeasy/out.openapi.yaml b/.speakeasy/out.openapi.yaml new file mode 100644 index 0000000..8cc5737 --- /dev/null +++ b/.speakeasy/out.openapi.yaml @@ -0,0 +1,8371 @@ +openapi: 3.1.0 +info: + title: OpenRouter API + version: 1.0.0 + description: OpenAI-compatible Chat Completions and Completions API with additional OpenRouter features + contact: + name: OpenRouter Support + url: https://openrouter.ai/docs + email: support@openrouter.ai + license: + name: MIT + url: https://opensource.org/licenses/MIT +components: + schemas: + OpenAIResponsesResponseStatus: + type: string + enum: + - completed + - incomplete + - in_progress + - failed + - cancelled + - queued + x-speakeasy-unknown-values: allow + FileCitation: + type: object + properties: + type: + type: string + enum: + - file_citation + file_id: + type: string + filename: + type: string + index: + type: number + required: + - type + - file_id + - filename + - index + example: + type: file_citation + file_id: file-abc123 + filename: research_paper.pdf + index: 0 + URLCitation: + type: object + properties: + type: + type: string + enum: + - url_citation + url: + type: string + title: + type: string + start_index: + type: number + end_index: + type: number + required: + - type + - url + - title + - start_index + - end_index + example: + type: url_citation + start_index: 0 + end_index: 42 + title: OpenRouter Documentation + url: https://openrouter.ai/docs + FilePath: + type: object + properties: + type: + type: string + enum: + - file_path + file_id: + type: string + index: + type: number + required: + - type + - file_id + - index + example: + type: file_path + file_id: file-xyz789 + index: 0 + OpenAIResponsesAnnotation: + anyOf: + - $ref: '#/components/schemas/FileCitation' + - $ref: '#/components/schemas/URLCitation' + - $ref: '#/components/schemas/FilePath' + ResponseOutputText: + type: object + properties: + type: + type: string + enum: + - output_text + text: + type: string + annotations: + type: array + items: + $ref: '#/components/schemas/OpenAIResponsesAnnotation' + required: + - type + - text + example: + type: output_text + text: The capital of France is Paris. + annotations: + - type: url_citation + start_index: 0 + end_index: 42 + title: Paris - Wikipedia + url: https://en.wikipedia.org/wiki/Paris + OpenAIResponsesRefusalContent: + type: object + properties: + type: + type: string + enum: + - refusal + refusal: + type: string + required: + - type + - refusal + example: + type: refusal + refusal: I'm sorry, I cannot assist with that request + OutputMessage: + type: object + properties: + id: + type: string + role: + type: string + enum: + - assistant + type: + type: string + enum: + - message + status: + anyOf: + - type: string + enum: + - completed + - type: string + enum: + - incomplete + - type: string + enum: + - in_progress + content: + type: array + items: + anyOf: + - $ref: '#/components/schemas/ResponseOutputText' + - $ref: '#/components/schemas/OpenAIResponsesRefusalContent' + required: + - id + - role + - type + - content + example: + id: msg-abc123 + role: assistant + type: message + status: completed + content: + - type: output_text + text: Hello! How can I help you today? + ResponsesOutputMessage: + allOf: + - $ref: '#/components/schemas/OutputMessage' + - type: object + properties: {} + example: + id: msg-123 + type: message + role: assistant + status: completed + content: + - type: output_text + text: Hello! How can I help you? + annotations: [] + description: An output message item + ReasoningTextContent: + type: object + properties: + type: + type: string + enum: + - reasoning_text + text: + type: string + required: + - type + - text + example: + type: reasoning_text + text: Let me think step by step about this problem... + ReasoningSummaryText: + type: object + properties: + type: + type: string + enum: + - summary_text + text: + type: string + required: + - type + - text + example: + type: summary_text + text: Analyzed the problem using first principles + OutputItemReasoning: + type: object + properties: + type: + type: string + enum: + - reasoning + id: + type: string + content: + type: array + items: + $ref: '#/components/schemas/ReasoningTextContent' + summary: + type: array + items: + $ref: '#/components/schemas/ReasoningSummaryText' + encrypted_content: + type: string + nullable: true + status: + anyOf: + - type: string + enum: + - completed + - type: string + enum: + - incomplete + - type: string + enum: + - in_progress + required: + - type + - id + - summary + example: + type: reasoning + id: reasoning-abc123 + summary: + - type: summary_text + text: Analyzed the problem using first principles + ResponsesOutputItemReasoning: + allOf: + - $ref: '#/components/schemas/OutputItemReasoning' + - type: object + properties: {} + example: + id: reasoning-123 + type: reasoning + status: completed + summary: + - type: summary_text + text: Analyzed the problem and found the optimal solution. + content: + - type: reasoning_text + text: First, we analyze the problem... + description: An output item containing reasoning + OutputItemFunctionCall: + type: object + properties: + type: + type: string + enum: + - function_call + id: + type: string + name: + type: string + arguments: + type: string + call_id: + type: string + status: + anyOf: + - type: string + enum: + - completed + - type: string + enum: + - incomplete + - type: string + enum: + - in_progress + required: + - type + - name + - arguments + - call_id + example: + type: function_call + id: call-abc123 + name: get_weather + arguments: '{"location":"San Francisco","unit":"celsius"}' + call_id: call-abc123 + ResponsesOutputItemFunctionCall: + allOf: + - $ref: '#/components/schemas/OutputItemFunctionCall' + - type: object + properties: {} + example: + type: function_call + id: call-abc123 + name: get_weather + arguments: '{"location":"San Francisco","unit":"celsius"}' + call_id: call-abc123 + WebSearchStatus: + type: string + enum: + - completed + - searching + - in_progress + - failed + example: completed + x-speakeasy-unknown-values: allow + OutputItemWebSearchCall: + type: object + properties: + type: + type: string + enum: + - web_search_call + id: + type: string + status: + $ref: '#/components/schemas/WebSearchStatus' + required: + - type + - id + - status + example: + type: web_search_call + id: search-abc123 + status: completed + ResponsesWebSearchCallOutput: + allOf: + - $ref: '#/components/schemas/OutputItemWebSearchCall' + - type: object + properties: {} + example: + type: web_search_call + id: search-abc123 + status: completed + OutputItemFileSearchCall: + type: object + properties: + type: + type: string + enum: + - file_search_call + id: + type: string + queries: + type: array + items: + type: string + status: + $ref: '#/components/schemas/WebSearchStatus' + required: + - type + - id + - queries + - status + example: + type: file_search_call + id: filesearch-abc123 + queries: + - machine learning algorithms + - neural networks + status: completed + ResponsesOutputItemFileSearchCall: + allOf: + - $ref: '#/components/schemas/OutputItemFileSearchCall' + - type: object + properties: {} + example: + type: file_search_call + id: filesearch-abc123 + queries: + - machine learning algorithms + - neural networks + status: completed + ImageGenerationStatus: + type: string + enum: + - in_progress + - completed + - generating + - failed + example: completed + x-speakeasy-unknown-values: allow + OutputItemImageGenerationCall: + type: object + properties: + type: + type: string + enum: + - image_generation_call + id: + type: string + result: + type: string + nullable: true + default: null + status: + $ref: '#/components/schemas/ImageGenerationStatus' + required: + - type + - id + - status + example: + type: image_generation_call + id: imagegen-abc123 + result: iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg== + status: completed + ResponsesImageGenerationCall: + allOf: + - $ref: '#/components/schemas/OutputItemImageGenerationCall' + - type: object + properties: {} + example: + type: image_generation_call + id: imagegen-abc123 + result: iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg== + status: completed + ResponsesOutputItem: + anyOf: + - $ref: '#/components/schemas/ResponsesOutputMessage' + - $ref: '#/components/schemas/ResponsesOutputItemReasoning' + - $ref: '#/components/schemas/ResponsesOutputItemFunctionCall' + - $ref: '#/components/schemas/ResponsesWebSearchCallOutput' + - $ref: '#/components/schemas/ResponsesOutputItemFileSearchCall' + - $ref: '#/components/schemas/ResponsesImageGenerationCall' + description: An output item from the response + example: + id: msg-abc123 + role: assistant + type: message + status: completed + content: + - type: output_text + text: Hello! How can I help you today? + ResponsesErrorField: + type: object + nullable: true + properties: + code: + type: string + enum: + - server_error + - rate_limit_exceeded + - invalid_prompt + - vector_store_timeout + - invalid_image + - invalid_image_format + - invalid_base64_image + - invalid_image_url + - image_too_large + - image_too_small + - image_parse_error + - image_content_policy_violation + - invalid_image_mode + - image_file_too_large + - unsupported_image_media_type + - empty_image_file + - failed_to_download_image + - image_file_not_found + x-speakeasy-unknown-values: allow + message: + type: string + required: + - code + - message + description: Error information returned from the API + example: + code: rate_limit_exceeded + message: Rate limit exceeded. Please try again later. + OpenAIResponsesIncompleteDetails: + type: object + nullable: true + properties: + reason: + type: string + enum: + - max_output_tokens + - content_filter + x-speakeasy-unknown-values: allow + OpenAIResponsesUsage: + type: object + properties: + input_tokens: + type: number + input_tokens_details: + type: object + properties: + cached_tokens: + type: number + required: + - cached_tokens + output_tokens: + type: number + output_tokens_details: + type: object + properties: + reasoning_tokens: + type: number + required: + - reasoning_tokens + total_tokens: + type: number + required: + - input_tokens + - input_tokens_details + - output_tokens + - output_tokens_details + - total_tokens + OpenResponsesUsage: + allOf: + - $ref: '#/components/schemas/OpenAIResponsesUsage' + - type: object + properties: + cost: + type: number + nullable: true + description: Cost of the completion + is_byok: + type: boolean + description: Whether a request was made using a Bring Your Own Key configuration + cost_details: + type: object + properties: + upstream_inference_cost: + type: number + nullable: true + upstream_inference_input_cost: + type: number + upstream_inference_output_cost: + type: number + required: + - upstream_inference_input_cost + - upstream_inference_output_cost + description: Token usage information for the response + example: + input_tokens: 10 + output_tokens: 25 + total_tokens: 35 + input_tokens_details: + cached_tokens: 0 + output_tokens_details: + reasoning_tokens: 0 + cost: 0.0012 + cost_details: + upstream_inference_cost: null + upstream_inference_input_cost: 0.0008 + upstream_inference_output_cost: 0.0004 + ResponseInputText: + type: object + properties: + type: + type: string + enum: + - input_text + text: + type: string + required: + - type + - text + description: Text input content item + example: + type: input_text + text: Hello, how can I help you? + ResponseInputImage: + type: object + properties: + type: + type: string + enum: + - input_image + detail: + type: string + enum: + - auto + - high + - low + x-speakeasy-unknown-values: allow + image_url: + type: string + nullable: true + required: + - type + - detail + description: Image input content item + example: + type: input_image + detail: auto + image_url: https://example.com/image.jpg + ResponseInputFile: + type: object + properties: + type: + type: string + enum: + - input_file + file_id: + type: string + nullable: true + file_data: + type: string + filename: + type: string + file_url: + type: string + required: + - type + description: File input content item + example: + type: input_file + file_id: file-abc123 + filename: document.pdf + ResponseInputAudio: + type: object + properties: + type: + type: string + enum: + - input_audio + input_audio: + type: object + properties: + data: + type: string + format: + type: string + enum: + - mp3 + - wav + x-speakeasy-unknown-values: allow + required: + - data + - format + required: + - type + - input_audio + description: Audio input content item + example: + type: input_audio + input_audio: + data: SGVsbG8gV29ybGQ= + format: mp3 + ToolCallStatus: + type: string + nullable: true + enum: + - in_progress + - completed + - incomplete + example: completed + x-speakeasy-unknown-values: allow + OpenAIResponsesInput: + anyOf: + - type: string + - type: array + items: + anyOf: + - type: object + properties: + type: + type: string + enum: + - message + role: + anyOf: + - type: string + enum: + - user + - type: string + enum: + - system + - type: string + enum: + - assistant + - type: string + enum: + - developer + content: + anyOf: + - type: array + items: + oneOf: + - $ref: '#/components/schemas/ResponseInputText' + - $ref: '#/components/schemas/ResponseInputImage' + - $ref: '#/components/schemas/ResponseInputFile' + - $ref: '#/components/schemas/ResponseInputAudio' + discriminator: + propertyName: type + mapping: + input_text: '#/components/schemas/ResponseInputText' + input_image: '#/components/schemas/ResponseInputImage' + input_file: '#/components/schemas/ResponseInputFile' + input_audio: '#/components/schemas/ResponseInputAudio' + - type: string + required: + - role + - content + - type: object + properties: + id: + type: string + type: + type: string + enum: + - message + role: + anyOf: + - type: string + enum: + - user + - type: string + enum: + - system + - type: string + enum: + - developer + content: + type: array + items: + oneOf: + - $ref: '#/components/schemas/ResponseInputText' + - $ref: '#/components/schemas/ResponseInputImage' + - $ref: '#/components/schemas/ResponseInputFile' + - $ref: '#/components/schemas/ResponseInputAudio' + discriminator: + propertyName: type + mapping: + input_text: '#/components/schemas/ResponseInputText' + input_image: '#/components/schemas/ResponseInputImage' + input_file: '#/components/schemas/ResponseInputFile' + input_audio: '#/components/schemas/ResponseInputAudio' + required: + - id + - role + - content + - type: object + properties: + type: + type: string + enum: + - function_call_output + id: + type: string + nullable: true + call_id: + type: string + output: + type: string + status: + $ref: '#/components/schemas/ToolCallStatus' + required: + - type + - call_id + - output + - type: object + properties: + type: + type: string + enum: + - function_call + call_id: + type: string + name: + type: string + arguments: + type: string + id: + type: string + status: + $ref: '#/components/schemas/ToolCallStatus' + required: + - type + - call_id + - name + - arguments + - $ref: '#/components/schemas/OutputItemImageGenerationCall' + - $ref: '#/components/schemas/OutputMessage' + - nullable: true + OpenResponsesRequestMetadata: + type: object + nullable: true + additionalProperties: + type: string + maxLength: 512 + description: >- + Metadata key-value pairs for the request. Keys must be ≤64 characters and cannot contain brackets. Values must be ≤512 characters. Maximum 16 pairs allowed. + example: + user_id: '123' + session_id: abc-def-ghi + OpenResponsesFunctionTool: + type: object + properties: + type: + type: string + enum: + - function + name: + type: string + description: + type: string + nullable: true + strict: + type: boolean + nullable: true + parameters: + type: object + nullable: true + additionalProperties: + nullable: true + required: + - type + - name + - parameters + description: Function tool definition + example: + type: function + name: get_weather + description: Get the current weather in a location + parameters: + type: object + properties: + location: + type: string + description: The city and state + unit: + type: string + enum: + - celsius + - fahrenheit + x-speakeasy-unknown-values: allow + required: + - location + ResponsesSearchContextSize: + type: string + enum: + - low + - medium + - high + description: Size of the search context for web search tools + example: medium + x-speakeasy-unknown-values: allow + WebSearchPreviewToolUserLocation: + type: object + nullable: true + properties: + type: + type: string + enum: + - approximate + city: + type: string + nullable: true + country: + type: string + nullable: true + region: + type: string + nullable: true + timezone: + type: string + nullable: true + required: + - type + OpenResponsesWebSearchPreviewTool: + type: object + properties: + type: + type: string + enum: + - web_search_preview + search_context_size: + $ref: '#/components/schemas/ResponsesSearchContextSize' + user_location: + $ref: '#/components/schemas/WebSearchPreviewToolUserLocation' + required: + - type + description: Web search preview tool configuration + example: + type: web_search_preview + OpenResponsesWebSearchPreview20250311Tool: + type: object + properties: + type: + type: string + enum: + - web_search_preview_2025_03_11 + search_context_size: + $ref: '#/components/schemas/ResponsesSearchContextSize' + user_location: + $ref: '#/components/schemas/WebSearchPreviewToolUserLocation' + required: + - type + description: Web search preview tool configuration (2025-03-11 version) + example: + type: web_search_preview_2025_03_11 + ResponsesWebSearchUserLocation: + type: object + nullable: true + properties: + type: + type: string + enum: + - approximate + city: + type: string + nullable: true + country: + type: string + nullable: true + region: + type: string + nullable: true + timezone: + type: string + nullable: true + description: User location information for web search + example: + type: approximate + city: San Francisco + country: USA + region: California + timezone: America/Los_Angeles + OpenResponsesWebSearchTool: + type: object + properties: + type: + type: string + enum: + - web_search + filters: + type: object + nullable: true + properties: + allowed_domains: + type: array + nullable: true + items: + type: string + search_context_size: + $ref: '#/components/schemas/ResponsesSearchContextSize' + user_location: + $ref: '#/components/schemas/ResponsesWebSearchUserLocation' + required: + - type + description: Web search tool configuration + example: + type: web_search + filters: + allowed_domains: + - example.com + OpenResponsesWebSearch20250826Tool: + type: object + properties: + type: + type: string + enum: + - web_search_2025_08_26 + filters: + type: object + nullable: true + properties: + allowed_domains: + type: array + nullable: true + items: + type: string + search_context_size: + $ref: '#/components/schemas/ResponsesSearchContextSize' + user_location: + $ref: '#/components/schemas/ResponsesWebSearchUserLocation' + required: + - type + description: Web search tool configuration (2025-08-26 version) + example: + type: web_search_2025_08_26 + filters: + allowed_domains: + - example.com + OpenAIResponsesToolChoice: + anyOf: + - type: string + enum: + - auto + - type: string + enum: + - none + - type: string + enum: + - required + - type: object + properties: + type: + type: string + enum: + - function + name: + type: string + required: + - type + - name + - type: object + properties: + type: + anyOf: + - type: string + enum: + - web_search_preview_2025_03_11 + - type: string + enum: + - web_search_preview + required: + - type + OpenAIResponsesPrompt: + type: object + nullable: true + properties: + id: + type: string + variables: + type: object + nullable: true + additionalProperties: + anyOf: + - type: string + - $ref: '#/components/schemas/ResponseInputText' + - $ref: '#/components/schemas/ResponseInputImage' + - $ref: '#/components/schemas/ResponseInputFile' + required: + - id + OpenAIResponsesReasoningEffort: + type: string + nullable: true + enum: + - high + - medium + - low + - minimal + x-speakeasy-unknown-values: allow + ReasoningSummaryVerbosity: + type: string + enum: + - auto + - concise + - detailed + x-speakeasy-unknown-values: allow + OpenAIResponsesReasoningConfig: + type: object + nullable: true + properties: + effort: + $ref: '#/components/schemas/OpenAIResponsesReasoningEffort' + summary: + $ref: '#/components/schemas/ReasoningSummaryVerbosity' + OpenAIResponsesServiceTier: + type: string + nullable: true + enum: + - auto + - default + - flex + - priority + - scale + x-speakeasy-unknown-values: allow + OpenAIResponsesTruncation: + type: string + nullable: true + enum: + - auto + - disabled + x-speakeasy-unknown-values: allow + ResponsesFormatText: + type: object + properties: + type: + type: string + enum: + - text + required: + - type + description: Plain text response format + example: + type: text + ResponsesFormatJSONObject: + type: object + properties: + type: + type: string + enum: + - json_object + required: + - type + description: JSON object response format + example: + type: json_object + ResponsesFormatTextJSONSchemaConfig: + type: object + properties: + type: + type: string + enum: + - json_schema + name: + type: string + description: + type: string + strict: + type: boolean + nullable: true + schema: + type: object + additionalProperties: + nullable: true + required: + - type + - name + - schema + description: JSON schema constrained response format + example: + type: json_schema + name: user_info + description: User information schema + schema: + type: object + properties: + name: + type: string + age: + type: number + required: + - name + ResponseFormatTextConfig: + anyOf: + - $ref: '#/components/schemas/ResponsesFormatText' + - $ref: '#/components/schemas/ResponsesFormatJSONObject' + - $ref: '#/components/schemas/ResponsesFormatTextJSONSchemaConfig' + description: Text response format configuration + example: + type: text + ResponseTextConfig: + type: object + properties: + format: + $ref: '#/components/schemas/ResponseFormatTextConfig' + verbosity: + type: string + nullable: true + enum: + - high + - low + - medium + x-speakeasy-unknown-values: allow + description: Text output configuration including format and verbosity + example: + format: + type: text + verbosity: medium + OpenAIResponsesNonStreamingResponse: + type: object + properties: + id: + type: string + object: + type: string + enum: + - response + created_at: + type: number + model: + type: string + status: + $ref: '#/components/schemas/OpenAIResponsesResponseStatus' + output: + type: array + items: + oneOf: + - $ref: '#/components/schemas/OutputMessage' + - $ref: '#/components/schemas/OutputItemReasoning' + - $ref: '#/components/schemas/OutputItemFunctionCall' + - $ref: '#/components/schemas/OutputItemWebSearchCall' + - $ref: '#/components/schemas/OutputItemFileSearchCall' + - $ref: '#/components/schemas/OutputItemImageGenerationCall' + discriminator: + propertyName: type + mapping: + message: '#/components/schemas/OutputMessage' + reasoning: '#/components/schemas/OutputItemReasoning' + function_call: '#/components/schemas/OutputItemFunctionCall' + web_search_call: '#/components/schemas/OutputItemWebSearchCall' + file_search_call: '#/components/schemas/OutputItemFileSearchCall' + image_generation_call: '#/components/schemas/OutputItemImageGenerationCall' + user: + type: string + nullable: true + output_text: + type: string + prompt_cache_key: + type: string + nullable: true + safety_identifier: + type: string + nullable: true + error: + $ref: '#/components/schemas/ResponsesErrorField' + incomplete_details: + $ref: '#/components/schemas/OpenAIResponsesIncompleteDetails' + usage: + $ref: '#/components/schemas/OpenAIResponsesUsage' + max_tool_calls: + type: number + nullable: true + top_logprobs: + type: number + max_output_tokens: + type: number + nullable: true + temperature: + type: number + nullable: true + top_p: + type: number + nullable: true + instructions: + $ref: '#/components/schemas/OpenAIResponsesInput' + metadata: + $ref: '#/components/schemas/OpenResponsesRequestMetadata' + tools: + type: array + items: + oneOf: + - allOf: + - $ref: '#/components/schemas/OpenResponsesFunctionTool' + - type: object + properties: {} + description: Function tool definition + example: + type: function + name: get_weather + description: Get the current weather in a location + parameters: + type: object + properties: + location: + type: string + description: The city and state + unit: + type: string + enum: + - celsius + - fahrenheit + x-speakeasy-unknown-values: allow + required: + - location + - $ref: '#/components/schemas/OpenResponsesWebSearchPreviewTool' + - $ref: '#/components/schemas/OpenResponsesWebSearchPreview20250311Tool' + - $ref: '#/components/schemas/OpenResponsesWebSearchTool' + - $ref: '#/components/schemas/OpenResponsesWebSearch20250826Tool' + tool_choice: + $ref: '#/components/schemas/OpenAIResponsesToolChoice' + parallel_tool_calls: + type: boolean + prompt: + $ref: '#/components/schemas/OpenAIResponsesPrompt' + background: + type: boolean + nullable: true + previous_response_id: + type: string + nullable: true + reasoning: + $ref: '#/components/schemas/OpenAIResponsesReasoningConfig' + service_tier: + $ref: '#/components/schemas/OpenAIResponsesServiceTier' + store: + type: boolean + truncation: + $ref: '#/components/schemas/OpenAIResponsesTruncation' + text: + $ref: '#/components/schemas/ResponseTextConfig' + required: + - id + - object + - created_at + - model + - output + - error + - incomplete_details + - temperature + - top_p + - instructions + - metadata + - tools + - tool_choice + - parallel_tool_calls + OpenResponsesNonStreamingResponse: + allOf: + - $ref: '#/components/schemas/OpenAIResponsesNonStreamingResponse' + - type: object + properties: + output: + type: array + items: + $ref: '#/components/schemas/ResponsesOutputItem' + usage: + $ref: '#/components/schemas/OpenResponsesUsage' + description: Complete non-streaming response from the Responses API + example: + id: resp-abc123 + object: response + created_at: 1704067200 + model: gpt-4 + status: completed + output: + - type: message + id: msg-abc123 + status: completed + role: assistant + content: + - type: output_text + text: Hello! How can I help you today? + annotations: [] + usage: + input_tokens: 10 + output_tokens: 25 + total_tokens: 35 + input_tokens_details: + cached_tokens: 0 + output_tokens_details: + reasoning_tokens: 0 + tools: [] + tool_choice: auto + parallel_tool_calls: true + error: null + incomplete_details: null + temperature: null + top_p: null + max_output_tokens: null + metadata: null + instructions: null + OpenResponsesCreatedEvent: + type: object + properties: + type: + type: string + enum: + - response.created + response: + $ref: '#/components/schemas/OpenAIResponsesNonStreamingResponse' + sequence_number: + type: number + required: + - type + - response + - sequence_number + description: Event emitted when a response is created + example: + type: response.created + response: + id: resp-abc123 + object: response + created_at: 1704067200 + model: gpt-4 + status: in_progress + output: [] + tools: [] + tool_choice: auto + parallel_tool_calls: true + error: null + incomplete_details: null + metadata: null + instructions: null + temperature: null + top_p: null + max_output_tokens: null + sequence_number: 0 + OpenResponsesInProgressEvent: + type: object + properties: + type: + type: string + enum: + - response.in_progress + response: + $ref: '#/components/schemas/OpenAIResponsesNonStreamingResponse' + sequence_number: + type: number + required: + - type + - response + - sequence_number + description: Event emitted when a response is in progress + example: + type: response.in_progress + response: + id: resp-abc123 + object: response + created_at: 1704067200 + model: gpt-4 + status: in_progress + output: [] + tools: [] + tool_choice: auto + parallel_tool_calls: true + error: null + incomplete_details: null + metadata: null + instructions: null + temperature: null + top_p: null + max_output_tokens: null + sequence_number: 1 + OpenResponsesCompletedEvent: + type: object + properties: + type: + type: string + enum: + - response.completed + response: + $ref: '#/components/schemas/OpenAIResponsesNonStreamingResponse' + sequence_number: + type: number + required: + - type + - response + - sequence_number + description: Event emitted when a response has completed successfully + example: + type: response.completed + response: + id: resp-abc123 + object: response + created_at: 1704067200 + model: gpt-4 + status: completed + output: + - id: item-1 + type: message + status: completed + role: assistant + content: + - type: output_text + text: Hello! How can I help you? + annotations: [] + tools: [] + tool_choice: auto + parallel_tool_calls: true + error: null + incomplete_details: null + metadata: null + instructions: null + temperature: null + top_p: null + max_output_tokens: null + sequence_number: 10 + OpenResponsesIncompleteEvent: + type: object + properties: + type: + type: string + enum: + - response.incomplete + response: + $ref: '#/components/schemas/OpenAIResponsesNonStreamingResponse' + sequence_number: + type: number + required: + - type + - response + - sequence_number + description: Event emitted when a response is incomplete + example: + type: response.incomplete + response: + id: resp-abc123 + object: response + created_at: 1704067200 + model: gpt-4 + status: incomplete + output: [] + tools: [] + tool_choice: auto + parallel_tool_calls: true + error: null + incomplete_details: null + metadata: null + instructions: null + temperature: null + top_p: null + max_output_tokens: null + sequence_number: 5 + OpenResponsesFailedEvent: + type: object + properties: + type: + type: string + enum: + - response.failed + response: + $ref: '#/components/schemas/OpenAIResponsesNonStreamingResponse' + sequence_number: + type: number + required: + - type + - response + - sequence_number + description: Event emitted when a response has failed + example: + type: response.failed + response: + id: resp-abc123 + object: response + created_at: 1704067200 + model: gpt-4 + status: failed + output: [] + tools: [] + tool_choice: auto + parallel_tool_calls: true + error: null + incomplete_details: null + metadata: null + instructions: null + temperature: null + top_p: null + max_output_tokens: null + sequence_number: 3 + OpenAIResponsesErrorEvent: + type: object + properties: + type: + type: string + enum: + - error + code: + type: string + nullable: true + message: + type: string + param: + type: string + nullable: true + sequence_number: + type: number + required: + - type + - code + - message + - param + - sequence_number + description: Event emitted when an error occurs during streaming + example: + type: error + code: rate_limit_exceeded + message: Rate limit exceeded. Please try again later. + param: null + sequence_number: 2 + OpenResponsesErrorEvent: + allOf: + - $ref: '#/components/schemas/OpenAIResponsesErrorEvent' + - type: object + properties: {} + description: Event emitted when an error occurs during streaming + example: + type: error + code: rate_limit_exceeded + message: Rate limit exceeded. Please try again later. + param: null + sequence_number: 2 + OpenResponsesOutputItemAddedEvent: + type: object + properties: + type: + type: string + enum: + - response.output_item.added + output_index: + type: number + item: + oneOf: + - $ref: '#/components/schemas/OutputMessage' + - $ref: '#/components/schemas/OutputItemReasoning' + - $ref: '#/components/schemas/OutputItemFunctionCall' + - $ref: '#/components/schemas/OutputItemWebSearchCall' + - $ref: '#/components/schemas/OutputItemFileSearchCall' + - $ref: '#/components/schemas/OutputItemImageGenerationCall' + discriminator: + propertyName: type + mapping: + message: '#/components/schemas/OutputMessage' + reasoning: '#/components/schemas/OutputItemReasoning' + function_call: '#/components/schemas/OutputItemFunctionCall' + web_search_call: '#/components/schemas/OutputItemWebSearchCall' + file_search_call: '#/components/schemas/OutputItemFileSearchCall' + image_generation_call: '#/components/schemas/OutputItemImageGenerationCall' + sequence_number: + type: number + required: + - type + - output_index + - item + - sequence_number + description: Event emitted when a new output item is added to the response + example: + type: response.output_item.added + output_index: 0 + item: + id: item-1 + type: message + status: in_progress + role: assistant + content: [] + sequence_number: 2 + OpenResponsesOutputItemDoneEvent: + type: object + properties: + type: + type: string + enum: + - response.output_item.done + output_index: + type: number + item: + oneOf: + - $ref: '#/components/schemas/OutputMessage' + - $ref: '#/components/schemas/OutputItemReasoning' + - $ref: '#/components/schemas/OutputItemFunctionCall' + - $ref: '#/components/schemas/OutputItemWebSearchCall' + - $ref: '#/components/schemas/OutputItemFileSearchCall' + - $ref: '#/components/schemas/OutputItemImageGenerationCall' + discriminator: + propertyName: type + mapping: + message: '#/components/schemas/OutputMessage' + reasoning: '#/components/schemas/OutputItemReasoning' + function_call: '#/components/schemas/OutputItemFunctionCall' + web_search_call: '#/components/schemas/OutputItemWebSearchCall' + file_search_call: '#/components/schemas/OutputItemFileSearchCall' + image_generation_call: '#/components/schemas/OutputItemImageGenerationCall' + sequence_number: + type: number + required: + - type + - output_index + - item + - sequence_number + description: Event emitted when an output item is complete + example: + type: response.output_item.done + output_index: 0 + item: + id: item-1 + type: message + status: completed + role: assistant + content: + - type: output_text + text: Hello! How can I help you? + annotations: [] + sequence_number: 8 + OpenResponsesContentPartAddedEvent: + type: object + properties: + type: + type: string + enum: + - response.content_part.added + output_index: + type: number + item_id: + type: string + content_index: + type: number + part: + anyOf: + - $ref: '#/components/schemas/ResponseOutputText' + - $ref: '#/components/schemas/OpenAIResponsesRefusalContent' + sequence_number: + type: number + required: + - type + - output_index + - item_id + - content_index + - part + - sequence_number + description: Event emitted when a new content part is added to an output item + example: + type: response.content_part.added + output_index: 0 + item_id: item-1 + content_index: 0 + part: + type: output_text + text: '' + annotations: [] + sequence_number: 3 + OpenResponsesContentPartDoneEvent: + type: object + properties: + type: + type: string + enum: + - response.content_part.done + output_index: + type: number + item_id: + type: string + content_index: + type: number + part: + anyOf: + - $ref: '#/components/schemas/ResponseOutputText' + - $ref: '#/components/schemas/OpenAIResponsesRefusalContent' + sequence_number: + type: number + required: + - type + - output_index + - item_id + - content_index + - part + - sequence_number + description: Event emitted when a content part is complete + example: + type: response.content_part.done + output_index: 0 + item_id: item-1 + content_index: 0 + part: + type: output_text + text: Hello! How can I help you? + annotations: [] + sequence_number: 7 + OpenResponsesTopLogprobs: + type: object + properties: + token: + type: string + logprob: + type: number + description: Alternative token with its log probability + example: + token: hello + logprob: -0.5 + OpenResponsesLogProbs: + type: object + properties: + logprob: + type: number + token: + type: string + top_logprobs: + type: array + items: + $ref: '#/components/schemas/OpenResponsesTopLogprobs' + required: + - logprob + - token + description: Log probability information for a token + example: + logprob: -0.1 + token: world + top_logprobs: + - token: hello + logprob: -0.5 + OpenResponsesTextDeltaEvent: + type: object + properties: + type: + type: string + enum: + - response.output_text.delta + logprobs: + type: array + items: + $ref: '#/components/schemas/OpenResponsesLogProbs' + output_index: + type: number + item_id: + type: string + content_index: + type: number + delta: + type: string + sequence_number: + type: number + required: + - type + - logprobs + - output_index + - item_id + - content_index + - delta + - sequence_number + description: Event emitted when a text delta is streamed + example: + type: response.output_text.delta + logprobs: [] + output_index: 0 + item_id: item-1 + content_index: 0 + delta: Hello + sequence_number: 4 + OpenResponsesTextDoneEvent: + type: object + properties: + type: + type: string + enum: + - response.output_text.done + output_index: + type: number + item_id: + type: string + content_index: + type: number + text: + type: string + sequence_number: + type: number + logprobs: + type: array + items: + $ref: '#/components/schemas/OpenResponsesLogProbs' + required: + - type + - output_index + - item_id + - content_index + - text + - sequence_number + - logprobs + description: Event emitted when text streaming is complete + example: + type: response.output_text.done + output_index: 0 + item_id: item-1 + content_index: 0 + text: Hello! How can I help you? + sequence_number: 6 + logprobs: [] + OpenResponsesRefusalDeltaEvent: + type: object + properties: + type: + type: string + enum: + - response.refusal.delta + output_index: + type: number + item_id: + type: string + content_index: + type: number + delta: + type: string + sequence_number: + type: number + required: + - type + - output_index + - item_id + - content_index + - delta + - sequence_number + description: Event emitted when a refusal delta is streamed + example: + type: response.refusal.delta + output_index: 0 + item_id: item-1 + content_index: 0 + delta: I'm sorry + sequence_number: 4 + OpenResponsesRefusalDoneEvent: + type: object + properties: + type: + type: string + enum: + - response.refusal.done + output_index: + type: number + item_id: + type: string + content_index: + type: number + refusal: + type: string + sequence_number: + type: number + required: + - type + - output_index + - item_id + - content_index + - refusal + - sequence_number + description: Event emitted when refusal streaming is complete + example: + type: response.refusal.done + output_index: 0 + item_id: item-1 + content_index: 0 + refusal: I'm sorry, but I can't assist with that request. + sequence_number: 6 + OpenResponsesOutputTextAnnotationAddedEvent: + type: object + properties: + type: + type: string + enum: + - response.output_text.annotation.added + output_index: + type: number + item_id: + type: string + content_index: + type: number + sequence_number: + type: number + annotation_index: + type: number + annotation: + $ref: '#/components/schemas/OpenAIResponsesAnnotation' + required: + - type + - output_index + - item_id + - content_index + - sequence_number + - annotation_index + - annotation + description: Event emitted when a text annotation is added to output + example: + type: response.output_text.annotation.added + output_index: 0 + item_id: item-1 + content_index: 0 + sequence_number: 5 + annotation_index: 0 + annotation: + type: url_citation + url: https://example.com + title: Example + start_index: 0 + end_index: 7 + OpenResponsesFunctionCallArgumentsDeltaEvent: + type: object + properties: + type: + type: string + enum: + - response.function_call_arguments.delta + item_id: + type: string + output_index: + type: number + delta: + type: string + sequence_number: + type: number + required: + - type + - item_id + - output_index + - delta + - sequence_number + description: Event emitted when function call arguments are being streamed + example: + type: response.function_call_arguments.delta + item_id: item-1 + output_index: 0 + delta: '{"city": "San' + sequence_number: 4 + OpenResponsesFunctionCallArgumentsDoneEvent: + type: object + properties: + type: + type: string + enum: + - response.function_call_arguments.done + item_id: + type: string + output_index: + type: number + name: + type: string + arguments: + type: string + sequence_number: + type: number + required: + - type + - item_id + - output_index + - name + - arguments + - sequence_number + description: Event emitted when function call arguments streaming is complete + example: + type: response.function_call_arguments.done + item_id: item-1 + output_index: 0 + name: get_weather + arguments: '{"city": "San Francisco", "units": "celsius"}' + sequence_number: 6 + OpenAIResponsesReasoningDeltaEvent: + type: object + properties: + type: + type: string + enum: + - response.reasoning_text.delta + output_index: + type: number + item_id: + type: string + content_index: + type: number + delta: + type: string + sequence_number: + type: number + required: + - type + - output_index + - item_id + - content_index + - delta + - sequence_number + description: Event emitted when reasoning text delta is streamed + example: + type: response.reasoning_text.delta + output_index: 0 + item_id: item-1 + content_index: 0 + delta: First, we need + sequence_number: 4 + OpenResponsesReasoningDeltaEvent: + allOf: + - $ref: '#/components/schemas/OpenAIResponsesReasoningDeltaEvent' + - type: object + properties: {} + description: Event emitted when reasoning text delta is streamed + example: + type: response.reasoning_text.delta + output_index: 0 + item_id: item-1 + content_index: 0 + delta: First, we need + sequence_number: 4 + OpenAIResponsesReasoningDoneEvent: + type: object + properties: + type: + type: string + enum: + - response.reasoning_text.done + output_index: + type: number + item_id: + type: string + content_index: + type: number + text: + type: string + sequence_number: + type: number + required: + - type + - output_index + - item_id + - content_index + - text + - sequence_number + description: Event emitted when reasoning text streaming is complete + example: + type: response.reasoning_text.done + output_index: 0 + item_id: item-1 + content_index: 0 + text: First, we need to identify the key components and then combine them logically. + sequence_number: 6 + OpenResponsesReasoningDoneEvent: + allOf: + - $ref: '#/components/schemas/OpenAIResponsesReasoningDoneEvent' + - type: object + properties: {} + description: Event emitted when reasoning text streaming is complete + example: + type: response.reasoning_text.done + output_index: 0 + item_id: item-1 + content_index: 0 + text: First, we need to identify the key components and then combine them logically. + sequence_number: 6 + OpenAIResponsesReasoningSummaryPartAddedEvent: + type: object + properties: + type: + type: string + enum: + - response.reasoning_summary_part.added + output_index: + type: number + item_id: + type: string + summary_index: + type: number + part: + $ref: '#/components/schemas/ReasoningSummaryText' + sequence_number: + type: number + required: + - type + - output_index + - item_id + - summary_index + - part + - sequence_number + description: Event emitted when a reasoning summary part is added + example: + type: response.reasoning_summary_part.added + output_index: 0 + item_id: item-1 + summary_index: 0 + part: + type: summary_text + text: '' + sequence_number: 3 + OpenResponsesReasoningSummaryPartAddedEvent: + allOf: + - $ref: '#/components/schemas/OpenAIResponsesReasoningSummaryPartAddedEvent' + - type: object + properties: {} + description: Event emitted when a reasoning summary part is added + example: + type: response.reasoning_summary_part.added + output_index: 0 + item_id: item-1 + summary_index: 0 + part: + type: summary_text + text: '' + sequence_number: 3 + OpenResponsesReasoningSummaryPartDoneEvent: + type: object + properties: + type: + type: string + enum: + - response.reasoning_summary_part.done + output_index: + type: number + item_id: + type: string + summary_index: + type: number + part: + $ref: '#/components/schemas/ReasoningSummaryText' + sequence_number: + type: number + required: + - type + - output_index + - item_id + - summary_index + - part + - sequence_number + description: Event emitted when a reasoning summary part is complete + example: + type: response.reasoning_summary_part.done + output_index: 0 + item_id: item-1 + summary_index: 0 + part: + type: summary_text + text: Analyzing the problem step by step to find the optimal solution. + sequence_number: 7 + OpenAIResponsesReasoningSummaryTextDeltaEvent: + type: object + properties: + type: + type: string + enum: + - response.reasoning_summary_text.delta + item_id: + type: string + output_index: + type: number + summary_index: + type: number + delta: + type: string + sequence_number: + type: number + required: + - type + - item_id + - output_index + - summary_index + - delta + - sequence_number + description: Event emitted when reasoning summary text delta is streamed + example: + type: response.reasoning_summary_text.delta + item_id: item-1 + output_index: 0 + summary_index: 0 + delta: Analyzing + sequence_number: 4 + OpenResponsesReasoningSummaryTextDeltaEvent: + allOf: + - $ref: '#/components/schemas/OpenAIResponsesReasoningSummaryTextDeltaEvent' + - type: object + properties: {} + description: Event emitted when reasoning summary text delta is streamed + example: + type: response.reasoning_summary_text.delta + item_id: item-1 + output_index: 0 + summary_index: 0 + delta: Analyzing + sequence_number: 4 + OpenAIResponsesReasoningSummaryTextDoneEvent: + type: object + properties: + type: + type: string + enum: + - response.reasoning_summary_text.done + item_id: + type: string + output_index: + type: number + summary_index: + type: number + text: + type: string + sequence_number: + type: number + required: + - type + - item_id + - output_index + - summary_index + - text + - sequence_number + description: Event emitted when reasoning summary text streaming is complete + example: + type: response.reasoning_summary_text.done + item_id: item-1 + output_index: 0 + summary_index: 0 + text: Analyzing the problem step by step to find the optimal solution. + sequence_number: 6 + OpenResponsesReasoningSummaryTextDoneEvent: + allOf: + - $ref: '#/components/schemas/OpenAIResponsesReasoningSummaryTextDoneEvent' + - type: object + properties: {} + description: Event emitted when reasoning summary text streaming is complete + example: + type: response.reasoning_summary_text.done + item_id: item-1 + output_index: 0 + summary_index: 0 + text: Analyzing the problem step by step to find the optimal solution. + sequence_number: 6 + OpenAIResponsesImageGenCallInProgress: + type: object + properties: + type: + type: string + enum: + - response.image_generation_call.in_progress + item_id: + type: string + output_index: + type: number + sequence_number: + type: number + required: + - type + - item_id + - output_index + - sequence_number + OpenResponsesImageGenCallInProgress: + allOf: + - $ref: '#/components/schemas/OpenAIResponsesImageGenCallInProgress' + - type: object + properties: {} + description: Image generation call in progress + example: + type: response.image_generation_call.in_progress + output_index: 0 + sequence_number: 1 + item_id: call-123 + OpenAIResponsesImageGenCallGenerating: + type: object + properties: + type: + type: string + enum: + - response.image_generation_call.generating + item_id: + type: string + output_index: + type: number + sequence_number: + type: number + required: + - type + - item_id + - output_index + - sequence_number + OpenResponsesImageGenCallGenerating: + allOf: + - $ref: '#/components/schemas/OpenAIResponsesImageGenCallGenerating' + - type: object + properties: {} + description: Image generation call is generating + example: + type: response.image_generation_call.generating + output_index: 0 + sequence_number: 2 + item_id: call-123 + OpenAIResponsesImageGenCallPartialImage: + type: object + properties: + type: + type: string + enum: + - response.image_generation_call.partial_image + item_id: + type: string + output_index: + type: number + sequence_number: + type: number + partial_image_b64: + type: string + partial_image_index: + type: number + required: + - type + - item_id + - output_index + - sequence_number + - partial_image_b64 + - partial_image_index + OpenResponsesImageGenCallPartialImage: + allOf: + - $ref: '#/components/schemas/OpenAIResponsesImageGenCallPartialImage' + - type: object + properties: {} + description: Image generation call with partial image + example: + type: response.image_generation_call.partial_image + output_index: 0 + sequence_number: 3 + item_id: call-123 + partial_image_b64: base64encodedimage... + partial_image_index: 0 + OpenAIResponsesImageGenCallCompleted: + type: object + properties: + type: + type: string + enum: + - response.image_generation_call.completed + item_id: + type: string + output_index: + type: number + sequence_number: + type: number + required: + - type + - item_id + - output_index + - sequence_number + OpenResponsesImageGenCallCompleted: + allOf: + - $ref: '#/components/schemas/OpenAIResponsesImageGenCallCompleted' + - type: object + properties: {} + description: Image generation call completed + example: + type: response.image_generation_call.completed + output_index: 0 + sequence_number: 4 + item_id: call-123 + OpenResponsesStreamEvent: + oneOf: + - allOf: + - $ref: '#/components/schemas/OpenResponsesCreatedEvent' + - type: object + properties: + response: + $ref: '#/components/schemas/OpenResponsesNonStreamingResponse' + description: Event emitted when a response is created + example: + type: response.created + response: + id: resp-abc123 + object: response + created_at: 1704067200 + model: gpt-4 + status: in_progress + output: [] + tools: [] + tool_choice: auto + parallel_tool_calls: true + error: null + incomplete_details: null + metadata: null + instructions: null + temperature: null + top_p: null + max_output_tokens: null + sequence_number: 0 + - allOf: + - $ref: '#/components/schemas/OpenResponsesInProgressEvent' + - type: object + properties: + response: + $ref: '#/components/schemas/OpenResponsesNonStreamingResponse' + description: Event emitted when a response is in progress + example: + type: response.in_progress + response: + id: resp-abc123 + object: response + created_at: 1704067200 + model: gpt-4 + status: in_progress + output: [] + tools: [] + tool_choice: auto + parallel_tool_calls: true + error: null + incomplete_details: null + metadata: null + instructions: null + temperature: null + top_p: null + max_output_tokens: null + sequence_number: 1 + - allOf: + - $ref: '#/components/schemas/OpenResponsesCompletedEvent' + - type: object + properties: + response: + $ref: '#/components/schemas/OpenResponsesNonStreamingResponse' + description: Event emitted when a response has completed successfully + example: + type: response.completed + response: + id: resp-abc123 + object: response + created_at: 1704067200 + model: gpt-4 + status: completed + output: + - id: item-1 + type: message + status: completed + role: assistant + content: + - type: output_text + text: Hello! How can I help you? + annotations: [] + tools: [] + tool_choice: auto + parallel_tool_calls: true + error: null + incomplete_details: null + metadata: null + instructions: null + temperature: null + top_p: null + max_output_tokens: null + sequence_number: 10 + - allOf: + - $ref: '#/components/schemas/OpenResponsesIncompleteEvent' + - type: object + properties: + response: + $ref: '#/components/schemas/OpenResponsesNonStreamingResponse' + description: Event emitted when a response is incomplete + example: + type: response.incomplete + response: + id: resp-abc123 + object: response + created_at: 1704067200 + model: gpt-4 + status: incomplete + output: [] + tools: [] + tool_choice: auto + parallel_tool_calls: true + error: null + incomplete_details: null + metadata: null + instructions: null + temperature: null + top_p: null + max_output_tokens: null + sequence_number: 5 + - allOf: + - $ref: '#/components/schemas/OpenResponsesFailedEvent' + - type: object + properties: + response: + $ref: '#/components/schemas/OpenResponsesNonStreamingResponse' + description: Event emitted when a response has failed + example: + type: response.failed + response: + id: resp-abc123 + object: response + created_at: 1704067200 + model: gpt-4 + status: failed + output: [] + tools: [] + tool_choice: auto + parallel_tool_calls: true + error: null + incomplete_details: null + metadata: null + instructions: null + temperature: null + top_p: null + max_output_tokens: null + sequence_number: 3 + - $ref: '#/components/schemas/OpenResponsesErrorEvent' + - allOf: + - $ref: '#/components/schemas/OpenResponsesOutputItemAddedEvent' + - type: object + properties: + item: + $ref: '#/components/schemas/ResponsesOutputItem' + description: Event emitted when a new output item is added to the response + example: + type: response.output_item.added + output_index: 0 + item: + id: item-1 + type: message + status: in_progress + role: assistant + content: [] + sequence_number: 2 + - allOf: + - $ref: '#/components/schemas/OpenResponsesOutputItemDoneEvent' + - type: object + properties: + item: + $ref: '#/components/schemas/ResponsesOutputItem' + description: Event emitted when an output item is complete + example: + type: response.output_item.done + output_index: 0 + item: + id: item-1 + type: message + status: completed + role: assistant + content: + - type: output_text + text: Hello! How can I help you? + annotations: [] + sequence_number: 8 + - allOf: + - $ref: '#/components/schemas/OpenResponsesContentPartAddedEvent' + - type: object + properties: + part: + anyOf: + - $ref: '#/components/schemas/ResponseOutputText' + - $ref: '#/components/schemas/ReasoningTextContent' + - $ref: '#/components/schemas/OpenAIResponsesRefusalContent' + description: Event emitted when a new content part is added to an output item + example: + type: response.content_part.added + output_index: 0 + item_id: item-1 + content_index: 0 + part: + type: output_text + text: '' + annotations: [] + sequence_number: 3 + - allOf: + - $ref: '#/components/schemas/OpenResponsesContentPartDoneEvent' + - type: object + properties: + part: + anyOf: + - $ref: '#/components/schemas/ResponseOutputText' + - $ref: '#/components/schemas/ReasoningTextContent' + - $ref: '#/components/schemas/OpenAIResponsesRefusalContent' + description: Event emitted when a content part is complete + example: + type: response.content_part.done + output_index: 0 + item_id: item-1 + content_index: 0 + part: + type: output_text + text: Hello! How can I help you? + annotations: [] + sequence_number: 7 + - allOf: + - $ref: '#/components/schemas/OpenResponsesTextDeltaEvent' + - type: object + properties: {} + description: Event emitted when a text delta is streamed + example: + type: response.output_text.delta + logprobs: [] + output_index: 0 + item_id: item-1 + content_index: 0 + delta: Hello + sequence_number: 4 + - allOf: + - $ref: '#/components/schemas/OpenResponsesTextDoneEvent' + - type: object + properties: {} + description: Event emitted when text streaming is complete + example: + type: response.output_text.done + output_index: 0 + item_id: item-1 + content_index: 0 + text: Hello! How can I help you? + sequence_number: 6 + logprobs: [] + - allOf: + - $ref: '#/components/schemas/OpenResponsesRefusalDeltaEvent' + - type: object + properties: {} + description: Event emitted when a refusal delta is streamed + example: + type: response.refusal.delta + output_index: 0 + item_id: item-1 + content_index: 0 + delta: I'm sorry + sequence_number: 4 + - allOf: + - $ref: '#/components/schemas/OpenResponsesRefusalDoneEvent' + - type: object + properties: {} + description: Event emitted when refusal streaming is complete + example: + type: response.refusal.done + output_index: 0 + item_id: item-1 + content_index: 0 + refusal: I'm sorry, but I can't assist with that request. + sequence_number: 6 + - allOf: + - $ref: '#/components/schemas/OpenResponsesOutputTextAnnotationAddedEvent' + - type: object + properties: {} + description: Event emitted when a text annotation is added to output + example: + type: response.output_text.annotation.added + output_index: 0 + item_id: item-1 + content_index: 0 + sequence_number: 5 + annotation_index: 0 + annotation: + type: url_citation + url: https://example.com + title: Example + start_index: 0 + end_index: 7 + - allOf: + - $ref: '#/components/schemas/OpenResponsesFunctionCallArgumentsDeltaEvent' + - type: object + properties: {} + description: Event emitted when function call arguments are being streamed + example: + type: response.function_call_arguments.delta + item_id: item-1 + output_index: 0 + delta: '{"city": "San' + sequence_number: 4 + - allOf: + - $ref: '#/components/schemas/OpenResponsesFunctionCallArgumentsDoneEvent' + - type: object + properties: {} + description: Event emitted when function call arguments streaming is complete + example: + type: response.function_call_arguments.done + item_id: item-1 + output_index: 0 + name: get_weather + arguments: '{"city": "San Francisco", "units": "celsius"}' + sequence_number: 6 + - $ref: '#/components/schemas/OpenResponsesReasoningDeltaEvent' + - $ref: '#/components/schemas/OpenResponsesReasoningDoneEvent' + - $ref: '#/components/schemas/OpenResponsesReasoningSummaryPartAddedEvent' + - allOf: + - $ref: '#/components/schemas/OpenResponsesReasoningSummaryPartDoneEvent' + - type: object + properties: {} + description: Event emitted when a reasoning summary part is complete + example: + type: response.reasoning_summary_part.done + output_index: 0 + item_id: item-1 + summary_index: 0 + part: + type: summary_text + text: Analyzing the problem step by step to find the optimal solution. + sequence_number: 7 + - $ref: '#/components/schemas/OpenResponsesReasoningSummaryTextDeltaEvent' + - $ref: '#/components/schemas/OpenResponsesReasoningSummaryTextDoneEvent' + - $ref: '#/components/schemas/OpenResponsesImageGenCallInProgress' + - $ref: '#/components/schemas/OpenResponsesImageGenCallGenerating' + - $ref: '#/components/schemas/OpenResponsesImageGenCallPartialImage' + - $ref: '#/components/schemas/OpenResponsesImageGenCallCompleted' + description: Union of all possible event types emitted during response streaming + example: + type: response.created + response: + id: resp-abc123 + object: response + created_at: 1704067200 + model: gpt-4 + status: in_progress + output: [] + tools: [] + tool_choice: auto + parallel_tool_calls: true + error: null + incomplete_details: null + metadata: null + instructions: null + temperature: null + top_p: null + max_output_tokens: null + sequence_number: 0 + BadRequestResponseErrorData: + type: object + properties: + code: + type: integer + message: + type: string + metadata: + type: object + nullable: true + additionalProperties: + nullable: true + required: + - code + - message + description: Error data for BadRequestResponse + example: + code: 400 + message: Invalid request parameters + BadRequestResponse: + type: object + properties: + error: + $ref: '#/components/schemas/BadRequestResponseErrorData' + user_id: + type: string + nullable: true + required: + - error + description: Bad Request - Invalid request parameters or malformed input + example: + error: + code: 400 + message: Invalid request parameters + UnauthorizedResponseErrorData: + type: object + properties: + code: + type: integer + message: + type: string + metadata: + type: object + nullable: true + additionalProperties: + nullable: true + required: + - code + - message + description: Error data for UnauthorizedResponse + example: + code: 401 + message: Missing Authentication header + UnauthorizedResponse: + type: object + properties: + error: + $ref: '#/components/schemas/UnauthorizedResponseErrorData' + user_id: + type: string + nullable: true + required: + - error + description: Unauthorized - Authentication required or invalid credentials + example: + error: + code: 401 + message: Missing Authentication header + PaymentRequiredResponseErrorData: + type: object + properties: + code: + type: integer + message: + type: string + metadata: + type: object + nullable: true + additionalProperties: + nullable: true + required: + - code + - message + description: Error data for PaymentRequiredResponse + example: + code: 402 + message: Insufficient credits. Add more using https://openrouter.ai/credits + PaymentRequiredResponse: + type: object + properties: + error: + $ref: '#/components/schemas/PaymentRequiredResponseErrorData' + user_id: + type: string + nullable: true + required: + - error + description: Payment Required - Insufficient credits or quota to complete request + example: + error: + code: 402 + message: Insufficient credits. Add more using https://openrouter.ai/credits + NotFoundResponseErrorData: + type: object + properties: + code: + type: integer + message: + type: string + metadata: + type: object + nullable: true + additionalProperties: + nullable: true + required: + - code + - message + description: Error data for NotFoundResponse + example: + code: 404 + message: Resource not found + NotFoundResponse: + type: object + properties: + error: + $ref: '#/components/schemas/NotFoundResponseErrorData' + user_id: + type: string + nullable: true + required: + - error + description: Not Found - Resource does not exist + example: + error: + code: 404 + message: Resource not found + RequestTimeoutResponseErrorData: + type: object + properties: + code: + type: integer + message: + type: string + metadata: + type: object + nullable: true + additionalProperties: + nullable: true + required: + - code + - message + description: Error data for RequestTimeoutResponse + example: + code: 408 + message: Operation timed out. Please try again later. + RequestTimeoutResponse: + type: object + properties: + error: + $ref: '#/components/schemas/RequestTimeoutResponseErrorData' + user_id: + type: string + nullable: true + required: + - error + description: Request Timeout - Operation exceeded time limit + example: + error: + code: 408 + message: Operation timed out. Please try again later. + PayloadTooLargeResponseErrorData: + type: object + properties: + code: + type: integer + message: + type: string + metadata: + type: object + nullable: true + additionalProperties: + nullable: true + required: + - code + - message + description: Error data for PayloadTooLargeResponse + example: + code: 413 + message: Request payload too large + PayloadTooLargeResponse: + type: object + properties: + error: + $ref: '#/components/schemas/PayloadTooLargeResponseErrorData' + user_id: + type: string + nullable: true + required: + - error + description: Payload Too Large - Request payload exceeds size limits + example: + error: + code: 413 + message: Request payload too large + UnprocessableEntityResponseErrorData: + type: object + properties: + code: + type: integer + message: + type: string + metadata: + type: object + nullable: true + additionalProperties: + nullable: true + required: + - code + - message + description: Error data for UnprocessableEntityResponse + example: + code: 422 + message: Invalid argument + UnprocessableEntityResponse: + type: object + properties: + error: + $ref: '#/components/schemas/UnprocessableEntityResponseErrorData' + user_id: + type: string + nullable: true + required: + - error + description: Unprocessable Entity - Semantic validation failure + example: + error: + code: 422 + message: Invalid argument + TooManyRequestsResponseErrorData: + type: object + properties: + code: + type: integer + message: + type: string + metadata: + type: object + nullable: true + additionalProperties: + nullable: true + required: + - code + - message + description: Error data for TooManyRequestsResponse + example: + code: 429 + message: Rate limit exceeded + TooManyRequestsResponse: + type: object + properties: + error: + $ref: '#/components/schemas/TooManyRequestsResponseErrorData' + user_id: + type: string + nullable: true + required: + - error + description: Too Many Requests - Rate limit exceeded + example: + error: + code: 429 + message: Rate limit exceeded + InternalServerResponseErrorData: + type: object + properties: + code: + type: integer + message: + type: string + metadata: + type: object + nullable: true + additionalProperties: + nullable: true + required: + - code + - message + description: Error data for InternalServerResponse + example: + code: 500 + message: Internal Server Error + InternalServerResponse: + type: object + properties: + error: + $ref: '#/components/schemas/InternalServerResponseErrorData' + user_id: + type: string + nullable: true + required: + - error + description: Internal Server Error - Unexpected server error + example: + error: + code: 500 + message: Internal Server Error + BadGatewayResponseErrorData: + type: object + properties: + code: + type: integer + message: + type: string + metadata: + type: object + nullable: true + additionalProperties: + nullable: true + required: + - code + - message + description: Error data for BadGatewayResponse + example: + code: 502 + message: Provider returned error + BadGatewayResponse: + type: object + properties: + error: + $ref: '#/components/schemas/BadGatewayResponseErrorData' + user_id: + type: string + nullable: true + required: + - error + description: Bad Gateway - Provider/upstream API failure + example: + error: + code: 502 + message: Provider returned error + ServiceUnavailableResponseErrorData: + type: object + properties: + code: + type: integer + message: + type: string + metadata: + type: object + nullable: true + additionalProperties: + nullable: true + required: + - code + - message + description: Error data for ServiceUnavailableResponse + example: + code: 503 + message: Service temporarily unavailable + ServiceUnavailableResponse: + type: object + properties: + error: + $ref: '#/components/schemas/ServiceUnavailableResponseErrorData' + user_id: + type: string + nullable: true + required: + - error + description: Service Unavailable - Service temporarily unavailable + example: + error: + code: 503 + message: Service temporarily unavailable + EdgeNetworkTimeoutResponseErrorData: + type: object + properties: + code: + type: integer + message: + type: string + metadata: + type: object + nullable: true + additionalProperties: + nullable: true + required: + - code + - message + description: Error data for EdgeNetworkTimeoutResponse + example: + code: 524 + message: Request timed out. Please try again later. + EdgeNetworkTimeoutResponse: + type: object + properties: + error: + $ref: '#/components/schemas/EdgeNetworkTimeoutResponseErrorData' + user_id: + type: string + nullable: true + required: + - error + description: Infrastructure Timeout - Provider request timed out at edge network + example: + error: + code: 524 + message: Request timed out. Please try again later. + ProviderOverloadedResponseErrorData: + type: object + properties: + code: + type: integer + message: + type: string + metadata: + type: object + nullable: true + additionalProperties: + nullable: true + required: + - code + - message + description: Error data for ProviderOverloadedResponse + example: + code: 529 + message: Provider returned error + ProviderOverloadedResponse: + type: object + properties: + error: + $ref: '#/components/schemas/ProviderOverloadedResponseErrorData' + user_id: + type: string + nullable: true + required: + - error + description: Provider Overloaded - Provider is temporarily overloaded + example: + error: + code: 529 + message: Provider returned error + OpenResponsesReasoning: + allOf: + - $ref: '#/components/schemas/OutputItemReasoning' + - type: object + properties: + signature: + type: string + nullable: true + format: + type: string + nullable: true + enum: + - unknown + - openai-responses-v1 + - xai-responses-v1 + - anthropic-claude-v1 + x-speakeasy-unknown-values: allow + example: + type: reasoning + id: reasoning-abc123 + summary: + - type: summary_text + text: Step by step analysis + description: Reasoning output item with signature and format extensions + OpenResponsesEasyInputMessage: + type: object + properties: + type: + type: string + enum: + - message + role: + anyOf: + - type: string + enum: + - user + - type: string + enum: + - system + - type: string + enum: + - assistant + - type: string + enum: + - developer + content: + anyOf: + - type: array + items: + oneOf: + - $ref: '#/components/schemas/ResponseInputText' + - $ref: '#/components/schemas/ResponseInputImage' + - $ref: '#/components/schemas/ResponseInputFile' + - $ref: '#/components/schemas/ResponseInputAudio' + discriminator: + propertyName: type + mapping: + input_text: '#/components/schemas/ResponseInputText' + input_image: '#/components/schemas/ResponseInputImage' + input_file: '#/components/schemas/ResponseInputFile' + input_audio: '#/components/schemas/ResponseInputAudio' + - type: string + required: + - role + - content + OpenResponsesInputMessageItem: + type: object + properties: + id: + type: string + type: + type: string + enum: + - message + role: + anyOf: + - type: string + enum: + - user + - type: string + enum: + - system + - type: string + enum: + - developer + content: + type: array + items: + oneOf: + - $ref: '#/components/schemas/ResponseInputText' + - $ref: '#/components/schemas/ResponseInputImage' + - $ref: '#/components/schemas/ResponseInputFile' + - $ref: '#/components/schemas/ResponseInputAudio' + discriminator: + propertyName: type + mapping: + input_text: '#/components/schemas/ResponseInputText' + input_image: '#/components/schemas/ResponseInputImage' + input_file: '#/components/schemas/ResponseInputFile' + input_audio: '#/components/schemas/ResponseInputAudio' + required: + - role + - content + OpenResponsesFunctionToolCall: + type: object + properties: + type: + type: string + enum: + - function_call + call_id: + type: string + name: + type: string + arguments: + type: string + id: + type: string + status: + $ref: '#/components/schemas/ToolCallStatus' + required: + - type + - call_id + - name + - arguments + - id + description: A function call initiated by the model + example: + id: call-abc123 + type: function_call + call_id: call-abc123 + name: get_weather + arguments: '{"location":"San Francisco"}' + status: completed + OpenResponsesFunctionCallOutput: + type: object + properties: + type: + type: string + enum: + - function_call_output + id: + type: string + nullable: true + call_id: + type: string + output: + type: string + status: + $ref: '#/components/schemas/ToolCallStatus' + required: + - type + - call_id + - output + description: The output from a function call execution + example: + type: function_call_output + id: output-abc123 + call_id: call-abc123 + output: '{"temperature":72,"conditions":"sunny"}' + status: completed + OpenResponsesInput: + anyOf: + - type: string + - type: array + items: + anyOf: + - $ref: '#/components/schemas/OpenResponsesReasoning' + - $ref: '#/components/schemas/OpenResponsesEasyInputMessage' + - $ref: '#/components/schemas/OpenResponsesInputMessageItem' + - $ref: '#/components/schemas/OpenResponsesFunctionToolCall' + - $ref: '#/components/schemas/OpenResponsesFunctionCallOutput' + - $ref: '#/components/schemas/ResponsesOutputMessage' + - $ref: '#/components/schemas/ResponsesOutputItemReasoning' + - $ref: '#/components/schemas/ResponsesOutputItemFunctionCall' + - $ref: '#/components/schemas/ResponsesWebSearchCallOutput' + - $ref: '#/components/schemas/ResponsesOutputItemFileSearchCall' + - $ref: '#/components/schemas/ResponsesImageGenerationCall' + description: Input for a response request - can be a string or array of items + example: + - role: user + content: What is the weather today? + OpenResponsesResponseText: + allOf: + - $ref: '#/components/schemas/ResponseTextConfig' + - type: object + properties: {} + description: Text output configuration including format and verbosity + example: + format: + type: text + verbosity: medium + OpenResponsesReasoningConfig: + allOf: + - $ref: '#/components/schemas/OpenAIResponsesReasoningConfig' + - type: object + nullable: true + properties: + max_tokens: + type: number + nullable: true + enabled: + type: boolean + nullable: true + description: Configuration for reasoning mode in the response + example: + summary: auto + enabled: true + OpenAIResponsesIncludable: + type: string + enum: + - file_search_call.results + - message.input_image.image_url + - computer_call_output.output.image_url + - reasoning.encrypted_content + - code_interpreter_call.outputs + x-speakeasy-unknown-values: allow + ProviderName: + type: string + enum: + - AnyScale + - Cent-ML + - HuggingFace + - Hyperbolic 2 + - Lepton + - Lynn 2 + - Lynn + - Mancer + - Modal + - OctoAI + - Recursal + - Reflection + - Replicate + - SambaNova 2 + - SF Compute + - Together 2 + - 01.AI + - AI21 + - AionLabs + - Alibaba + - Amazon Bedrock + - Anthropic + - AtlasCloud + - Atoma + - Avian + - Azure + - BaseTen + - Cerebras + - Chutes + - Cirrascale + - Clarifai + - Cloudflare + - Cohere + - CrofAI + - Crusoe + - DeepInfra + - DeepSeek + - Enfer + - Featherless + - Fireworks + - Friendli + - GMICloud + - Google + - Google AI Studio + - Groq + - Hyperbolic + - Inception + - InferenceNet + - Infermatic + - Inflection + - InoCloud + - Kluster + - Lambda + - Liquid + - Mancer 2 + - Meta + - Minimax + - ModelRun + - Mistral + - Modular + - Moonshot AI + - Morph + - NCompass + - Nebius + - NextBit + - Nineteen + - Novita + - Nvidia + - OpenAI + - OpenInference + - Parasail + - Perplexity + - Phala + - Relace + - SambaNova + - SiliconFlow + - Stealth + - Switchpoint + - Targon + - Together + - Ubicloud + - Venice + - WandB + - xAI + - Z.AI + - FakeProvider + example: OpenAI + x-speakeasy-unknown-values: allow + Quantization: + type: string + enum: + - int4 + - int8 + - fp4 + - fp6 + - fp8 + - fp16 + - bf16 + - fp32 + - unknown + example: fp16 + x-speakeasy-unknown-values: allow + BigNumberUnion: + anyOf: + - type: number + - type: string + - type: number + example: 1000 + description: A value in string or number format that is a large number + example: 1000 + OpenResponsesRequest: + type: object + properties: + input: + $ref: '#/components/schemas/OpenResponsesInput' + instructions: + type: string + nullable: true + metadata: + $ref: '#/components/schemas/OpenResponsesRequestMetadata' + tools: + type: array + items: + oneOf: + - allOf: + - $ref: '#/components/schemas/OpenResponsesFunctionTool' + - type: object + properties: {} + description: Function tool definition + example: + type: function + name: get_weather + description: Get the current weather in a location + parameters: + type: object + properties: + location: + type: string + description: The city and state + unit: + type: string + enum: + - celsius + - fahrenheit + x-speakeasy-unknown-values: allow + required: + - location + - $ref: '#/components/schemas/OpenResponsesWebSearchPreviewTool' + - $ref: '#/components/schemas/OpenResponsesWebSearchPreview20250311Tool' + - $ref: '#/components/schemas/OpenResponsesWebSearchTool' + - $ref: '#/components/schemas/OpenResponsesWebSearch20250826Tool' + tool_choice: + $ref: '#/components/schemas/OpenAIResponsesToolChoice' + parallel_tool_calls: + type: boolean + nullable: true + model: + type: string + models: + type: array + items: + type: string + text: + $ref: '#/components/schemas/OpenResponsesResponseText' + reasoning: + $ref: '#/components/schemas/OpenResponsesReasoningConfig' + max_output_tokens: + type: number + nullable: true + temperature: + type: number + nullable: true + minimum: 0 + maximum: 2 + top_p: + type: number + nullable: true + minimum: 0 + top_k: + type: number + prompt_cache_key: + type: string + nullable: true + previous_response_id: + type: string + nullable: true + prompt: + $ref: '#/components/schemas/OpenAIResponsesPrompt' + include: + type: array + nullable: true + items: + $ref: '#/components/schemas/OpenAIResponsesIncludable' + background: + type: boolean + nullable: true + safety_identifier: + type: string + nullable: true + store: + type: boolean + nullable: true + service_tier: + allOf: + - $ref: '#/components/schemas/OpenAIResponsesServiceTier' + - enum: + - auto + - default + - flex + - scale + - priority + example: auto + x-speakeasy-unknown-values: allow + truncation: + allOf: + - $ref: '#/components/schemas/OpenAIResponsesTruncation' + - example: auto + stream: + type: boolean + default: false + provider: + type: object + nullable: true + properties: + allow_fallbacks: + type: boolean + nullable: true + description: > + Whether to allow backup providers to serve requests + + - true: (default) when the primary provider (or your custom providers in "order") is unavailable, use the next best provider. + + - false: use only the primary/custom provider, and return the upstream error if it's unavailable. + + require_parameters: + type: boolean + nullable: true + description: >- + Whether to filter providers to only those that support the parameters you've provided. If this setting is omitted or set to false, then providers will receive only the parameters they support, and ignore the rest. + data_collection: + type: string + nullable: true + enum: + - deny + - allow + example: deny + description: > + Data collection setting. If no available model provider meets the requirement, your request will return an error. + + - allow: (default) allow providers which store user data non-transiently and may train on it + + - deny: use only providers which do not collect user data. + + x-speakeasy-unknown-values: allow + zdr: + type: boolean + nullable: true + description: >- + Whether to restrict routing to only ZDR (Zero Data Retention) endpoints. When true, only endpoints that do not retain prompts will be used. + example: true + enforce_distillable_text: + type: boolean + nullable: true + description: >- + Whether to restrict routing to only models that allow text distillation. When true, only models where the author has allowed distillation will be used. + example: true + order: + type: array + nullable: true + items: + anyOf: + - $ref: '#/components/schemas/ProviderName' + - type: string + description: >- + An ordered list of provider slugs. The router will attempt to use the first provider in the subset of this list that supports your requested model, and fall back to the next if it is unavailable. If no providers are available, the request will fail with an error message. + only: + type: array + nullable: true + items: + anyOf: + - $ref: '#/components/schemas/ProviderName' + - type: string + description: >- + List of provider slugs to allow. If provided, this list is merged with your account-wide allowed provider settings for this request. + ignore: + type: array + nullable: true + items: + anyOf: + - $ref: '#/components/schemas/ProviderName' + - type: string + description: >- + List of provider slugs to ignore. If provided, this list is merged with your account-wide ignored provider settings for this request. + quantizations: + type: array + nullable: true + items: + $ref: '#/components/schemas/Quantization' + description: A list of quantization levels to filter the provider by. + sort: + type: string + nullable: true + enum: + - price + - throughput + - latency + example: price + description: >- + The sorting strategy to use for this request, if "order" is not specified. When set, no load balancing is performed. + x-speakeasy-unknown-values: allow + max_price: + type: object + properties: + prompt: + $ref: '#/components/schemas/BigNumberUnion' + completion: + $ref: '#/components/schemas/BigNumberUnion' + image: + $ref: '#/components/schemas/BigNumberUnion' + audio: + $ref: '#/components/schemas/BigNumberUnion' + request: + $ref: '#/components/schemas/BigNumberUnion' + additionalProperties: false + description: >- + The object specifying the maximum price you want to pay for this request. USD price per million tokens, for prompt and completion. + additionalProperties: false + description: When multiple model providers are available, optionally indicate your routing preference. + plugins: + type: array + items: + oneOf: + - type: object + properties: + id: + type: string + enum: + - moderation + required: + - id + - type: object + properties: + id: + type: string + enum: + - web + max_results: + type: number + search_prompt: + type: string + engine: + type: string + enum: + - native + - exa + x-speakeasy-unknown-values: allow + required: + - id + - type: object + properties: + id: + type: string + enum: + - file-parser + max_files: + type: number + pdf: + type: object + properties: + engine: + type: string + enum: + - mistral-ocr + - pdf-text + - native + x-speakeasy-unknown-values: allow + required: + - id + description: Plugins you want to enable for this request, including their settings. + user: + type: string + maxLength: 128 + description: >- + A unique identifier representing your end-user, which helps distinguish between different users of your app. This allows your app to identify specific users in case of abuse reports, preventing your entire app from being affected by the actions of individual users. Maximum of 128 characters. + description: Request schema for Responses endpoint + example: + model: anthropic/claude-4.5-sonnet-20250929 + input: + - type: message + content: Hello, how are you? + role: user + temperature: 0.7 + top_p: 0.9 + tools: + - type: function + name: get_current_weather + description: Get the current weather in a given location + parameters: + type: object + properties: + location: + type: string + ActivityItem: + type: object + properties: + date: + type: string + description: Date of the activity (YYYY-MM-DD format) + example: '2025-08-24' + model: + type: string + description: Model slug (e.g., "openai/gpt-4.1") + example: openai/gpt-4.1 + model_permaslug: + type: string + description: Model permaslug (e.g., "openai/gpt-4.1-2025-04-14") + example: openai/gpt-4.1-2025-04-14 + endpoint_id: + type: string + description: Unique identifier for the endpoint + example: 550e8400-e29b-41d4-a716-446655440000 + provider_name: + type: string + description: Name of the provider serving this endpoint + example: OpenAI + usage: + type: number + description: Total cost in USD (OpenRouter credits spent) + example: 0.015 + byok_usage_inference: + type: number + description: BYOK inference cost in USD (external credits spent) + example: 0.012 + requests: + type: number + description: Number of requests made + example: 5 + prompt_tokens: + type: number + description: Total prompt tokens used + example: 50 + completion_tokens: + type: number + description: Total completion tokens generated + example: 125 + reasoning_tokens: + type: number + description: Total reasoning tokens used + example: 25 + required: + - date + - model + - model_permaslug + - endpoint_id + - provider_name + - usage + - byok_usage_inference + - requests + - prompt_tokens + - completion_tokens + - reasoning_tokens + example: + date: '2025-08-24' + model: openai/gpt-4.1 + model_permaslug: openai/gpt-4.1-2025-04-14 + endpoint_id: 550e8400-e29b-41d4-a716-446655440000 + provider_name: OpenAI + usage: 0.015 + byok_usage_inference: 0.012 + requests: 5 + prompt_tokens: 50 + completion_tokens: 125 + reasoning_tokens: 25 + ForbiddenResponseErrorData: + type: object + properties: + code: + type: integer + message: + type: string + metadata: + type: object + nullable: true + additionalProperties: + nullable: true + required: + - code + - message + description: Error data for ForbiddenResponse + example: + code: 403 + message: Only provisioning keys can perform this operation + ForbiddenResponse: + type: object + properties: + error: + $ref: '#/components/schemas/ForbiddenResponseErrorData' + user_id: + type: string + nullable: true + required: + - error + description: Forbidden - Authentication successful but insufficient permissions + example: + error: + code: 403 + message: Only provisioning keys can perform this operation + CreateChargeRequest: + type: object + properties: + amount: + type: number + sender: + type: string + chain_id: + type: integer + enum: + - 1 + - 137 + - 8453 + x-speakeasy-unknown-values: allow + required: + - amount + - sender + - chain_id + description: Create a Coinbase charge for crypto payment + example: + amount: 100 + sender: '0x1234567890123456789012345678901234567890' + chain_id: 1 + PublicPricing: + type: object + properties: + prompt: + $ref: '#/components/schemas/BigNumberUnion' + completion: + $ref: '#/components/schemas/BigNumberUnion' + request: + $ref: '#/components/schemas/BigNumberUnion' + image: + $ref: '#/components/schemas/BigNumberUnion' + image_output: + $ref: '#/components/schemas/BigNumberUnion' + audio: + $ref: '#/components/schemas/BigNumberUnion' + input_audio_cache: + $ref: '#/components/schemas/BigNumberUnion' + web_search: + $ref: '#/components/schemas/BigNumberUnion' + internal_reasoning: + $ref: '#/components/schemas/BigNumberUnion' + input_cache_read: + $ref: '#/components/schemas/BigNumberUnion' + input_cache_write: + $ref: '#/components/schemas/BigNumberUnion' + discount: + type: number + required: + - prompt + - completion + additionalProperties: false + description: Pricing information for the model + example: + prompt: '0.00003' + completion: '0.00006' + request: '0' + image: '0' + ModelGroup: + type: string + enum: + - Router + - Media + - Other + - GPT + - Claude + - Gemini + - Grok + - Cohere + - Nova + - Qwen + - Yi + - DeepSeek + - Mistral + - Llama2 + - Llama3 + - Llama4 + - PaLM + - RWKV + - Qwen3 + example: GPT + description: Tokenizer type used by the model + x-speakeasy-unknown-values: allow + InputModality: + type: string + enum: + - text + - image + - file + - audio + - video + example: text + x-speakeasy-unknown-values: allow + OutputModality: + type: string + enum: + - text + - image + - embeddings + example: text + x-speakeasy-unknown-values: allow + ModelArchitecture: + type: object + properties: + tokenizer: + $ref: '#/components/schemas/ModelGroup' + instruct_type: + type: string + nullable: true + enum: + - none + - airoboros + - alpaca + - alpaca-modif + - chatml + - claude + - code-llama + - gemma + - llama2 + - llama3 + - mistral + - nemotron + - neural + - openchat + - phi3 + - rwkv + - vicuna + - zephyr + - deepseek-r1 + - deepseek-v3.1 + - qwq + - qwen3 + example: chatml + description: Instruction format type + x-speakeasy-unknown-values: allow + modality: + type: string + nullable: true + description: Primary modality of the model + example: text->text + input_modalities: + type: array + items: + $ref: '#/components/schemas/InputModality' + description: Supported input modalities + output_modalities: + type: array + items: + $ref: '#/components/schemas/OutputModality' + description: Supported output modalities + required: + - modality + - input_modalities + - output_modalities + description: Model architecture information + example: + tokenizer: GPT + instruct_type: chatml + modality: text->text + input_modalities: + - text + output_modalities: + - text + TopProviderInfo: + type: object + properties: + context_length: + type: number + nullable: true + description: Context length from the top provider + example: 8192 + max_completion_tokens: + type: number + nullable: true + description: Maximum completion tokens from the top provider + example: 4096 + is_moderated: + type: boolean + description: Whether the top provider moderates content + example: true + required: + - is_moderated + description: Information about the top provider for this model + example: + context_length: 8192 + max_completion_tokens: 4096 + is_moderated: true + PerRequestLimits: + type: object + nullable: true + properties: + prompt_tokens: + type: number + example: 1000 + description: Maximum prompt tokens per request + completion_tokens: + type: number + example: 1000 + description: Maximum completion tokens per request + required: + - prompt_tokens + - completion_tokens + description: Per-request token limits + example: + prompt_tokens: 1000 + completion_tokens: 1000 + Parameter: + type: string + enum: + - temperature + - top_p + - top_k + - min_p + - top_a + - frequency_penalty + - presence_penalty + - repetition_penalty + - max_tokens + - logit_bias + - logprobs + - top_logprobs + - seed + - response_format + - structured_outputs + - stop + - tools + - tool_choice + - parallel_tool_calls + - include_reasoning + - reasoning + - web_search_options + - verbosity + example: temperature + x-speakeasy-unknown-values: allow + DefaultParameters: + type: object + nullable: true + properties: + temperature: + type: number + nullable: true + minimum: 0 + maximum: 2 + top_p: + type: number + nullable: true + minimum: 0 + maximum: 1 + frequency_penalty: + type: number + nullable: true + minimum: -2 + maximum: 2 + additionalProperties: false + description: Default parameters for this model + example: + temperature: 0.7 + top_p: 0.9 + frequency_penalty: 0 + Model: + type: object + properties: + id: + type: string + description: Unique identifier for the model + example: openai/gpt-4 + canonical_slug: + type: string + description: Canonical slug for the model + example: openai/gpt-4 + hugging_face_id: + type: string + nullable: true + description: Hugging Face model identifier, if applicable + example: microsoft/DialoGPT-medium + name: + type: string + description: Display name of the model + example: GPT-4 + created: + type: number + description: Unix timestamp of when the model was created + example: 1692901234 + description: + type: string + description: Description of the model + example: GPT-4 is a large multimodal model that can solve difficult problems with greater accuracy. + pricing: + $ref: '#/components/schemas/PublicPricing' + context_length: + type: number + nullable: true + description: Maximum context length in tokens + example: 8192 + architecture: + $ref: '#/components/schemas/ModelArchitecture' + top_provider: + $ref: '#/components/schemas/TopProviderInfo' + per_request_limits: + $ref: '#/components/schemas/PerRequestLimits' + supported_parameters: + type: array + items: + $ref: '#/components/schemas/Parameter' + description: List of supported parameters for this model + default_parameters: + $ref: '#/components/schemas/DefaultParameters' + required: + - id + - canonical_slug + - name + - created + - pricing + - context_length + - architecture + - top_provider + - per_request_limits + - supported_parameters + - default_parameters + description: Information about an AI model available on OpenRouter + example: + id: openai/gpt-4 + canonical_slug: openai/gpt-4 + name: GPT-4 + created: 1692901234 + description: GPT-4 is a large multimodal model that can solve difficult problems with greater accuracy. + pricing: + prompt: '0.00003' + completion: '0.00006' + request: '0' + image: '0' + context_length: 8192 + architecture: + tokenizer: GPT + instruct_type: chatml + modality: text->text + input_modalities: + - text + output_modalities: + - text + top_provider: + context_length: 8192 + max_completion_tokens: 4096 + is_moderated: true + per_request_limits: null + supported_parameters: + - temperature + - top_p + - max_tokens + default_parameters: null + ModelsListResponseData: + type: array + items: + $ref: '#/components/schemas/Model' + description: List of available models + ModelsListResponse: + type: object + properties: + data: + $ref: '#/components/schemas/ModelsListResponseData' + required: + - data + description: List of available models + example: + data: + - id: openai/gpt-4 + canonical_slug: openai/gpt-4 + name: GPT-4 + created: 1692901234 + description: GPT-4 is a large multimodal model that can solve difficult problems with greater accuracy. + pricing: + prompt: '0.00003' + completion: '0.00006' + request: '0' + image: '0' + context_length: 8192 + architecture: + tokenizer: GPT + instruct_type: chatml + modality: text->text + input_modalities: + - text + output_modalities: + - text + top_provider: + context_length: 8192 + max_completion_tokens: 4096 + is_moderated: true + per_request_limits: null + supported_parameters: + - temperature + - top_p + - max_tokens + - frequency_penalty + - presence_penalty + default_parameters: null + ModelsCountResponse: + type: object + properties: + data: + type: object + properties: + count: + type: number + description: Total number of available models + example: 150 + required: + - count + description: Model count data + example: + count: 150 + required: + - data + description: Model count data + example: + data: + count: 150 + InstructType: + type: string + nullable: true + enum: + - none + - airoboros + - alpaca + - alpaca-modif + - chatml + - claude + - code-llama + - gemma + - llama2 + - llama3 + - mistral + - nemotron + - neural + - openchat + - phi3 + - rwkv + - vicuna + - zephyr + - deepseek-r1 + - deepseek-v3.1 + - qwq + - qwen3 + description: Instruction format type + x-speakeasy-unknown-values: allow + EndpointStatus: + type: integer + enum: + - 0 + - -1 + - -2 + - -3 + - -5 + - -10 + example: 0 + x-speakeasy-unknown-values: allow + PublicEndpoint: + type: object + properties: + name: + type: string + model_name: + type: string + context_length: + type: number + pricing: + type: object + properties: + prompt: + $ref: '#/components/schemas/BigNumberUnion' + completion: + $ref: '#/components/schemas/BigNumberUnion' + request: + $ref: '#/components/schemas/BigNumberUnion' + image: + $ref: '#/components/schemas/BigNumberUnion' + image_output: + $ref: '#/components/schemas/BigNumberUnion' + audio: + $ref: '#/components/schemas/BigNumberUnion' + input_audio_cache: + $ref: '#/components/schemas/BigNumberUnion' + web_search: + $ref: '#/components/schemas/BigNumberUnion' + internal_reasoning: + $ref: '#/components/schemas/BigNumberUnion' + input_cache_read: + $ref: '#/components/schemas/BigNumberUnion' + input_cache_write: + $ref: '#/components/schemas/BigNumberUnion' + discount: + type: number + required: + - prompt + - completion + additionalProperties: false + provider_name: + $ref: '#/components/schemas/ProviderName' + tag: + type: string + quantization: + allOf: + - $ref: '#/components/schemas/Quantization' + - nullable: true + max_completion_tokens: + type: number + nullable: true + max_prompt_tokens: + type: number + nullable: true + supported_parameters: + type: array + items: + $ref: '#/components/schemas/Parameter' + status: + $ref: '#/components/schemas/EndpointStatus' + uptime_last_30m: + type: number + nullable: true + supports_implicit_caching: + type: boolean + required: + - name + - model_name + - context_length + - pricing + - provider_name + - tag + - quantization + - max_completion_tokens + - max_prompt_tokens + - supported_parameters + - uptime_last_30m + - supports_implicit_caching + description: Information about a specific model endpoint + example: + name: 'OpenAI: GPT-4' + model_name: GPT-4 + context_length: 8192 + pricing: + prompt: '0.00003' + completion: '0.00006' + request: '0' + image: '0' + provider_name: OpenAI + tag: openai + quantization: fp16 + max_completion_tokens: 4096 + max_prompt_tokens: 8192 + supported_parameters: + - temperature + - top_p + - max_tokens + status: 0 + uptime_last_30m: 99.5 + supports_implicit_caching: true + ListEndpointsResponse: + type: object + properties: + id: + type: string + description: Unique identifier for the model + example: openai/gpt-4 + name: + type: string + description: Display name of the model + example: GPT-4 + created: + type: number + description: Unix timestamp of when the model was created + example: 1692901234 + description: + type: string + description: Description of the model + example: GPT-4 is a large multimodal model that can solve difficult problems with greater accuracy. + architecture: + allOf: + - $ref: '#/components/schemas/ModelArchitecture' + - properties: + tokenizer: + allOf: + - $ref: '#/components/schemas/ModelGroup' + - nullable: true + instruct_type: + $ref: '#/components/schemas/InstructType' + modality: + type: string + nullable: true + description: Primary modality of the model + example: text + input_modalities: + type: array + items: + $ref: '#/components/schemas/InputModality' + description: Supported input modalities + output_modalities: + type: array + items: + $ref: '#/components/schemas/OutputModality' + description: Supported output modalities + required: + - tokenizer + - instruct_type + - modality + - input_modalities + - output_modalities + example: + tokenizer: GPT + instruct_type: chatml + modality: text + endpoints: + type: array + items: + $ref: '#/components/schemas/PublicEndpoint' + description: List of available endpoints for this model + required: + - id + - name + - created + - description + - architecture + - endpoints + description: List of available endpoints for a model + example: + id: openai/gpt-4 + name: GPT-4 + created: 1692901234 + description: GPT-4 is a large multimodal model that can solve difficult problems with greater accuracy. + architecture: + tokenizer: GPT + instruct_type: chatml + modality: text->text + input_modalities: + - text + output_modalities: + - text + endpoints: + - name: 'OpenAI: GPT-4' + model_name: GPT-4 + context_length: 8192 + pricing: + prompt: '0.00003' + completion: '0.00006' + request: '0' + image: '0' + provider_name: OpenAI + tag: openai + quantization: fp16 + max_completion_tokens: 4096 + max_prompt_tokens: 8192 + supported_parameters: + - temperature + - top_p + - max_tokens + - frequency_penalty + - presence_penalty + status: default + uptime_last_30m: 99.5 + supports_implicit_caching: true + __schema0: + anyOf: + - $ref: '#/components/schemas/ChatCompletionFinishReason' + - type: 'null' + ModelName: + type: string + ChatMessageContentItemText: + type: object + properties: + type: + type: string + const: text + text: + type: string + required: + - type + - text + ChatMessageContentItemImage: + type: object + properties: + type: + type: string + const: image_url + image_url: + type: object + properties: + url: + type: string + detail: + type: string + enum: + - auto + - low + - high + x-speakeasy-unknown-values: allow + required: + - url + required: + - type + - image_url + ChatMessageContentItemAudio: + type: object + properties: + type: + type: string + const: input_audio + input_audio: + type: object + properties: + data: + type: string + format: + type: string + enum: + - wav + - mp3 + - flac + - m4a + - ogg + - pcm16 + - pcm24 + x-speakeasy-unknown-values: allow + required: + - data + - format + required: + - type + - input_audio + ChatMessageContentItemVideo: + type: object + properties: + type: + type: string + const: input_video + video_url: + type: object + properties: + url: + type: string + required: + - url + required: + - type + - video_url + ChatMessageContentItem: + oneOf: + - $ref: '#/components/schemas/ChatMessageContentItemText' + - $ref: '#/components/schemas/ChatMessageContentItemImage' + - $ref: '#/components/schemas/ChatMessageContentItemAudio' + - $ref: '#/components/schemas/ChatMessageContentItemVideo' + type: object + discriminator: + propertyName: type + mapping: + text: '#/components/schemas/ChatMessageContentItemText' + image_url: '#/components/schemas/ChatMessageContentItemImage' + input_audio: '#/components/schemas/ChatMessageContentItemAudio' + input_video: '#/components/schemas/ChatMessageContentItemVideo' + ChatMessageToolCall: + type: object + properties: + id: + type: string + type: + type: string + const: function + function: + type: object + properties: + name: + type: string + arguments: + type: string + required: + - name + - arguments + required: + - id + - type + - function + ChatMessageTokenLogprob: + type: object + properties: + token: + type: string + logprob: + type: number + bytes: + anyOf: + - type: array + items: + type: number + - type: 'null' + top_logprobs: + type: array + items: + type: object + properties: + token: + type: string + logprob: + type: number + bytes: + anyOf: + - type: array + items: + type: number + - type: 'null' + required: + - token + - logprob + - bytes + required: + - token + - logprob + - bytes + - top_logprobs + ChatMessageTokenLogprobs: + type: object + properties: + content: + anyOf: + - type: array + items: + $ref: '#/components/schemas/ChatMessageTokenLogprob' + - type: 'null' + refusal: + anyOf: + - type: array + items: + $ref: '#/components/schemas/ChatMessageTokenLogprob' + - type: 'null' + required: + - content + - refusal + ChatGenerationTokenUsage: + type: object + properties: + completion_tokens: + type: number + prompt_tokens: + type: number + total_tokens: + type: number + completion_tokens_details: + anyOf: + - type: object + properties: + reasoning_tokens: + anyOf: + - type: number + - type: 'null' + audio_tokens: + anyOf: + - type: number + - type: 'null' + accepted_prediction_tokens: + anyOf: + - type: number + - type: 'null' + rejected_prediction_tokens: + anyOf: + - type: number + - type: 'null' + - type: 'null' + prompt_tokens_details: + anyOf: + - type: object + properties: + cached_tokens: + type: number + audio_tokens: + type: number + video_tokens: + type: number + - type: 'null' + required: + - completion_tokens + - prompt_tokens + - total_tokens + ChatCompletionFinishReason: + type: string + enum: + - tool_calls + - stop + - length + - content_filter + - error + x-speakeasy-unknown-values: allow + JSONSchemaConfig: + type: object + properties: + name: + type: string + maxLength: 64 + description: + type: string + schema: + type: object + propertyNames: + type: string + additionalProperties: {} + strict: + anyOf: + - type: boolean + - type: 'null' + required: + - name + ResponseFormatJSONSchema: + type: object + properties: + type: + type: string + const: json_schema + json_schema: + $ref: '#/components/schemas/JSONSchemaConfig' + required: + - type + - json_schema + ResponseFormatTextGrammar: + type: object + properties: + type: + type: string + const: grammar + grammar: + type: string + required: + - type + - grammar + SystemMessage: + type: object + properties: + role: + type: string + const: system + content: + anyOf: + - type: string + - type: array + items: + $ref: '#/components/schemas/ChatMessageContentItemText' + name: + type: string + required: + - role + - content + UserMessage: + type: object + properties: + role: + type: string + const: user + content: + anyOf: + - type: string + - type: array + items: + $ref: '#/components/schemas/ChatMessageContentItem' + name: + type: string + required: + - role + - content + AssistantMessage: + type: object + properties: + role: + type: string + const: assistant + content: + anyOf: + - anyOf: + - type: string + - type: array + items: + $ref: '#/components/schemas/ChatMessageContentItem' + - type: 'null' + name: + type: string + tool_calls: + type: array + items: + $ref: '#/components/schemas/ChatMessageToolCall' + refusal: + anyOf: + - type: string + - type: 'null' + reasoning: + anyOf: + - type: string + - type: 'null' + required: + - role + ToolResponseMessage: + type: object + properties: + role: + type: string + const: tool + content: + anyOf: + - type: string + - type: array + items: + $ref: '#/components/schemas/ChatMessageContentItem' + tool_call_id: + type: string + required: + - role + - content + - tool_call_id + Message: + oneOf: + - $ref: '#/components/schemas/SystemMessage' + - $ref: '#/components/schemas/UserMessage' + - type: object + properties: + role: + type: string + const: developer + content: + anyOf: + - type: string + - type: array + items: + $ref: '#/components/schemas/ChatMessageContentItemText' + name: + type: string + required: + - role + - content + - $ref: '#/components/schemas/AssistantMessage' + - $ref: '#/components/schemas/ToolResponseMessage' + type: object + ToolDefinitionJson: + type: object + properties: + type: + type: string + const: function + function: + type: object + properties: + name: + type: string + maxLength: 64 + description: + type: string + parameters: + type: object + propertyNames: + type: string + additionalProperties: {} + strict: + anyOf: + - type: boolean + - type: 'null' + required: + - name + required: + - type + - function + NamedToolChoice: + type: object + properties: + type: + type: string + const: function + function: + type: object + properties: + name: + type: string + required: + - name + required: + - type + - function + ToolChoiceOption: + anyOf: + - type: string + const: none + - type: string + const: auto + - type: string + const: required + - $ref: '#/components/schemas/NamedToolChoice' + ChatStreamOptions: + type: object + properties: + include_usage: + type: boolean + ChatGenerationParams: + type: object + properties: + messages: + minItems: 1 + type: array + items: + $ref: '#/components/schemas/Message' + model: + $ref: '#/components/schemas/ModelName' + models: + type: array + items: + $ref: '#/components/schemas/ModelName' + frequency_penalty: + anyOf: + - type: number + minimum: -2 + maximum: 2 + - type: 'null' + logit_bias: + anyOf: + - type: object + propertyNames: + type: string + additionalProperties: + type: number + - type: 'null' + logprobs: + anyOf: + - type: boolean + - type: 'null' + top_logprobs: + anyOf: + - type: number + minimum: 0 + maximum: 20 + - type: 'null' + max_completion_tokens: + anyOf: + - type: number + minimum: 1 + - type: 'null' + max_tokens: + anyOf: + - type: number + minimum: 1 + - type: 'null' + metadata: + type: object + propertyNames: + type: string + additionalProperties: + type: string + presence_penalty: + anyOf: + - type: number + minimum: -2 + maximum: 2 + - type: 'null' + reasoning: + type: object + properties: + effort: + anyOf: + - type: string + enum: + - minimal + - low + - medium + - high + x-speakeasy-unknown-values: allow + - type: 'null' + summary: + anyOf: + - $ref: '#/components/schemas/ReasoningSummaryVerbosity' + - type: 'null' + response_format: + oneOf: + - type: object + properties: + type: + type: string + const: text + required: + - type + - type: object + properties: + type: + type: string + const: json_object + required: + - type + - $ref: '#/components/schemas/ResponseFormatJSONSchema' + - $ref: '#/components/schemas/ResponseFormatTextGrammar' + - type: object + properties: + type: + type: string + const: python + required: + - type + type: object + seed: + anyOf: + - type: integer + minimum: -9007199254740991 + maximum: 9007199254740991 + - type: 'null' + stop: + anyOf: + - anyOf: + - type: string + - maxItems: 4 + type: array + items: + type: string + - type: 'null' + stream: + default: false + type: boolean + stream_options: + anyOf: + - $ref: '#/components/schemas/ChatStreamOptions' + - type: 'null' + temperature: + default: 1 + anyOf: + - type: number + minimum: 0 + maximum: 2 + - type: 'null' + tool_choice: + $ref: '#/components/schemas/ToolChoiceOption' + tools: + type: array + items: + $ref: '#/components/schemas/ToolDefinitionJson' + top_p: + default: 1 + anyOf: + - type: number + minimum: 0 + maximum: 1 + - type: 'null' + user: + type: string + required: + - messages + ChatResponseChoice: + type: object + properties: + finish_reason: + $ref: '#/components/schemas/__schema0' + index: + type: number + message: + $ref: '#/components/schemas/AssistantMessage' + logprobs: + anyOf: + - $ref: '#/components/schemas/ChatMessageTokenLogprobs' + - type: 'null' + required: + - finish_reason + - index + - message + ChatStreamingMessageToolCall: + type: object + properties: + index: + type: number + id: + type: string + type: + type: string + const: function + function: + type: object + properties: + name: + type: string + arguments: + type: string + required: + - index + ChatStreamingMessageChunk: + type: object + properties: + role: + type: string + enum: + - assistant + content: + anyOf: + - type: string + - type: 'null' + reasoning: + anyOf: + - type: string + - type: 'null' + refusal: + anyOf: + - type: string + - type: 'null' + tool_calls: + type: array + items: + $ref: '#/components/schemas/ChatStreamingMessageToolCall' + ChatStreamingChoice: + type: object + properties: + delta: + $ref: '#/components/schemas/ChatStreamingMessageChunk' + finish_reason: + $ref: '#/components/schemas/__schema0' + index: + type: number + logprobs: + anyOf: + - $ref: '#/components/schemas/ChatMessageTokenLogprobs' + - type: 'null' + required: + - delta + - finish_reason + - index + ChatError: + type: object + properties: + error: + type: object + properties: + code: + anyOf: + - anyOf: + - type: string + - type: number + - type: 'null' + message: + type: string + param: + anyOf: + - type: string + - type: 'null' + type: + anyOf: + - type: string + - type: 'null' + required: + - code + - message + additionalProperties: false + required: + - error + additionalProperties: false + ChatResponse: + type: object + properties: + id: + type: string + choices: + type: array + items: + $ref: '#/components/schemas/ChatResponseChoice' + created: + type: number + model: + type: string + object: + type: string + const: chat.completion + system_fingerprint: + anyOf: + - type: string + - type: 'null' + usage: + $ref: '#/components/schemas/ChatGenerationTokenUsage' + required: + - id + - choices + - created + - model + - object + additionalProperties: false + ChatStreamingResponseChunk: + type: object + properties: + data: + type: object + properties: + id: + type: string + choices: + type: array + items: + $ref: '#/components/schemas/ChatStreamingChoice' + created: + type: number + model: + type: string + object: + type: string + const: chat.completion.chunk + system_fingerprint: + anyOf: + - type: string + - type: 'null' + error: + type: object + properties: + message: + type: string + code: + type: number + required: + - message + - code + additionalProperties: false + usage: + $ref: '#/components/schemas/ChatGenerationTokenUsage' + required: + - id + - choices + - created + - model + - object + additionalProperties: false + required: + - data + additionalProperties: false + CompletionFinishReason: + anyOf: + - type: string + enum: + - stop + - length + - content_filter + x-speakeasy-unknown-values: allow + - type: 'null' + CompletionLogprobs: + type: object + properties: + tokens: + type: array + items: + type: string + token_logprobs: + type: array + items: + type: number + top_logprobs: + anyOf: + - type: array + items: + type: object + propertyNames: + type: string + additionalProperties: + type: number + - type: 'null' + text_offset: + type: array + items: + type: number + required: + - tokens + - token_logprobs + - top_logprobs + - text_offset + CompletionUsage: + type: object + properties: + prompt_tokens: + type: number + completion_tokens: + type: number + total_tokens: + type: number + required: + - prompt_tokens + - completion_tokens + - total_tokens + CompletionCreateParams: + type: object + properties: + model: + $ref: '#/components/schemas/ModelName' + models: + type: array + items: + $ref: '#/components/schemas/ModelName' + prompt: + anyOf: + - type: string + - type: array + items: + type: string + - type: array + items: + type: number + - type: array + items: + type: array + items: + type: number + best_of: + anyOf: + - type: integer + minimum: 1 + maximum: 20 + - type: 'null' + echo: + anyOf: + - type: boolean + - type: 'null' + frequency_penalty: + anyOf: + - type: number + minimum: -2 + maximum: 2 + - type: 'null' + logit_bias: + anyOf: + - type: object + propertyNames: + type: string + additionalProperties: + type: number + - type: 'null' + logprobs: + anyOf: + - type: integer + minimum: 0 + maximum: 5 + - type: 'null' + max_tokens: + anyOf: + - type: integer + minimum: 1 + maximum: 9007199254740991 + - type: 'null' + 'n': + anyOf: + - type: integer + minimum: 1 + maximum: 128 + - type: 'null' + presence_penalty: + anyOf: + - type: number + minimum: -2 + maximum: 2 + - type: 'null' + seed: + anyOf: + - type: integer + minimum: -9007199254740991 + maximum: 9007199254740991 + - type: 'null' + stop: + anyOf: + - anyOf: + - type: string + - type: array + items: + type: string + - type: 'null' + stream: + default: false + type: boolean + stream_options: + anyOf: + - type: object + properties: + include_usage: + anyOf: + - type: boolean + - type: 'null' + - type: 'null' + suffix: + anyOf: + - type: string + - type: 'null' + temperature: + anyOf: + - type: number + minimum: 0 + maximum: 2 + - type: 'null' + top_p: + anyOf: + - type: number + minimum: 0 + maximum: 1 + - type: 'null' + user: + type: string + metadata: + anyOf: + - type: object + propertyNames: + type: string + additionalProperties: + type: string + - type: 'null' + response_format: + anyOf: + - oneOf: + - type: object + properties: + type: + type: string + const: text + required: + - type + - type: object + properties: + type: + type: string + const: json_object + required: + - type + - $ref: '#/components/schemas/ResponseFormatJSONSchema' + - $ref: '#/components/schemas/ResponseFormatTextGrammar' + - type: object + properties: + type: + type: string + const: python + required: + - type + type: object + - type: 'null' + required: + - prompt + CompletionChoice: + type: object + properties: + text: + type: string + index: + type: number + logprobs: + anyOf: + - $ref: '#/components/schemas/CompletionLogprobs' + - type: 'null' + finish_reason: + $ref: '#/components/schemas/CompletionFinishReason' + required: + - text + - index + - logprobs + - finish_reason + CompletionResponse: + type: object + properties: + id: + type: string + object: + type: string + const: text_completion + created: + type: number + model: + type: string + system_fingerprint: + type: string + choices: + type: array + items: + $ref: '#/components/schemas/CompletionChoice' + usage: + $ref: '#/components/schemas/CompletionUsage' + required: + - id + - object + - created + - model + - choices + additionalProperties: false + parameters: {} + securitySchemes: + apiKey: + type: http + scheme: bearer + description: API key as bearer token in Authorization header + bearer: + type: http + scheme: bearer + description: API key as bearer token in Authorization header +paths: + /responses: + post: + x-speakeasy-name-override: send + x-speakeasy-stream-request-field: stream + tags: + - beta.responses + summary: Create a response + description: Creates a streaming or non-streaming response using OpenResponses API format + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OpenResponsesRequest' + required: true + responses: + '200': + description: Successful response + content: + application/json: + schema: + $ref: '#/components/schemas/OpenResponsesNonStreamingResponse' + text/event-stream: + schema: + type: object + properties: + data: + $ref: '#/components/schemas/OpenResponsesStreamEvent' + required: + - data + x-speakeasy-sse-sentinel: '[DONE]' + '400': + description: Bad Request - Invalid request parameters or malformed input + content: + application/json: + schema: + $ref: '#/components/schemas/BadRequestResponse' + '401': + description: Unauthorized - Authentication required or invalid credentials + content: + application/json: + schema: + $ref: '#/components/schemas/UnauthorizedResponse' + '402': + description: Payment Required - Insufficient credits or quota to complete request + content: + application/json: + schema: + $ref: '#/components/schemas/PaymentRequiredResponse' + '404': + description: Not Found - Resource does not exist + content: + application/json: + schema: + $ref: '#/components/schemas/NotFoundResponse' + '408': + description: Request Timeout - Operation exceeded time limit + content: + application/json: + schema: + $ref: '#/components/schemas/RequestTimeoutResponse' + '413': + description: Payload Too Large - Request payload exceeds size limits + content: + application/json: + schema: + $ref: '#/components/schemas/PayloadTooLargeResponse' + '422': + description: Unprocessable Entity - Semantic validation failure + content: + application/json: + schema: + $ref: '#/components/schemas/UnprocessableEntityResponse' + '429': + description: Too Many Requests - Rate limit exceeded + content: + application/json: + schema: + $ref: '#/components/schemas/TooManyRequestsResponse' + '500': + description: Internal Server Error - Unexpected server error + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerResponse' + '502': + description: Bad Gateway - Provider/upstream API failure + content: + application/json: + schema: + $ref: '#/components/schemas/BadGatewayResponse' + '503': + description: Service Unavailable - Service temporarily unavailable + content: + application/json: + schema: + $ref: '#/components/schemas/ServiceUnavailableResponse' + '524': + description: Infrastructure Timeout - Request timed out at our edge network + content: + application/json: + schema: + $ref: '#/components/schemas/EdgeNetworkTimeoutResponse' + '529': + description: Provider Overloaded - Provider is temporarily overloaded + content: + application/json: + schema: + $ref: '#/components/schemas/ProviderOverloadedResponse' + operationId: createResponses + /activity: + get: + tags: + - Analytics + operationId: getUserActivity + summary: Get user activity grouped by endpoint + description: Returns user activity data grouped by endpoint for the last 30 (completed) UTC days + parameters: + - schema: + type: string + description: Filter by a single UTC date in the last 30 days (YYYY-MM-DD format). + example: '2025-08-24' + required: false + description: Filter by a single UTC date in the last 30 days (YYYY-MM-DD format). + name: date + in: query + responses: + '200': + description: Returns user activity data grouped by endpoint + content: + application/json: + schema: + type: object + properties: + data: + type: array + items: + $ref: '#/components/schemas/ActivityItem' + description: List of activity items + required: + - data + example: + data: + - date: '2025-08-24' + model: openai/gpt-4.1 + model_permaslug: openai/gpt-4.1-2025-04-14 + endpoint_id: 550e8400-e29b-41d4-a716-446655440000 + provider_name: OpenAI + usage: 0.015 + byok_usage_inference: 0.012 + requests: 5 + prompt_tokens: 50 + completion_tokens: 125 + reasoning_tokens: 25 + '400': + description: Bad Request - Invalid date format or date range + content: + application/json: + schema: + $ref: '#/components/schemas/BadRequestResponse' + '401': + description: Unauthorized - Authentication required or invalid credentials + content: + application/json: + schema: + $ref: '#/components/schemas/UnauthorizedResponse' + '403': + description: Forbidden - Only provisioning keys can fetch activity + content: + application/json: + schema: + $ref: '#/components/schemas/ForbiddenResponse' + '500': + description: Internal Server Error - Unexpected server error + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerResponse' + /credits: + get: + x-speakeasy-name-override: getCredits + tags: + - Credits + summary: Get remaining credits + operationId: getCredits + description: Get total credits purchased and used for the authenticated user + responses: + '200': + description: Returns the total credits purchased and used + content: + application/json: + schema: + type: object + description: Total credits purchased and used + example: + data: + total_credits: 100.5 + total_usage: 25.75 + '401': + description: Unauthorized - Authentication required or invalid credentials + content: + application/json: + schema: + $ref: '#/components/schemas/UnauthorizedResponse' + '403': + description: Forbidden - Only provisioning keys can fetch credits + content: + application/json: + schema: + $ref: '#/components/schemas/ForbiddenResponse' + '500': + description: Internal Server Error - Unexpected server error + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerResponse' + /credits/coinbase: + post: + security: + - bearer: [] + x-speakeasy-name-override: createCoinbaseCharge + tags: + - Credits + summary: Create a Coinbase charge for crypto payment + operationId: createCoinbaseCharge + description: Create a Coinbase charge for crypto payment + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/CreateChargeRequest' + required: true + responses: + '200': + description: Returns the calldata to fulfill the transaction + content: + application/json: + schema: + type: object + properties: + data: + type: object + properties: + id: + type: string + created_at: + type: string + expires_at: + type: string + web3_data: + type: object + properties: + transfer_intent: + type: object + properties: + call_data: + type: object + properties: + deadline: + type: string + fee_amount: + type: string + id: + type: string + operator: + type: string + prefix: + type: string + recipient: + type: string + recipient_amount: + type: string + recipient_currency: + type: string + refund_destination: + type: string + signature: + type: string + required: + - deadline + - fee_amount + - id + - operator + - prefix + - recipient + - recipient_amount + - recipient_currency + - refund_destination + - signature + metadata: + type: object + properties: + chain_id: + type: number + contract_address: + type: string + sender: + type: string + required: + - chain_id + - contract_address + - sender + required: + - call_data + - metadata + required: + - transfer_intent + required: + - id + - created_at + - expires_at + - web3_data + required: + - data + '400': + description: Bad Request - Invalid credit amount or request body + content: + application/json: + schema: + $ref: '#/components/schemas/BadRequestResponse' + '401': + description: Unauthorized - Authentication required or invalid credentials + content: + application/json: + schema: + $ref: '#/components/schemas/UnauthorizedResponse' + '429': + description: Too Many Requests - Rate limit exceeded + content: + application/json: + schema: + $ref: '#/components/schemas/TooManyRequestsResponse' + '500': + description: Internal Server Error - Unexpected server error + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerResponse' + /embeddings: + post: + x-speakeasy-name-override: generate + tags: + - Embeddings + summary: Submit an embedding request + description: Submits an embedding request to the embeddings router + requestBody: + content: + application/json: + schema: + type: object + properties: + input: + anyOf: + - type: string + - type: array + items: + type: string + - type: array + items: + type: number + - type: array + items: + type: array + items: + type: number + model: + type: string + provider: + type: object + properties: + allow_fallbacks: + type: boolean + nullable: true + description: > + Whether to allow backup providers to serve requests + + - true: (default) when the primary provider (or your custom providers in "order") is unavailable, use the next best provider. + + - false: use only the primary/custom provider, and return the upstream error if it's unavailable. + + require_parameters: + type: boolean + nullable: true + description: >- + Whether to filter providers to only those that support the parameters you've provided. If this setting is omitted or set to false, then providers will receive only the parameters they support, and ignore the rest. + data_collection: + type: string + nullable: true + enum: + - deny + - allow + example: deny + description: > + Data collection setting. If no available model provider meets the requirement, your request will return an error. + + - allow: (default) allow providers which store user data non-transiently and may train on it + + - deny: use only providers which do not collect user data. + + x-speakeasy-unknown-values: allow + zdr: + type: boolean + nullable: true + description: >- + Whether to restrict routing to only ZDR (Zero Data Retention) endpoints. When true, only endpoints that do not retain prompts will be used. + example: true + enforce_distillable_text: + type: boolean + nullable: true + description: >- + Whether to restrict routing to only models that allow text distillation. When true, only models where the author has allowed distillation will be used. + example: true + order: + type: array + nullable: true + items: + anyOf: + - $ref: '#/components/schemas/ProviderName' + - type: string + description: >- + An ordered list of provider slugs. The router will attempt to use the first provider in the subset of this list that supports your requested model, and fall back to the next if it is unavailable. If no providers are available, the request will fail with an error message. + only: + type: array + nullable: true + items: + anyOf: + - $ref: '#/components/schemas/ProviderName' + - type: string + description: >- + List of provider slugs to allow. If provided, this list is merged with your account-wide allowed provider settings for this request. + ignore: + type: array + nullable: true + items: + anyOf: + - $ref: '#/components/schemas/ProviderName' + - type: string + description: >- + List of provider slugs to ignore. If provided, this list is merged with your account-wide ignored provider settings for this request. + quantizations: + type: array + nullable: true + items: + $ref: '#/components/schemas/Quantization' + description: A list of quantization levels to filter the provider by. + sort: + type: string + nullable: true + enum: + - price + - throughput + - latency + example: price + description: >- + The sorting strategy to use for this request, if "order" is not specified. When set, no load balancing is performed. + x-speakeasy-unknown-values: allow + max_price: + type: object + properties: + prompt: + $ref: '#/components/schemas/BigNumberUnion' + completion: + $ref: '#/components/schemas/BigNumberUnion' + image: + $ref: '#/components/schemas/BigNumberUnion' + audio: + $ref: '#/components/schemas/BigNumberUnion' + request: + $ref: '#/components/schemas/BigNumberUnion' + additionalProperties: false + description: >- + The object specifying the maximum price you want to pay for this request. USD price per million tokens, for prompt and completion. + encoding_format: + anyOf: + - type: string + enum: + - float + - type: string + enum: + - base64 + user: + type: string + required: + - input + - model + required: true + responses: + '200': + description: Embedding response + content: + application/json: + schema: + type: object + properties: + id: + type: string + object: + type: string + enum: + - list + data: + type: array + items: + type: object + properties: + object: + type: string + enum: + - embedding + embedding: + anyOf: + - type: array + items: + type: number + - type: string + index: + type: number + required: + - object + - embedding + model: + type: string + usage: + type: object + properties: + prompt_tokens: + type: number + total_tokens: + type: number + cost: + type: number + required: + - prompt_tokens + - total_tokens + required: + - object + - data + - model + text/event-stream: + schema: + type: string + description: Not used for embeddings - embeddings do not support streaming + x-speakeasy-sse-sentinel: '[DONE]' + '400': + description: Bad Request - Invalid request parameters or malformed input + content: + application/json: + schema: + $ref: '#/components/schemas/BadRequestResponse' + '401': + description: Unauthorized - Authentication required or invalid credentials + content: + application/json: + schema: + $ref: '#/components/schemas/UnauthorizedResponse' + '402': + description: Payment Required - Insufficient credits or quota to complete request + content: + application/json: + schema: + $ref: '#/components/schemas/PaymentRequiredResponse' + '404': + description: Not Found - Resource does not exist + content: + application/json: + schema: + $ref: '#/components/schemas/NotFoundResponse' + '429': + description: Too Many Requests - Rate limit exceeded + content: + application/json: + schema: + $ref: '#/components/schemas/TooManyRequestsResponse' + '500': + description: Internal Server Error - Unexpected server error + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerResponse' + '502': + description: Bad Gateway - Provider/upstream API failure + content: + application/json: + schema: + $ref: '#/components/schemas/BadGatewayResponse' + '503': + description: Service Unavailable - Service temporarily unavailable + content: + application/json: + schema: + $ref: '#/components/schemas/ServiceUnavailableResponse' + '524': + description: Cloudflare Timeout - Provider request timed out at CDN edge + content: + application/json: + schema: + $ref: '#/components/schemas/EdgeNetworkTimeoutResponse' + '529': + description: Provider Overloaded - Provider is temporarily overloaded + content: + application/json: + schema: + $ref: '#/components/schemas/ProviderOverloadedResponse' + operationId: createEmbeddings + /embeddings/models: + get: + tags: + - Embeddings + x-speakeasy-name-override: listModels + summary: List all embeddings models + description: Returns a list of all available embeddings models and their properties + responses: + '200': + description: Returns a list of embeddings models + content: + application/json: + schema: + $ref: '#/components/schemas/ModelsListResponse' + '400': + description: Bad Request - Invalid request parameters + content: + application/json: + schema: + $ref: '#/components/schemas/BadRequestResponse' + '500': + description: Internal Server Error + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerResponse' + operationId: listEmbeddingsModels + /generation: + get: + tags: + - Generations + summary: Get request & usage metadata for a generation + parameters: + - schema: + type: string + minLength: 1 + required: true + name: id + in: query + responses: + '200': + description: Returns the request metadata for this generation + content: + application/json: + schema: + type: object + properties: + data: + type: object + properties: + id: + type: string + description: Unique identifier for the generation + example: gen-3bhGkxlo4XFrqiabUM7NDtwDzWwG + upstream_id: + type: string + nullable: true + description: Upstream provider's identifier for this generation + example: chatcmpl-791bcf62-080e-4568-87d0-94c72e3b4946 + total_cost: + type: number + description: Total cost of the generation in USD + example: 0.0015 + cache_discount: + type: number + nullable: true + description: Discount applied due to caching + example: 0.0002 + upstream_inference_cost: + type: number + nullable: true + description: Cost charged by the upstream provider + example: 0.0012 + created_at: + type: string + description: ISO 8601 timestamp of when the generation was created + example: '2024-07-15T23:33:19.433273+00:00' + model: + type: string + description: Model used for the generation + example: sao10k/l3-stheno-8b + app_id: + type: number + nullable: true + description: ID of the app that made the request + example: 12345 + streamed: + type: boolean + nullable: true + description: Whether the response was streamed + example: true + cancelled: + type: boolean + nullable: true + description: Whether the generation was cancelled + example: false + provider_name: + type: string + nullable: true + description: Name of the provider that served the request + example: Infermatic + latency: + type: number + nullable: true + description: Total latency in milliseconds + example: 1250 + moderation_latency: + type: number + nullable: true + description: Moderation latency in milliseconds + example: 50 + generation_time: + type: number + nullable: true + description: Time taken for generation in milliseconds + example: 1200 + finish_reason: + type: string + nullable: true + description: Reason the generation finished + example: stop + tokens_prompt: + type: number + nullable: true + description: Number of tokens in the prompt + example: 10 + tokens_completion: + type: number + nullable: true + description: Number of tokens in the completion + example: 25 + native_tokens_prompt: + type: number + nullable: true + description: Native prompt tokens as reported by provider + example: 10 + native_tokens_completion: + type: number + nullable: true + description: Native completion tokens as reported by provider + example: 25 + native_tokens_completion_images: + type: number + nullable: true + description: Native completion image tokens as reported by provider + example: 0 + native_tokens_reasoning: + type: number + nullable: true + description: Native reasoning tokens as reported by provider + example: 5 + native_tokens_cached: + type: number + nullable: true + description: Native cached tokens as reported by provider + example: 3 + num_media_prompt: + type: number + nullable: true + description: Number of media items in the prompt + example: 1 + num_input_audio_prompt: + type: number + nullable: true + description: Number of audio inputs in the prompt + example: 0 + num_media_completion: + type: number + nullable: true + description: Number of media items in the completion + example: 0 + num_search_results: + type: number + nullable: true + description: Number of search results included + example: 5 + origin: + type: string + description: Origin URL of the request + example: https://openrouter.ai/ + usage: + type: number + description: Usage amount in USD + example: 0.0015 + is_byok: + type: boolean + description: Whether this used bring-your-own-key + example: false + native_finish_reason: + type: string + nullable: true + description: Native finish reason as reported by provider + example: stop + external_user: + type: string + nullable: true + description: External user identifier + example: user-123 + api_type: + type: string + nullable: true + enum: + - completions + - embeddings + description: Type of API used for the generation + x-speakeasy-unknown-values: allow + required: + - id + - upstream_id + - total_cost + - cache_discount + - upstream_inference_cost + - created_at + - model + - app_id + - streamed + - cancelled + - provider_name + - latency + - moderation_latency + - generation_time + - finish_reason + - tokens_prompt + - tokens_completion + - native_tokens_prompt + - native_tokens_completion + - native_tokens_completion_images + - native_tokens_reasoning + - native_tokens_cached + - num_media_prompt + - num_input_audio_prompt + - num_media_completion + - num_search_results + - origin + - usage + - is_byok + - native_finish_reason + - external_user + - api_type + description: Generation data + required: + - data + description: Generation response + '401': + description: Unauthorized - Authentication required or invalid credentials + content: + application/json: + schema: + $ref: '#/components/schemas/UnauthorizedResponse' + '402': + description: Payment Required - Insufficient credits or quota to complete request + content: + application/json: + schema: + $ref: '#/components/schemas/PaymentRequiredResponse' + '404': + description: Not Found - Generation not found + content: + application/json: + schema: + $ref: '#/components/schemas/NotFoundResponse' + '429': + description: Too Many Requests - Rate limit exceeded + content: + application/json: + schema: + $ref: '#/components/schemas/TooManyRequestsResponse' + '500': + description: Internal Server Error - Unexpected server error + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerResponse' + '502': + description: Bad Gateway - Provider/upstream API failure + content: + application/json: + schema: + $ref: '#/components/schemas/BadGatewayResponse' + '524': + description: Infrastructure Timeout - Request timed out at our edge network + content: + application/json: + schema: + $ref: '#/components/schemas/EdgeNetworkTimeoutResponse' + '529': + description: Provider Overloaded - Provider is temporarily overloaded + content: + application/json: + schema: + $ref: '#/components/schemas/ProviderOverloadedResponse' + operationId: getGeneration + /models/count: + get: + tags: + - Models + x-speakeasy-name-override: count + summary: Get total count of available models + responses: + '200': + description: Returns the total count of available models + content: + application/json: + schema: + $ref: '#/components/schemas/ModelsCountResponse' + '500': + description: Internal Server Error + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerResponse' + operationId: listModelsCount + /models: + get: + tags: + - Models + x-speakeasy-name-override: list + summary: List all models and their properties + parameters: + - schema: + type: string + required: false + name: category + in: query + - schema: + type: string + required: false + name: supported_parameters + in: query + responses: + '200': + description: Returns a list of models or RSS feed + content: + application/json: + schema: + $ref: '#/components/schemas/ModelsListResponse' + '400': + description: Bad Request - Invalid request parameters + content: + application/json: + schema: + $ref: '#/components/schemas/BadRequestResponse' + '500': + description: Internal Server Error + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerResponse' + operationId: getModels + /models/user: + get: + tags: + - Models + x-speakeasy-name-override: listForUser + summary: List models filtered by user provider preferences + security: + - bearer: [] + responses: + '200': + description: Returns a list of models filtered by user provider preferences + content: + application/json: + schema: + $ref: '#/components/schemas/ModelsListResponse' + '401': + description: Unauthorized - Missing or invalid authentication + content: + application/json: + schema: + $ref: '#/components/schemas/UnauthorizedResponse' + '500': + description: Internal Server Error + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerResponse' + operationId: listModelsUser + /models/{author}/{slug}/endpoints: + get: + tags: + - Endpoints + operationId: listEndpoints + x-speakeasy-name-override: list + summary: List all endpoints for a model + parameters: + - schema: + type: string + required: true + name: author + in: path + - schema: + type: string + required: true + name: slug + in: path + responses: + '200': + description: Returns a list of endpoints + content: + application/json: + schema: + type: object + properties: + data: + $ref: '#/components/schemas/ListEndpointsResponse' + required: + - data + '404': + description: Not Found - Model does not exist + content: + application/json: + schema: + $ref: '#/components/schemas/NotFoundResponse' + '500': + description: Internal Server Error - Unexpected server error + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerResponse' + /endpoints/zdr: + get: + tags: + - Endpoints + x-speakeasy-name-override: listZdrEndpoints + summary: Preview the impact of ZDR on the available endpoints + responses: + '200': + description: Returns a list of endpoints + content: + application/json: + schema: + type: object + properties: + data: + type: array + items: + $ref: '#/components/schemas/PublicEndpoint' + required: + - data + '500': + description: Internal Server Error - Unexpected server error + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerResponse' + operationId: listEndpointsZdr + /parameters/{author}/{slug}: + get: + tags: + - Parameters + summary: Get a model's supported parameters and data about which are most popular + security: + - bearer: [] + parameters: + - schema: + type: string + required: true + name: author + in: path + - schema: + type: string + required: true + name: slug + in: path + - schema: + type: string + enum: + - AI21 + - AionLabs + - Alibaba + - Amazon Bedrock + - Anthropic + - AtlasCloud + - Atoma + - Avian + - Azure + - BaseTen + - Cerebras + - Chutes + - Cirrascale + - Clarifai + - Cloudflare + - Cohere + - CrofAI + - Crusoe + - DeepInfra + - DeepSeek + - Enfer + - Featherless + - Fireworks + - Friendli + - GMICloud + - Google + - Google AI Studio + - Groq + - Hyperbolic + - Inception + - InferenceNet + - Infermatic + - Inflection + - Kluster + - Lambda + - Liquid + - Mancer 2 + - Meta + - Minimax + - ModelRun + - Mistral + - Modular + - Moonshot AI + - Morph + - NCompass + - Nebius + - NextBit + - Nineteen + - Novita + - Nvidia + - OpenAI + - OpenInference + - Parasail + - Perplexity + - Phala + - Relace + - SambaNova + - SiliconFlow + - Stealth + - Switchpoint + - Targon + - Together + - Ubicloud + - Venice + - WandB + - xAI + - Z.AI + - FakeProvider + x-speakeasy-unknown-values: allow + required: false + name: provider + in: query + responses: + '200': + description: Returns the parameters for the specified model + content: + application/json: + schema: + type: object + properties: + data: + type: object + properties: + model: + type: string + description: Model identifier + example: openai/gpt-4 + supported_parameters: + type: array + items: + type: string + enum: + - temperature + - top_p + - top_k + - min_p + - top_a + - frequency_penalty + - presence_penalty + - repetition_penalty + - max_tokens + - logit_bias + - logprobs + - top_logprobs + - seed + - response_format + - structured_outputs + - stop + - tools + - tool_choice + - parallel_tool_calls + - include_reasoning + - reasoning + - web_search_options + - verbosity + x-speakeasy-unknown-values: allow + description: List of parameters supported by this model + example: + - temperature + - top_p + - max_tokens + required: + - model + - supported_parameters + example: + model: openai/gpt-4 + supported_parameters: + - temperature + - top_p + - max_tokens + description: Parameter analytics data + required: + - data + example: + data: + model: openai/gpt-4 + supported_parameters: + - temperature + - top_p + - max_tokens + '401': + description: Unauthorized - Authentication required or invalid credentials + content: + application/json: + schema: + $ref: '#/components/schemas/UnauthorizedResponse' + '404': + description: Not Found - Model or provider does not exist + content: + application/json: + schema: + $ref: '#/components/schemas/NotFoundResponse' + '500': + description: Internal Server Error - Unexpected server error + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerResponse' + operationId: getParameters + /providers: + get: + tags: + - Providers + x-speakeasy-name-override: list + summary: List all providers + operationId: listProviders + responses: + '200': + description: Returns a list of providers + content: + application/json: + schema: + type: object + properties: + data: + type: array + items: + type: object + properties: + name: + type: string + description: Display name of the provider + example: OpenAI + slug: + type: string + description: URL-friendly identifier for the provider + example: openai + privacy_policy_url: + type: string + nullable: true + description: URL to the provider's privacy policy + example: https://openai.com/privacy + terms_of_service_url: + type: string + nullable: true + description: URL to the provider's terms of service + example: https://openai.com/terms + status_page_url: + type: string + nullable: true + description: URL to the provider's status page + example: https://status.openai.com + required: + - name + - slug + - privacy_policy_url + example: + name: OpenAI + slug: openai + privacy_policy_url: https://openai.com/privacy + terms_of_service_url: https://openai.com/terms + status_page_url: https://status.openai.com + required: + - data + '500': + description: Internal Server Error - Unexpected server error + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerResponse' + /keys: + get: + operationId: list + x-speakeasy-name-override: list + tags: + - API Keys + summary: List API keys + parameters: + - schema: + type: string + description: Whether to include disabled API keys in the response + example: 'false' + required: false + description: Whether to include disabled API keys in the response + name: include_disabled + in: query + - schema: + type: string + description: Number of API keys to skip for pagination + example: '0' + required: false + description: Number of API keys to skip for pagination + name: offset + in: query + responses: + '200': + description: List of API keys + content: + application/json: + schema: + type: object + properties: + data: + type: array + items: + type: object + properties: + hash: + type: string + description: Unique hash identifier for the API key + example: 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 + name: + type: string + description: Name of the API key + example: My Production Key + label: + type: string + description: Human-readable label for the API key + example: Production API Key + disabled: + type: boolean + description: Whether the API key is disabled + example: false + limit: + type: number + nullable: true + description: Spending limit for the API key in USD + example: 100 + limit_remaining: + type: number + nullable: true + description: Remaining spending limit in USD + example: 74.5 + limit_reset: + type: string + nullable: true + description: Type of limit reset for the API key + example: monthly + include_byok_in_limit: + type: boolean + description: Whether to include external BYOK usage in the credit limit + example: false + usage: + type: number + description: Total OpenRouter credit usage (in USD) for the API key + example: 25.5 + usage_daily: + type: number + description: OpenRouter credit usage (in USD) for the current UTC day + example: 25.5 + usage_weekly: + type: number + description: OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday) + example: 25.5 + usage_monthly: + type: number + description: OpenRouter credit usage (in USD) for the current UTC month + example: 25.5 + byok_usage: + type: number + description: Total external BYOK usage (in USD) for the API key + example: 17.38 + byok_usage_daily: + type: number + description: External BYOK usage (in USD) for the current UTC day + example: 17.38 + byok_usage_weekly: + type: number + description: External BYOK usage (in USD) for the current UTC week (Monday-Sunday) + example: 17.38 + byok_usage_monthly: + type: number + description: External BYOK usage (in USD) for current UTC month + example: 17.38 + created_at: + type: string + description: ISO 8601 timestamp of when the API key was created + example: '2025-08-24T10:30:00Z' + updated_at: + type: string + nullable: true + description: ISO 8601 timestamp of when the API key was last updated + example: '2025-08-24T15:45:00Z' + expires_at: + type: string + nullable: true + format: date-time + description: ISO 8601 UTC timestamp when the API key expires, or null if no expiration + example: '2027-12-31T23:59:59Z' + required: + - hash + - name + - label + - disabled + - limit + - limit_remaining + - limit_reset + - include_byok_in_limit + - usage + - usage_daily + - usage_weekly + - usage_monthly + - byok_usage + - byok_usage_daily + - byok_usage_weekly + - byok_usage_monthly + - created_at + - updated_at + example: + hash: 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 + name: My Production Key + label: Production API Key + disabled: false + limit: 100 + limit_remaining: 74.5 + limit_reset: monthly + include_byok_in_limit: false + usage: 25.5 + usage_daily: 25.5 + usage_weekly: 25.5 + usage_monthly: 25.5 + byok_usage: 17.38 + byok_usage_daily: 17.38 + byok_usage_weekly: 17.38 + byok_usage_monthly: 17.38 + created_at: '2025-08-24T10:30:00Z' + updated_at: '2025-08-24T15:45:00Z' + expires_at: '2027-12-31T23:59:59Z' + description: List of API keys + required: + - data + example: + data: + - hash: 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 + name: My Production Key + label: Production API Key + disabled: false + limit: 100 + limit_remaining: 74.5 + limit_reset: monthly + include_byok_in_limit: false + usage: 25.5 + usage_daily: 25.5 + usage_weekly: 25.5 + usage_monthly: 25.5 + byok_usage: 17.38 + byok_usage_daily: 17.38 + byok_usage_weekly: 17.38 + byok_usage_monthly: 17.38 + created_at: '2025-08-24T10:30:00Z' + updated_at: '2025-08-24T15:45:00Z' + expires_at: '2027-12-31T23:59:59Z' + '401': + description: Unauthorized - Missing or invalid authentication + content: + application/json: + schema: + $ref: '#/components/schemas/UnauthorizedResponse' + '429': + description: Too Many Requests - Rate limit exceeded + content: + application/json: + schema: + $ref: '#/components/schemas/TooManyRequestsResponse' + '500': + description: Internal Server Error + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerResponse' + post: + x-speakeasy-name-override: create + tags: + - API Keys + summary: Create a new API key + requestBody: + content: + application/json: + schema: + type: object + properties: + name: + type: string + minLength: 1 + description: Name for the new API key + example: My New API Key + limit: + type: number + nullable: true + description: Optional spending limit for the API key in USD + example: 50 + limit_reset: + type: string + nullable: true + enum: + - daily + - weekly + - monthly + description: >- + Type of limit reset for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday. + example: monthly + x-speakeasy-unknown-values: allow + include_byok_in_limit: + type: boolean + description: Whether to include BYOK usage in the limit + example: true + expires_at: + type: string + nullable: true + format: date-time + description: >- + Optional ISO 8601 UTC timestamp when the API key should expire. Must be UTC, other timezones will be rejected + example: '2027-12-31T23:59:59Z' + required: + - name + example: + name: My New API Key + limit: 50 + limit_reset: monthly + include_byok_in_limit: true + expires_at: '2027-12-31T23:59:59Z' + required: true + responses: + '201': + description: API key created successfully + content: + application/json: + schema: + type: object + properties: + data: + type: object + properties: + hash: + type: string + description: Unique hash identifier for the API key + example: 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 + name: + type: string + description: Name of the API key + example: My Production Key + label: + type: string + description: Human-readable label for the API key + example: Production API Key + disabled: + type: boolean + description: Whether the API key is disabled + example: false + limit: + type: number + nullable: true + description: Spending limit for the API key in USD + example: 100 + limit_remaining: + type: number + nullable: true + description: Remaining spending limit in USD + example: 74.5 + limit_reset: + type: string + nullable: true + description: Type of limit reset for the API key + example: monthly + include_byok_in_limit: + type: boolean + description: Whether to include external BYOK usage in the credit limit + example: false + usage: + type: number + description: Total OpenRouter credit usage (in USD) for the API key + example: 25.5 + usage_daily: + type: number + description: OpenRouter credit usage (in USD) for the current UTC day + example: 25.5 + usage_weekly: + type: number + description: OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday) + example: 25.5 + usage_monthly: + type: number + description: OpenRouter credit usage (in USD) for the current UTC month + example: 25.5 + byok_usage: + type: number + description: Total external BYOK usage (in USD) for the API key + example: 17.38 + byok_usage_daily: + type: number + description: External BYOK usage (in USD) for the current UTC day + example: 17.38 + byok_usage_weekly: + type: number + description: External BYOK usage (in USD) for the current UTC week (Monday-Sunday) + example: 17.38 + byok_usage_monthly: + type: number + description: External BYOK usage (in USD) for current UTC month + example: 17.38 + created_at: + type: string + description: ISO 8601 timestamp of when the API key was created + example: '2025-08-24T10:30:00Z' + updated_at: + type: string + nullable: true + description: ISO 8601 timestamp of when the API key was last updated + example: '2025-08-24T15:45:00Z' + expires_at: + type: string + nullable: true + format: date-time + description: ISO 8601 UTC timestamp when the API key expires, or null if no expiration + example: '2027-12-31T23:59:59Z' + required: + - hash + - name + - label + - disabled + - limit + - limit_remaining + - limit_reset + - include_byok_in_limit + - usage + - usage_daily + - usage_weekly + - usage_monthly + - byok_usage + - byok_usage_daily + - byok_usage_weekly + - byok_usage_monthly + - created_at + - updated_at + example: + hash: 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 + name: My Production Key + label: Production API Key + disabled: false + limit: 100 + limit_remaining: 74.5 + limit_reset: monthly + include_byok_in_limit: false + usage: 25.5 + usage_daily: 25.5 + usage_weekly: 25.5 + usage_monthly: 25.5 + byok_usage: 17.38 + byok_usage_daily: 17.38 + byok_usage_weekly: 17.38 + byok_usage_monthly: 17.38 + created_at: '2025-08-24T10:30:00Z' + updated_at: '2025-08-24T15:45:00Z' + expires_at: '2027-12-31T23:59:59Z' + description: The created API key information + key: + type: string + description: The actual API key string (only shown once) + example: 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 + required: + - data + - key + example: + data: + hash: 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 + name: My New API Key + label: My New API Key + disabled: false + limit: 50 + limit_remaining: 50 + limit_reset: monthly + include_byok_in_limit: true + usage: 0 + usage_daily: 0 + usage_weekly: 0 + usage_monthly: 0 + byok_usage: 0 + byok_usage_daily: 0 + byok_usage_weekly: 0 + byok_usage_monthly: 0 + created_at: '2025-08-24T10:30:00Z' + updated_at: null + expires_at: '2027-12-31T23:59:59Z' + key: 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 + '400': + description: Bad Request - Invalid request parameters + content: + application/json: + schema: + $ref: '#/components/schemas/BadRequestResponse' + '401': + description: Unauthorized - Missing or invalid authentication + content: + application/json: + schema: + $ref: '#/components/schemas/UnauthorizedResponse' + '429': + description: Too Many Requests - Rate limit exceeded + content: + application/json: + schema: + $ref: '#/components/schemas/TooManyRequestsResponse' + '500': + description: Internal Server Error + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerResponse' + operationId: createKeys + /keys/{hash}: + patch: + x-speakeasy-name-override: update + tags: + - API Keys + summary: Update an API key + parameters: + - schema: + type: string + description: The hash identifier of the API key to update + example: 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 + required: true + description: The hash identifier of the API key to update + name: hash + in: path + requestBody: + content: + application/json: + schema: + type: object + properties: + name: + type: string + description: New name for the API key + example: Updated API Key Name + disabled: + type: boolean + description: Whether to disable the API key + example: false + limit: + type: number + nullable: true + description: New spending limit for the API key in USD + example: 75 + limit_reset: + type: string + nullable: true + enum: + - daily + - weekly + - monthly + description: >- + New limit reset type for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday. + example: daily + x-speakeasy-unknown-values: allow + include_byok_in_limit: + type: boolean + description: Whether to include BYOK usage in the limit + example: true + example: + name: Updated API Key Name + disabled: false + limit: 75 + limit_reset: daily + include_byok_in_limit: true + required: true + responses: + '200': + description: API key updated successfully + content: + application/json: + schema: + type: object + properties: + data: + type: object + properties: + hash: + type: string + description: Unique hash identifier for the API key + example: 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 + name: + type: string + description: Name of the API key + example: My Production Key + label: + type: string + description: Human-readable label for the API key + example: Production API Key + disabled: + type: boolean + description: Whether the API key is disabled + example: false + limit: + type: number + nullable: true + description: Spending limit for the API key in USD + example: 100 + limit_remaining: + type: number + nullable: true + description: Remaining spending limit in USD + example: 74.5 + limit_reset: + type: string + nullable: true + description: Type of limit reset for the API key + example: monthly + include_byok_in_limit: + type: boolean + description: Whether to include external BYOK usage in the credit limit + example: false + usage: + type: number + description: Total OpenRouter credit usage (in USD) for the API key + example: 25.5 + usage_daily: + type: number + description: OpenRouter credit usage (in USD) for the current UTC day + example: 25.5 + usage_weekly: + type: number + description: OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday) + example: 25.5 + usage_monthly: + type: number + description: OpenRouter credit usage (in USD) for the current UTC month + example: 25.5 + byok_usage: + type: number + description: Total external BYOK usage (in USD) for the API key + example: 17.38 + byok_usage_daily: + type: number + description: External BYOK usage (in USD) for the current UTC day + example: 17.38 + byok_usage_weekly: + type: number + description: External BYOK usage (in USD) for the current UTC week (Monday-Sunday) + example: 17.38 + byok_usage_monthly: + type: number + description: External BYOK usage (in USD) for current UTC month + example: 17.38 + created_at: + type: string + description: ISO 8601 timestamp of when the API key was created + example: '2025-08-24T10:30:00Z' + updated_at: + type: string + nullable: true + description: ISO 8601 timestamp of when the API key was last updated + example: '2025-08-24T15:45:00Z' + expires_at: + type: string + nullable: true + format: date-time + description: ISO 8601 UTC timestamp when the API key expires, or null if no expiration + example: '2027-12-31T23:59:59Z' + required: + - hash + - name + - label + - disabled + - limit + - limit_remaining + - limit_reset + - include_byok_in_limit + - usage + - usage_daily + - usage_weekly + - usage_monthly + - byok_usage + - byok_usage_daily + - byok_usage_weekly + - byok_usage_monthly + - created_at + - updated_at + example: + hash: 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 + name: My Production Key + label: Production API Key + disabled: false + limit: 100 + limit_remaining: 74.5 + limit_reset: monthly + include_byok_in_limit: false + usage: 25.5 + usage_daily: 25.5 + usage_weekly: 25.5 + usage_monthly: 25.5 + byok_usage: 17.38 + byok_usage_daily: 17.38 + byok_usage_weekly: 17.38 + byok_usage_monthly: 17.38 + created_at: '2025-08-24T10:30:00Z' + updated_at: '2025-08-24T15:45:00Z' + expires_at: '2027-12-31T23:59:59Z' + description: The updated API key information + required: + - data + example: + data: + hash: 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 + name: Updated API Key Name + label: Updated API Key Name + disabled: false + limit: 75 + limit_remaining: 49.5 + limit_reset: daily + include_byok_in_limit: true + usage: 25.5 + usage_daily: 25.5 + usage_weekly: 25.5 + usage_monthly: 25.5 + byok_usage: 17.38 + byok_usage_daily: 17.38 + byok_usage_weekly: 17.38 + byok_usage_monthly: 17.38 + created_at: '2025-08-24T10:30:00Z' + updated_at: '2025-08-24T16:00:00Z' + expires_at: null + '400': + description: Bad Request - Invalid request parameters + content: + application/json: + schema: + $ref: '#/components/schemas/BadRequestResponse' + '401': + description: Unauthorized - Missing or invalid authentication + content: + application/json: + schema: + $ref: '#/components/schemas/UnauthorizedResponse' + '404': + description: Not Found - API key does not exist + content: + application/json: + schema: + $ref: '#/components/schemas/NotFoundResponse' + '429': + description: Too Many Requests - Rate limit exceeded + content: + application/json: + schema: + $ref: '#/components/schemas/TooManyRequestsResponse' + '500': + description: Internal Server Error + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerResponse' + operationId: updateKeys + delete: + x-speakeasy-name-override: delete + tags: + - API Keys + summary: Delete an API key + parameters: + - schema: + type: string + description: The hash identifier of the API key to delete + example: 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 + required: true + description: The hash identifier of the API key to delete + name: hash + in: path + responses: + '200': + description: API key deleted successfully + content: + application/json: + schema: + type: object + properties: + deleted: + type: boolean + const: true + description: Confirmation that the API key was deleted + example: true + required: + - deleted + example: + deleted: true + '401': + description: Unauthorized - Missing or invalid authentication + content: + application/json: + schema: + $ref: '#/components/schemas/UnauthorizedResponse' + '404': + description: Not Found - API key does not exist + content: + application/json: + schema: + $ref: '#/components/schemas/NotFoundResponse' + '429': + description: Too Many Requests - Rate limit exceeded + content: + application/json: + schema: + $ref: '#/components/schemas/TooManyRequestsResponse' + '500': + description: Internal Server Error + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerResponse' + operationId: deleteKeys + get: + operationId: getKey + x-speakeasy-name-override: get + tags: + - API Keys + summary: Get a single API key + parameters: + - schema: + type: string + description: The hash identifier of the API key to retrieve + example: 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 + required: true + description: The hash identifier of the API key to retrieve + name: hash + in: path + responses: + '200': + description: API key details + content: + application/json: + schema: + type: object + properties: + data: + type: object + properties: + hash: + type: string + description: Unique hash identifier for the API key + example: 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 + name: + type: string + description: Name of the API key + example: My Production Key + label: + type: string + description: Human-readable label for the API key + example: Production API Key + disabled: + type: boolean + description: Whether the API key is disabled + example: false + limit: + type: number + nullable: true + description: Spending limit for the API key in USD + example: 100 + limit_remaining: + type: number + nullable: true + description: Remaining spending limit in USD + example: 74.5 + limit_reset: + type: string + nullable: true + description: Type of limit reset for the API key + example: monthly + include_byok_in_limit: + type: boolean + description: Whether to include external BYOK usage in the credit limit + example: false + usage: + type: number + description: Total OpenRouter credit usage (in USD) for the API key + example: 25.5 + usage_daily: + type: number + description: OpenRouter credit usage (in USD) for the current UTC day + example: 25.5 + usage_weekly: + type: number + description: OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday) + example: 25.5 + usage_monthly: + type: number + description: OpenRouter credit usage (in USD) for the current UTC month + example: 25.5 + byok_usage: + type: number + description: Total external BYOK usage (in USD) for the API key + example: 17.38 + byok_usage_daily: + type: number + description: External BYOK usage (in USD) for the current UTC day + example: 17.38 + byok_usage_weekly: + type: number + description: External BYOK usage (in USD) for the current UTC week (Monday-Sunday) + example: 17.38 + byok_usage_monthly: + type: number + description: External BYOK usage (in USD) for current UTC month + example: 17.38 + created_at: + type: string + description: ISO 8601 timestamp of when the API key was created + example: '2025-08-24T10:30:00Z' + updated_at: + type: string + nullable: true + description: ISO 8601 timestamp of when the API key was last updated + example: '2025-08-24T15:45:00Z' + expires_at: + type: string + nullable: true + format: date-time + description: ISO 8601 UTC timestamp when the API key expires, or null if no expiration + example: '2027-12-31T23:59:59Z' + required: + - hash + - name + - label + - disabled + - limit + - limit_remaining + - limit_reset + - include_byok_in_limit + - usage + - usage_daily + - usage_weekly + - usage_monthly + - byok_usage + - byok_usage_daily + - byok_usage_weekly + - byok_usage_monthly + - created_at + - updated_at + example: + hash: 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 + name: My Production Key + label: Production API Key + disabled: false + limit: 100 + limit_remaining: 74.5 + limit_reset: monthly + include_byok_in_limit: false + usage: 25.5 + usage_daily: 25.5 + usage_weekly: 25.5 + usage_monthly: 25.5 + byok_usage: 17.38 + byok_usage_daily: 17.38 + byok_usage_weekly: 17.38 + byok_usage_monthly: 17.38 + created_at: '2025-08-24T10:30:00Z' + updated_at: '2025-08-24T15:45:00Z' + expires_at: '2027-12-31T23:59:59Z' + description: The API key information + required: + - data + example: + data: + hash: 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 + name: My Production Key + label: Production API Key + disabled: false + limit: 100 + limit_remaining: 74.5 + limit_reset: monthly + include_byok_in_limit: false + usage: 25.5 + usage_daily: 25.5 + usage_weekly: 25.5 + usage_monthly: 25.5 + byok_usage: 17.38 + byok_usage_daily: 17.38 + byok_usage_weekly: 17.38 + byok_usage_monthly: 17.38 + created_at: '2025-08-24T10:30:00Z' + updated_at: '2025-08-24T15:45:00Z' + expires_at: '2027-12-31T23:59:59Z' + '401': + description: Unauthorized - Missing or invalid authentication + content: + application/json: + schema: + $ref: '#/components/schemas/UnauthorizedResponse' + '404': + description: Not Found - API key does not exist + content: + application/json: + schema: + $ref: '#/components/schemas/NotFoundResponse' + '429': + description: Too Many Requests - Rate limit exceeded + content: + application/json: + schema: + $ref: '#/components/schemas/TooManyRequestsResponse' + '500': + description: Internal Server Error + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerResponse' + /key: + get: + operationId: getCurrentKey + x-speakeasy-name-override: getCurrentKeyMetadata + tags: + - API Keys + summary: Get current API key + description: Get information on the API key associated with the current authentication session + responses: + '200': + description: API key details + content: + application/json: + schema: + type: object + properties: + data: + type: object + properties: + label: + type: string + description: Human-readable label for the API key + example: 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 + limit: + type: number + nullable: true + description: Spending limit for the API key in USD + example: 100 + usage: + type: number + description: Total OpenRouter credit usage (in USD) for the API key + example: 25.5 + usage_daily: + type: number + description: OpenRouter credit usage (in USD) for the current UTC day + example: 25.5 + usage_weekly: + type: number + description: OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday) + example: 25.5 + usage_monthly: + type: number + description: OpenRouter credit usage (in USD) for the current UTC month + example: 25.5 + byok_usage: + type: number + description: Total external BYOK usage (in USD) for the API key + example: 17.38 + byok_usage_daily: + type: number + description: External BYOK usage (in USD) for the current UTC day + example: 17.38 + byok_usage_weekly: + type: number + description: External BYOK usage (in USD) for the current UTC week (Monday-Sunday) + example: 17.38 + byok_usage_monthly: + type: number + description: External BYOK usage (in USD) for current UTC month + example: 17.38 + is_free_tier: + type: boolean + description: Whether this is a free tier API key + example: false + is_provisioning_key: + type: boolean + description: Whether this is a provisioning key + example: false + limit_remaining: + type: number + nullable: true + description: Remaining spending limit in USD + example: 74.5 + limit_reset: + type: string + nullable: true + description: Type of limit reset for the API key + example: monthly + include_byok_in_limit: + type: boolean + description: Whether to include external BYOK usage in the credit limit + example: false + expires_at: + type: string + nullable: true + format: date-time + description: ISO 8601 UTC timestamp when the API key expires, or null if no expiration + example: '2027-12-31T23:59:59Z' + rate_limit: + type: object + properties: + requests: + type: number + description: Number of requests allowed per interval + example: 1000 + interval: + type: string + description: Rate limit interval + example: 1h + note: + type: string + description: Note about the rate limit + example: This field is deprecated and safe to ignore. + required: + - requests + - interval + - note + description: Legacy rate limit information about a key. Will always return -1. + deprecated: true + example: + requests: 1000 + interval: 1h + note: This field is deprecated and safe to ignore. + required: + - label + - limit + - usage + - usage_daily + - usage_weekly + - usage_monthly + - byok_usage + - byok_usage_daily + - byok_usage_weekly + - byok_usage_monthly + - is_free_tier + - is_provisioning_key + - limit_remaining + - limit_reset + - include_byok_in_limit + - rate_limit + description: Current API key information + example: + label: sk-or-v1-au78b3456789012345678901234567890 + limit: 100 + usage: 25.5 + usage_daily: 25.5 + usage_weekly: 25.5 + usage_monthly: 25.5 + byok_usage: 17.38 + byok_usage_daily: 17.38 + byok_usage_weekly: 17.38 + byok_usage_monthly: 17.38 + is_free_tier: false + is_provisioning_key: false + limit_remaining: 74.5 + limit_reset: monthly + include_byok_in_limit: false + expires_at: '2027-12-31T23:59:59Z' + rate_limit: + requests: 1000 + interval: 1h + note: This field is deprecated and safe to ignore. + required: + - data + example: + data: + label: sk-or-v1-au78b3456789012345678901234567890 + limit: 100 + usage: 25.5 + usage_daily: 25.5 + usage_weekly: 25.5 + usage_monthly: 25.5 + byok_usage: 17.38 + byok_usage_daily: 17.38 + byok_usage_weekly: 17.38 + byok_usage_monthly: 17.38 + is_free_tier: false + is_provisioning_key: false + limit_remaining: 74.5 + limit_reset: monthly + include_byok_in_limit: false + expires_at: '2027-12-31T23:59:59Z' + rate_limit: + requests: 1000 + interval: 1h + note: This field is deprecated and safe to ignore. + '401': + description: Unauthorized - Authentication required or invalid credentials + content: + application/json: + schema: + $ref: '#/components/schemas/UnauthorizedResponse' + '500': + description: Internal Server Error - Unexpected server error + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerResponse' + /auth/keys: + post: + operationId: exchangeAuthCodeForAPIKey + tags: + - OAuth + summary: Exchange authorization code for API key + description: Exchange an authorization code from the PKCE flow for a user-controlled API key + requestBody: + content: + application/json: + schema: + type: object + properties: + code: + type: string + description: The authorization code received from the OAuth redirect + example: auth_code_abc123def456 + code_verifier: + type: string + description: The code verifier if code_challenge was used in the authorization request + example: dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk + code_challenge_method: + type: string + nullable: true + enum: + - S256 + - plain + description: The method used to generate the code challenge + example: S256 + x-speakeasy-unknown-values: allow + required: + - code + example: + code: auth_code_abc123def456 + code_verifier: dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk + code_challenge_method: S256 + required: true + responses: + '200': + description: Successfully exchanged code for an API key + content: + application/json: + schema: + type: object + properties: + key: + type: string + description: The API key to use for OpenRouter requests + example: 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 + user_id: + type: string + nullable: true + description: User ID associated with the API key + example: user_2yOPcMpKoQhcd4bVgSMlELRaIah + required: + - key + - user_id + example: + key: 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 + user_id: user_2yOPcMpKoQhcd4bVgSMlELRaIah + '400': + description: Bad Request - Invalid request parameters or malformed input + content: + application/json: + schema: + $ref: '#/components/schemas/BadRequestResponse' + '403': + description: Forbidden - Authentication successful but insufficient permissions + content: + application/json: + schema: + $ref: '#/components/schemas/ForbiddenResponse' + '500': + description: Internal Server Error - Unexpected server error + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerResponse' + /auth/keys/code: + post: + x-speakeasy-name-override: createAuthCode + tags: + - OAuth + summary: Create authorization code + description: Create an authorization code for the PKCE flow to generate a user-controlled API key + requestBody: + content: + application/json: + schema: + type: object + properties: + callback_url: + type: string + format: uri + description: >- + The callback URL to redirect to after authorization. Note, only https URLs on ports 443 and 3000 are allowed. + example: https://myapp.com/auth/callback + code_challenge: + type: string + description: PKCE code challenge for enhanced security + example: E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM + code_challenge_method: + type: string + enum: + - S256 + - plain + description: The method used to generate the code challenge + example: S256 + x-speakeasy-unknown-values: allow + limit: + type: number + description: Credit limit for the API key to be created + example: 100 + expires_at: + type: string + nullable: true + format: date-time + description: Optional expiration time for the API key to be created + required: + - callback_url + example: + callback_url: https://myapp.com/auth/callback + code_challenge: E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM + code_challenge_method: S256 + limit: 100 + required: true + responses: + '200': + description: Successfully created authorization code + content: + application/json: + schema: + type: object + properties: + data: + type: object + properties: + id: + type: string + description: The authorization code ID to use in the exchange request + example: auth_code_xyz789 + app_id: + type: number + description: The application ID associated with this auth code + example: 12345 + created_at: + type: string + description: ISO 8601 timestamp of when the auth code was created + example: '2025-08-24T10:30:00Z' + required: + - id + - app_id + - created_at + description: Auth code data + example: + id: auth_code_xyz789 + app_id: 12345 + created_at: '2025-08-24T10:30:00Z' + required: + - data + '400': + description: Bad Request - Invalid request parameters or malformed input + content: + application/json: + schema: + $ref: '#/components/schemas/BadRequestResponse' + '401': + description: Unauthorized - Authentication required or invalid credentials + content: + application/json: + schema: + $ref: '#/components/schemas/UnauthorizedResponse' + '500': + description: Internal Server Error - Unexpected server error + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerResponse' + operationId: createAuthKeysCode + /chat/completions: + post: + summary: Create a chat completion + operationId: sendChatCompletionRequest + x-speakeasy-group: chat + x-speakeasy-name-override: send + x-speakeasy-stream-request-field: stream + description: >- + Sends a request for a model response for the given chat conversation. Supports both streaming and non-streaming modes. + tags: + - Chat + requestBody: + required: true + description: Chat completion request parameters + content: + application/json: + schema: + $ref: '#/components/schemas/ChatGenerationParams' + responses: + '200': + description: Successful chat completion response + content: + application/json: + schema: + $ref: '#/components/schemas/ChatResponse' + description: Chat completion response + text/event-stream: + x-speakeasy-sse-sentinel: '[DONE]' + schema: + $ref: '#/components/schemas/ChatStreamingResponseChunk' + '400': + description: Bad request - invalid parameters + content: + application/json: + schema: + $ref: '#/components/schemas/ChatError' + '401': + description: Unauthorized - invalid API key + content: + application/json: + schema: + $ref: '#/components/schemas/ChatError' + '429': + description: Too many requests - rate limit exceeded + content: + application/json: + schema: + $ref: '#/components/schemas/ChatError' + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ChatError' + /completions: + post: + summary: Create a completion + x-speakeasy-group: completions + x-speakeasy-name-override: generate + x-speakeasy-stream-request-field: stream + description: Creates a completion for the provided prompt and parameters. Supports both streaming and non-streaming modes. + tags: + - Completions + requestBody: + required: true + description: Completion request parameters + content: + application/json: + schema: + $ref: '#/components/schemas/CompletionCreateParams' + responses: + '200': + description: Successful completion response + content: + application/json: + schema: + $ref: '#/components/schemas/CompletionResponse' + description: Completion response + '400': + description: Bad request - invalid parameters + content: + application/json: + schema: + $ref: '#/components/schemas/ChatError' + '401': + description: Unauthorized - invalid API key + content: + application/json: + schema: + $ref: '#/components/schemas/ChatError' + '429': + description: Too many requests - rate limit exceeded + content: + application/json: + schema: + $ref: '#/components/schemas/ChatError' + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ChatError' + operationId: createCompletions +servers: + - url: https://openrouter.ai/api/v1 + description: Production server + x-speakeasy-server-id: production +security: + - apiKey: [] +externalDocs: + description: OpenRouter Documentation + url: https://openrouter.ai/docs +tags: + - name: API Keys + description: API key management endpoints + - name: Analytics + description: Analytics and usage endpoints + - name: Chat + description: Chat completion endpoints + - name: Completions + description: Text completion endpoints + - name: Credits + description: Credit management endpoints + - name: Embeddings + description: Text embedding endpoints + - name: Endpoints + description: Endpoint information + - name: Generations + description: Generation history endpoints + - name: Models + description: Model information endpoints + - name: OAuth + description: OAuth authentication endpoints + - name: Parameters + description: Parameters endpoints + - name: Providers + description: Provider information endpoints + - name: beta.responses + description: beta.responses endpoints +x-fern-base-path: / +x-retry-strategy: + type: exponential + initialDelay: 500 + maxDelay: 60000 + maxAttempts: 3 diff --git a/.speakeasy/workflow.lock b/.speakeasy/workflow.lock new file mode 100644 index 0000000..f566598 --- /dev/null +++ b/.speakeasy/workflow.lock @@ -0,0 +1,34 @@ +speakeasyVersion: 1.656.2 +sources: + -OAS: + sourceNamespace: open-router-chat-completions-api + sourceRevisionDigest: sha256:08647b466c00989914e3a2436175152270f771f0a57d055f5bab14cc2d4be89e + sourceBlobDigest: sha256:53027ec57392d9617cc001ece83c2fe1aa6e5dbfd52d170381c34c33c6042c23 + tags: + - latest +targets: + open-router: + source: -OAS + sourceNamespace: open-router-chat-completions-api + sourceRevisionDigest: sha256:08647b466c00989914e3a2436175152270f771f0a57d055f5bab14cc2d4be89e + sourceBlobDigest: sha256:53027ec57392d9617cc001ece83c2fe1aa6e5dbfd52d170381c34c33c6042c23 +workflow: + workflowVersion: 1.0.0 + speakeasyVersion: latest + sources: + -OAS: + inputs: + - location: registry.speakeasyapi.dev/openrouter/sdk/open-router-chat-completions-api:main + output: .speakeasy/out.openapi.yaml + registry: + location: registry.speakeasyapi.dev/openrouter/sdk/-oas + targets: + open-router: + target: python + source: -OAS + codeSamples: + registry: + location: registry.speakeasyapi.dev/openrouter/sdk/-oas-python-code-samples + labelOverride: + fixedValue: Python (SDK) + blocking: false diff --git a/.speakeasy/workflow.yaml b/.speakeasy/workflow.yaml new file mode 100644 index 0000000..9cc9dac --- /dev/null +++ b/.speakeasy/workflow.yaml @@ -0,0 +1,19 @@ +workflowVersion: 1.0.0 +speakeasyVersion: latest +sources: + -OAS: + inputs: + - location: registry.speakeasyapi.dev/openrouter/sdk/open-router-chat-completions-api:main + output: .speakeasy/out.openapi.yaml + registry: + location: registry.speakeasyapi.dev/openrouter/sdk/-oas +targets: + open-router: + target: python + source: -OAS + codeSamples: + registry: + location: registry.speakeasyapi.dev/openrouter/sdk/-oas-python-code-samples + labelOverride: + fixedValue: Python (SDK) + blocking: false diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..8d79f0a --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,6 @@ +{ + "python.testing.pytestArgs": ["tests", "-vv"], + "python.testing.unittestEnabled": false, + "python.testing.pytestEnabled": true, + "pylint.args": ["--rcfile=pylintrc"] +} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..d585717 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,26 @@ +# Contributing to This Repository + +Thank you for your interest in contributing to this repository. Please note that this repository contains generated code. As such, we do not accept direct changes or pull requests. Instead, we encourage you to follow the guidelines below to report issues and suggest improvements. + +## How to Report Issues + +If you encounter any bugs or have suggestions for improvements, please open an issue on GitHub. When reporting an issue, please provide as much detail as possible to help us reproduce the problem. This includes: + +- A clear and descriptive title +- Steps to reproduce the issue +- Expected and actual behavior +- Any relevant logs, screenshots, or error messages +- Information about your environment (e.g., operating system, software versions) + - For example can be collected using the `npx envinfo` command from your terminal if you have Node.js installed + +## Issue Triage and Upstream Fixes + +We will review and triage issues as quickly as possible. Our goal is to address bugs and incorporate improvements in the upstream source code. Fixes will be included in the next generation of the generated code. + +## Contact + +If you have any questions or need further assistance, please feel free to reach out by opening an issue. + +Thank you for your understanding and cooperation! + +The Maintainers diff --git a/README.md b/README.md new file mode 100644 index 0000000..cdef504 --- /dev/null +++ b/README.md @@ -0,0 +1,1251 @@ +# openrouter + +Developer-friendly & type-safe Python SDK specifically catered to leverage *openrouter* API. + + + + +

+> [!IMPORTANT] +> This SDK is not yet ready for production use. To complete setup please follow the steps outlined in your [workspace](https://app.speakeasy.com/org/openrouter/sdk). Delete this section before > publishing to a package manager. + + +## Summary + +OpenRouter API: OpenAI-compatible Chat Completions and Completions API with additional OpenRouter features + +For more information about the API: [OpenRouter Documentation](https://openrouter.ai/docs) + + + +## Table of Contents + +* [openrouter](#openrouter) + * [SDK Installation](#sdk-installation) + * [IDE Support](#ide-support) + * [SDK Example Usage](#sdk-example-usage) + * [Authentication](#authentication) + * [Available Resources and Operations](#available-resources-and-operations) + * [Server-sent event streaming](#server-sent-event-streaming) + * [Retries](#retries) + * [Error Handling](#error-handling) + * [Server Selection](#server-selection) + * [Custom HTTP Client](#custom-http-client) + * [Resource Management](#resource-management) + * [Debugging](#debugging) +* [Development](#development) + * [Maturity](#maturity) + * [Contributions](#contributions) + + + + +## SDK Installation + +> [!TIP] +> To finish publishing your SDK to PyPI you must [run your first generation action](https://www.speakeasy.com/docs/github-setup#step-by-step-guide). + + +> [!NOTE] +> **Python version upgrade policy** +> +> Once a Python version reaches its [official end of life date](https://devguide.python.org/versions/), a 3-month grace period is provided for users to upgrade. Following this grace period, the minimum python version supported in the SDK will be updated. + +The SDK can be installed with *uv*, *pip*, or *poetry* package managers. + +### uv + +*uv* is a fast Python package installer and resolver, designed as a drop-in replacement for pip and pip-tools. It's recommended for its speed and modern Python tooling capabilities. + +```bash +uv add git+.git +``` + +### PIP + +*PIP* is the default package installer for Python, enabling easy installation and management of packages from PyPI via the command line. + +```bash +pip install git+.git +``` + +### Poetry + +*Poetry* is a modern tool that simplifies dependency management and package publishing by using a single `pyproject.toml` file to handle project metadata and dependencies. + +```bash +poetry add git+.git +``` + +### Shell and script usage with `uv` + +You can use this SDK in a Python shell with [uv](https://docs.astral.sh/uv/) and the `uvx` command that comes with it like so: + +```shell +uvx --from openrouter python +``` + +It's also possible to write a standalone Python script without needing to set up a whole project like so: + +```python +#!/usr/bin/env -S uv run --script +# /// script +# requires-python = ">=3.9" +# dependencies = [ +# "openrouter", +# ] +# /// + +from openrouter import OpenRouter + +sdk = OpenRouter( + # SDK arguments +) + +# Rest of script here... +``` + +Once that is saved to a file, you can run it with `uv run script.py` where +`script.py` can be replaced with the actual file name. + + + +## IDE Support + +### PyCharm + +Generally, the SDK will work well with most IDEs out of the box. However, when using PyCharm, you can enjoy much better integration with Pydantic by installing an additional plugin. + +- [PyCharm Pydantic Plugin](https://docs.pydantic.dev/latest/integrations/pycharm/) + + + +## SDK Example Usage + +### Example + +```python +# Synchronous Example +from openrouter import OpenRouter +import os + + +with OpenRouter( + api_key=os.getenv("OPENROUTER_API_KEY", ""), +) as open_router: + + res = open_router.beta.responses.send(input=[ + { + "type": "message", + "role": "user", + "content": "Hello, how are you?", + }, + ], metadata={ + "user_id": "123", + "session_id": "abc-def-ghi", + }, tools=[ + { + "type": "function", + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + }, + }, + }, + }, + ], model="anthropic/claude-4.5-sonnet-20250929", text={ + "format_": { + "type": "text", + }, + "verbosity": "medium", + }, reasoning={ + "summary": "auto", + "enabled": True, + }, temperature=0.7, top_p=0.9, prompt={ + "id": "", + "variables": { + "key": { + "type": "input_text", + "text": "Hello, how can I help you?", + }, + }, + }, service_tier="auto", truncation="auto", stream=False, provider={ + "data_collection": "deny", + "zdr": True, + "enforce_distillable_text": True, + "order": [ + "OpenAI", + ], + "only": [ + "OpenAI", + ], + "ignore": [ + "OpenAI", + ], + "quantizations": None, + "sort": "price", + }) + + with res as event_stream: + for event in event_stream: + # handle event + print(event, flush=True) +``` + +
+ +The same SDK client can also be used to make asynchronous requests by importing asyncio. + +```python +# Asynchronous Example +import asyncio +from openrouter import OpenRouter +import os + +async def main(): + + async with OpenRouter( + api_key=os.getenv("OPENROUTER_API_KEY", ""), + ) as open_router: + + res = await open_router.beta.responses.send_async(input=[ + { + "type": "message", + "role": "user", + "content": "Hello, how are you?", + }, + ], metadata={ + "user_id": "123", + "session_id": "abc-def-ghi", + }, tools=[ + { + "type": "function", + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + }, + }, + }, + }, + ], model="anthropic/claude-4.5-sonnet-20250929", text={ + "format_": { + "type": "text", + }, + "verbosity": "medium", + }, reasoning={ + "summary": "auto", + "enabled": True, + }, temperature=0.7, top_p=0.9, prompt={ + "id": "", + "variables": { + "key": { + "type": "input_text", + "text": "Hello, how can I help you?", + }, + }, + }, service_tier="auto", truncation="auto", stream=False, provider={ + "data_collection": "deny", + "zdr": True, + "enforce_distillable_text": True, + "order": [ + "OpenAI", + ], + "only": [ + "OpenAI", + ], + "ignore": [ + "OpenAI", + ], + "quantizations": None, + "sort": "price", + }) + + async with res as event_stream: + async for event in event_stream: + # handle event + print(event, flush=True) + +asyncio.run(main()) +``` + + + +## Authentication + +### Per-Client Security Schemes + +This SDK supports the following security scheme globally: + +| Name | Type | Scheme | Environment Variable | +| --------- | ---- | ----------- | -------------------- | +| `api_key` | http | HTTP Bearer | `OPENROUTER_API_KEY` | + +To authenticate with the API the `api_key` parameter must be set when initializing the SDK client instance. For example: +```python +from openrouter import OpenRouter +import os + + +with OpenRouter( + api_key=os.getenv("OPENROUTER_API_KEY", ""), +) as open_router: + + res = open_router.beta.responses.send(input=[ + { + "type": "message", + "role": "user", + "content": "Hello, how are you?", + }, + ], metadata={ + "user_id": "123", + "session_id": "abc-def-ghi", + }, tools=[ + { + "type": "function", + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + }, + }, + }, + }, + ], model="anthropic/claude-4.5-sonnet-20250929", text={ + "format_": { + "type": "text", + }, + "verbosity": "medium", + }, reasoning={ + "summary": "auto", + "enabled": True, + }, temperature=0.7, top_p=0.9, prompt={ + "id": "", + "variables": { + "key": { + "type": "input_text", + "text": "Hello, how can I help you?", + }, + }, + }, service_tier="auto", truncation="auto", stream=False, provider={ + "data_collection": "deny", + "zdr": True, + "enforce_distillable_text": True, + "order": [ + "OpenAI", + ], + "only": [ + "OpenAI", + ], + "ignore": [ + "OpenAI", + ], + "quantizations": None, + "sort": "price", + }) + + with res as event_stream: + for event in event_stream: + # handle event + print(event, flush=True) + +``` + +### Per-Operation Security Schemes + +Some operations in this SDK require the security scheme to be specified at the request level. For example: +```python +from openrouter import OpenRouter, models +import os + + +with OpenRouter() as open_router: + + res = open_router.credits.create_coinbase_charge(security=models.CreateCoinbaseChargeSecurity( + bearer=os.getenv("OPENROUTER_BEARER", ""), + ), amount=100, sender="0x1234567890123456789012345678901234567890", chain_id=1) + + # Handle response + print(res) + +``` + + + +## Available Resources and Operations + +
+Available methods + +### [analytics](docs/sdks/analytics/README.md) + +* [get_user_activity](docs/sdks/analytics/README.md#get_user_activity) - Get user activity grouped by endpoint + +### [api_keys](docs/sdks/apikeys/README.md) + +* [list](docs/sdks/apikeys/README.md#list) - List API keys +* [create](docs/sdks/apikeys/README.md#create) - Create a new API key +* [update](docs/sdks/apikeys/README.md#update) - Update an API key +* [delete](docs/sdks/apikeys/README.md#delete) - Delete an API key +* [get](docs/sdks/apikeys/README.md#get) - Get a single API key +* [get_current_key_metadata](docs/sdks/apikeys/README.md#get_current_key_metadata) - Get current API key + +#### [beta.responses](docs/sdks/responses/README.md) + +* [send](docs/sdks/responses/README.md#send) - Create a response + +### [chat](docs/sdks/chat/README.md) + +* [send](docs/sdks/chat/README.md#send) - Create a chat completion + +### [completions](docs/sdks/completions/README.md) + +* [generate](docs/sdks/completions/README.md#generate) - Create a completion + +### [credits](docs/sdks/credits/README.md) + +* [get_credits](docs/sdks/credits/README.md#get_credits) - Get remaining credits +* [create_coinbase_charge](docs/sdks/credits/README.md#create_coinbase_charge) - Create a Coinbase charge for crypto payment + +### [embeddings](docs/sdks/embeddings/README.md) + +* [generate](docs/sdks/embeddings/README.md#generate) - Submit an embedding request +* [list_models](docs/sdks/embeddings/README.md#list_models) - List all embeddings models + +### [endpoints](docs/sdks/endpoints/README.md) + +* [list](docs/sdks/endpoints/README.md#list) - List all endpoints for a model +* [list_zdr_endpoints](docs/sdks/endpoints/README.md#list_zdr_endpoints) - Preview the impact of ZDR on the available endpoints + +### [generations](docs/sdks/generations/README.md) + +* [get_generation](docs/sdks/generations/README.md#get_generation) - Get request & usage metadata for a generation + +### [models](docs/sdks/models/README.md) + +* [count](docs/sdks/models/README.md#count) - Get total count of available models +* [list](docs/sdks/models/README.md#list) - List all models and their properties +* [list_for_user](docs/sdks/models/README.md#list_for_user) - List models filtered by user provider preferences + +### [o_auth](docs/sdks/oauth/README.md) + +* [exchange_auth_code_for_api_key](docs/sdks/oauth/README.md#exchange_auth_code_for_api_key) - Exchange authorization code for API key +* [create_auth_code](docs/sdks/oauth/README.md#create_auth_code) - Create authorization code + +### [parameters](docs/sdks/parameters/README.md) + +* [get_parameters](docs/sdks/parameters/README.md#get_parameters) - Get a model's supported parameters and data about which are most popular + +### [providers](docs/sdks/providers/README.md) + +* [list](docs/sdks/providers/README.md#list) - List all providers + +
+ + + +## Server-sent event streaming + +[Server-sent events][mdn-sse] are used to stream content from certain +operations. These operations will expose the stream as [Generator][generator] that +can be consumed using a simple `for` loop. The loop will +terminate when the server no longer has any events to send and closes the +underlying connection. + +The stream is also a [Context Manager][context-manager] and can be used with the `with` statement and will close the +underlying connection when the context is exited. + +```python +from openrouter import OpenRouter +import os + + +with OpenRouter( + api_key=os.getenv("OPENROUTER_API_KEY", ""), +) as open_router: + + res = open_router.beta.responses.send(input=[ + { + "type": "message", + "role": "user", + "content": "Hello, how are you?", + }, + ], metadata={ + "user_id": "123", + "session_id": "abc-def-ghi", + }, tools=[ + { + "type": "function", + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + }, + }, + }, + }, + ], model="anthropic/claude-4.5-sonnet-20250929", text={ + "format_": { + "type": "text", + }, + "verbosity": "medium", + }, reasoning={ + "summary": "auto", + "enabled": True, + }, temperature=0.7, top_p=0.9, prompt={ + "id": "", + "variables": { + "key": { + "type": "input_text", + "text": "Hello, how can I help you?", + }, + }, + }, service_tier="auto", truncation="auto", stream=False, provider={ + "data_collection": "deny", + "zdr": True, + "enforce_distillable_text": True, + "order": [ + "OpenAI", + ], + "only": [ + "OpenAI", + ], + "ignore": [ + "OpenAI", + ], + "quantizations": None, + "sort": "price", + }) + + with res as event_stream: + for event in event_stream: + # handle event + print(event, flush=True) + +``` + +[mdn-sse]: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events +[generator]: https://book.pythontips.com/en/latest/generators.html +[context-manager]: https://book.pythontips.com/en/latest/context_managers.html + + + +## Retries + +Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK. + +To change the default retry strategy for a single API call, simply provide a `RetryConfig` object to the call: +```python +from openrouter import OpenRouter +from openrouter.utils import BackoffStrategy, RetryConfig +import os + + +with OpenRouter( + api_key=os.getenv("OPENROUTER_API_KEY", ""), +) as open_router: + + res = open_router.beta.responses.send(input=[ + { + "type": "message", + "role": "user", + "content": "Hello, how are you?", + }, + ], metadata={ + "user_id": "123", + "session_id": "abc-def-ghi", + }, tools=[ + { + "type": "function", + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + }, + }, + }, + }, + ], model="anthropic/claude-4.5-sonnet-20250929", text={ + "format_": { + "type": "text", + }, + "verbosity": "medium", + }, reasoning={ + "summary": "auto", + "enabled": True, + }, temperature=0.7, top_p=0.9, prompt={ + "id": "", + "variables": { + "key": { + "type": "input_text", + "text": "Hello, how can I help you?", + }, + }, + }, service_tier="auto", truncation="auto", stream=False, provider={ + "data_collection": "deny", + "zdr": True, + "enforce_distillable_text": True, + "order": [ + "OpenAI", + ], + "only": [ + "OpenAI", + ], + "ignore": [ + "OpenAI", + ], + "quantizations": None, + "sort": "price", + }, + RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False)) + + with res as event_stream: + for event in event_stream: + # handle event + print(event, flush=True) + +``` + +If you'd like to override the default retry strategy for all operations that support retries, you can use the `retry_config` optional parameter when initializing the SDK: +```python +from openrouter import OpenRouter +from openrouter.utils import BackoffStrategy, RetryConfig +import os + + +with OpenRouter( + retry_config=RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False), + api_key=os.getenv("OPENROUTER_API_KEY", ""), +) as open_router: + + res = open_router.beta.responses.send(input=[ + { + "type": "message", + "role": "user", + "content": "Hello, how are you?", + }, + ], metadata={ + "user_id": "123", + "session_id": "abc-def-ghi", + }, tools=[ + { + "type": "function", + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + }, + }, + }, + }, + ], model="anthropic/claude-4.5-sonnet-20250929", text={ + "format_": { + "type": "text", + }, + "verbosity": "medium", + }, reasoning={ + "summary": "auto", + "enabled": True, + }, temperature=0.7, top_p=0.9, prompt={ + "id": "", + "variables": { + "key": { + "type": "input_text", + "text": "Hello, how can I help you?", + }, + }, + }, service_tier="auto", truncation="auto", stream=False, provider={ + "data_collection": "deny", + "zdr": True, + "enforce_distillable_text": True, + "order": [ + "OpenAI", + ], + "only": [ + "OpenAI", + ], + "ignore": [ + "OpenAI", + ], + "quantizations": None, + "sort": "price", + }) + + with res as event_stream: + for event in event_stream: + # handle event + print(event, flush=True) + +``` + + + +## Error Handling + +[`OpenRouterError`](./src/openrouter/errors/openroutererror.py) is the base class for all HTTP error responses. It has the following properties: + +| Property | Type | Description | +| ------------------ | ---------------- | --------------------------------------------------------------------------------------- | +| `err.message` | `str` | Error message | +| `err.status_code` | `int` | HTTP response status code eg `404` | +| `err.headers` | `httpx.Headers` | HTTP response headers | +| `err.body` | `str` | HTTP body. Can be empty string if no body is returned. | +| `err.raw_response` | `httpx.Response` | Raw HTTP response | +| `err.data` | | Optional. Some errors may contain structured data. [See Error Classes](#error-classes). | + +### Example +```python +from openrouter import OpenRouter, errors +import os + + +with OpenRouter( + api_key=os.getenv("OPENROUTER_API_KEY", ""), +) as open_router: + res = None + try: + + res = open_router.beta.responses.send(input=[ + { + "type": "message", + "role": "user", + "content": "Hello, how are you?", + }, + ], metadata={ + "user_id": "123", + "session_id": "abc-def-ghi", + }, tools=[ + { + "type": "function", + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + }, + }, + }, + }, + ], model="anthropic/claude-4.5-sonnet-20250929", text={ + "format_": { + "type": "text", + }, + "verbosity": "medium", + }, reasoning={ + "summary": "auto", + "enabled": True, + }, temperature=0.7, top_p=0.9, prompt={ + "id": "", + "variables": { + "key": { + "type": "input_text", + "text": "Hello, how can I help you?", + }, + }, + }, service_tier="auto", truncation="auto", stream=False, provider={ + "data_collection": "deny", + "zdr": True, + "enforce_distillable_text": True, + "order": [ + "OpenAI", + ], + "only": [ + "OpenAI", + ], + "ignore": [ + "OpenAI", + ], + "quantizations": None, + "sort": "price", + }) + + with res as event_stream: + for event in event_stream: + # handle event + print(event, flush=True) + + + except errors.OpenRouterError as e: + # The base class for HTTP error responses + print(e.message) + print(e.status_code) + print(e.body) + print(e.headers) + print(e.raw_response) + + # Depending on the method different errors may be thrown + if isinstance(e, errors.BadRequestResponseError): + print(e.data.error) # models.BadRequestResponseErrorData + print(e.data.user_id) # OptionalNullable[str] +``` + +### Error Classes +**Primary errors:** +* [`OpenRouterError`](./src/openrouter/errors/openroutererror.py): The base class for HTTP error responses. + * [`InternalServerResponseError`](./src/openrouter/errors/internalserverresponseerror.py): Internal Server Error - Unexpected server error. Status code `500`. * + +
Less common errors (19) + +
+ +**Network errors:** +* [`httpx.RequestError`](https://www.python-httpx.org/exceptions/#httpx.RequestError): Base class for request errors. + * [`httpx.ConnectError`](https://www.python-httpx.org/exceptions/#httpx.ConnectError): HTTP client was unable to make a request to a server. + * [`httpx.TimeoutException`](https://www.python-httpx.org/exceptions/#httpx.TimeoutException): HTTP request timed out. + + +**Inherit from [`OpenRouterError`](./src/openrouter/errors/openroutererror.py)**: +* [`UnauthorizedResponseError`](./src/openrouter/errors/unauthorizedresponseerror.py): Unauthorized - Authentication required or invalid credentials. Status code `401`. Applicable to 15 of 24 methods.* +* [`BadRequestResponseError`](./src/openrouter/errors/badrequestresponseerror.py): Bad Request - Invalid request parameters or malformed input. Status code `400`. Applicable to 10 of 24 methods.* +* [`TooManyRequestsResponseError`](./src/openrouter/errors/toomanyrequestsresponseerror.py): Too Many Requests - Rate limit exceeded. Status code `429`. Applicable to 9 of 24 methods.* +* [`NotFoundResponseError`](./src/openrouter/errors/notfoundresponseerror.py): Not Found - Resource does not exist. Status code `404`. Applicable to 8 of 24 methods.* +* [`PaymentRequiredResponseError`](./src/openrouter/errors/paymentrequiredresponseerror.py): Payment Required - Insufficient credits or quota to complete request. Status code `402`. Applicable to 3 of 24 methods.* +* [`ForbiddenResponseError`](./src/openrouter/errors/forbiddenresponseerror.py): Forbidden - Authentication successful but insufficient permissions. Status code `403`. Applicable to 3 of 24 methods.* +* [`BadGatewayResponseError`](./src/openrouter/errors/badgatewayresponseerror.py): Bad Gateway - Provider/upstream API failure. Status code `502`. Applicable to 3 of 24 methods.* +* [`EdgeNetworkTimeoutResponseError`](./src/openrouter/errors/edgenetworktimeoutresponseerror.py): Infrastructure Timeout - Provider request timed out at edge network. Status code `524`. Applicable to 3 of 24 methods.* +* [`ProviderOverloadedResponseError`](./src/openrouter/errors/provideroverloadedresponseerror.py): Provider Overloaded - Provider is temporarily overloaded. Status code `529`. Applicable to 3 of 24 methods.* +* [`ChatError`](./src/openrouter/errors/chaterror.py): Bad request - invalid parameters. Applicable to 2 of 24 methods.* +* [`ServiceUnavailableResponseError`](./src/openrouter/errors/serviceunavailableresponseerror.py): Service Unavailable - Service temporarily unavailable. Status code `503`. Applicable to 2 of 24 methods.* +* [`RequestTimeoutResponseError`](./src/openrouter/errors/requesttimeoutresponseerror.py): Request Timeout - Operation exceeded time limit. Status code `408`. Applicable to 1 of 24 methods.* +* [`PayloadTooLargeResponseError`](./src/openrouter/errors/payloadtoolargeresponseerror.py): Payload Too Large - Request payload exceeds size limits. Status code `413`. Applicable to 1 of 24 methods.* +* [`UnprocessableEntityResponseError`](./src/openrouter/errors/unprocessableentityresponseerror.py): Unprocessable Entity - Semantic validation failure. Status code `422`. Applicable to 1 of 24 methods.* +* [`ResponseValidationError`](./src/openrouter/errors/responsevalidationerror.py): Type mismatch between the response data and the expected Pydantic model. Provides access to the Pydantic validation error via the `cause` attribute. + +
+ +\* Check [the method documentation](#available-resources-and-operations) to see if the error is applicable. + + + +## Server Selection + +### Select Server by Name + +You can override the default server globally by passing a server name to the `server: str` optional parameter when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the names associated with the available servers: + +| Name | Server | Description | +| ------------ | ------------------------------ | ----------------- | +| `production` | `https://openrouter.ai/api/v1` | Production server | + +#### Example + +```python +from openrouter import OpenRouter +import os + + +with OpenRouter( + server="production", + api_key=os.getenv("OPENROUTER_API_KEY", ""), +) as open_router: + + res = open_router.beta.responses.send(input=[ + { + "type": "message", + "role": "user", + "content": "Hello, how are you?", + }, + ], metadata={ + "user_id": "123", + "session_id": "abc-def-ghi", + }, tools=[ + { + "type": "function", + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + }, + }, + }, + }, + ], model="anthropic/claude-4.5-sonnet-20250929", text={ + "format_": { + "type": "text", + }, + "verbosity": "medium", + }, reasoning={ + "summary": "auto", + "enabled": True, + }, temperature=0.7, top_p=0.9, prompt={ + "id": "", + "variables": { + "key": { + "type": "input_text", + "text": "Hello, how can I help you?", + }, + }, + }, service_tier="auto", truncation="auto", stream=False, provider={ + "data_collection": "deny", + "zdr": True, + "enforce_distillable_text": True, + "order": [ + "OpenAI", + ], + "only": [ + "OpenAI", + ], + "ignore": [ + "OpenAI", + ], + "quantizations": None, + "sort": "price", + }) + + with res as event_stream: + for event in event_stream: + # handle event + print(event, flush=True) + +``` + +### Override Server URL Per-Client + +The default server can also be overridden globally by passing a URL to the `server_url: str` optional parameter when initializing the SDK client instance. For example: +```python +from openrouter import OpenRouter +import os + + +with OpenRouter( + server_url="https://openrouter.ai/api/v1", + api_key=os.getenv("OPENROUTER_API_KEY", ""), +) as open_router: + + res = open_router.beta.responses.send(input=[ + { + "type": "message", + "role": "user", + "content": "Hello, how are you?", + }, + ], metadata={ + "user_id": "123", + "session_id": "abc-def-ghi", + }, tools=[ + { + "type": "function", + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + }, + }, + }, + }, + ], model="anthropic/claude-4.5-sonnet-20250929", text={ + "format_": { + "type": "text", + }, + "verbosity": "medium", + }, reasoning={ + "summary": "auto", + "enabled": True, + }, temperature=0.7, top_p=0.9, prompt={ + "id": "", + "variables": { + "key": { + "type": "input_text", + "text": "Hello, how can I help you?", + }, + }, + }, service_tier="auto", truncation="auto", stream=False, provider={ + "data_collection": "deny", + "zdr": True, + "enforce_distillable_text": True, + "order": [ + "OpenAI", + ], + "only": [ + "OpenAI", + ], + "ignore": [ + "OpenAI", + ], + "quantizations": None, + "sort": "price", + }) + + with res as event_stream: + for event in event_stream: + # handle event + print(event, flush=True) + +``` + + + +## Custom HTTP Client + +The Python SDK makes API calls using the [httpx](https://www.python-httpx.org/) HTTP library. In order to provide a convenient way to configure timeouts, cookies, proxies, custom headers, and other low-level configuration, you can initialize the SDK client with your own HTTP client instance. +Depending on whether you are using the sync or async version of the SDK, you can pass an instance of `HttpClient` or `AsyncHttpClient` respectively, which are Protocol's ensuring that the client has the necessary methods to make API calls. +This allows you to wrap the client with your own custom logic, such as adding custom headers, logging, or error handling, or you can just pass an instance of `httpx.Client` or `httpx.AsyncClient` directly. + +For example, you could specify a header for every request that this sdk makes as follows: +```python +from openrouter import OpenRouter +import httpx + +http_client = httpx.Client(headers={"x-custom-header": "someValue"}) +s = OpenRouter(client=http_client) +``` + +or you could wrap the client with your own custom logic: +```python +from openrouter import OpenRouter +from openrouter.httpclient import AsyncHttpClient +import httpx + +class CustomClient(AsyncHttpClient): + client: AsyncHttpClient + + def __init__(self, client: AsyncHttpClient): + self.client = client + + async def send( + self, + request: httpx.Request, + *, + stream: bool = False, + auth: Union[ + httpx._types.AuthTypes, httpx._client.UseClientDefault, None + ] = httpx.USE_CLIENT_DEFAULT, + follow_redirects: Union[ + bool, httpx._client.UseClientDefault + ] = httpx.USE_CLIENT_DEFAULT, + ) -> httpx.Response: + request.headers["Client-Level-Header"] = "added by client" + + return await self.client.send( + request, stream=stream, auth=auth, follow_redirects=follow_redirects + ) + + def build_request( + self, + method: str, + url: httpx._types.URLTypes, + *, + content: Optional[httpx._types.RequestContent] = None, + data: Optional[httpx._types.RequestData] = None, + files: Optional[httpx._types.RequestFiles] = None, + json: Optional[Any] = None, + params: Optional[httpx._types.QueryParamTypes] = None, + headers: Optional[httpx._types.HeaderTypes] = None, + cookies: Optional[httpx._types.CookieTypes] = None, + timeout: Union[ + httpx._types.TimeoutTypes, httpx._client.UseClientDefault + ] = httpx.USE_CLIENT_DEFAULT, + extensions: Optional[httpx._types.RequestExtensions] = None, + ) -> httpx.Request: + return self.client.build_request( + method, + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + timeout=timeout, + extensions=extensions, + ) + +s = OpenRouter(async_client=CustomClient(httpx.AsyncClient())) +``` + + + +## Resource Management + +The `OpenRouter` class implements the context manager protocol and registers a finalizer function to close the underlying sync and async HTTPX clients it uses under the hood. This will close HTTP connections, release memory and free up other resources held by the SDK. In short-lived Python programs and notebooks that make a few SDK method calls, resource management may not be a concern. However, in longer-lived programs, it is beneficial to create a single SDK instance via a [context manager][context-manager] and reuse it across the application. + +[context-manager]: https://docs.python.org/3/reference/datamodel.html#context-managers + +```python +from openrouter import OpenRouter +import os +def main(): + + with OpenRouter( + api_key=os.getenv("OPENROUTER_API_KEY", ""), + ) as open_router: + # Rest of application here... + + +# Or when using async: +async def amain(): + + async with OpenRouter( + api_key=os.getenv("OPENROUTER_API_KEY", ""), + ) as open_router: + # Rest of application here... +``` + + + +## Debugging + +You can setup your SDK to emit debug logs for SDK requests and responses. + +You can pass your own logger class directly into your SDK. +```python +from openrouter import OpenRouter +import logging + +logging.basicConfig(level=logging.DEBUG) +s = OpenRouter(debug_logger=logging.getLogger("openrouter")) +``` + +You can also enable a default debug logger by setting an environment variable `OPENROUTER_DEBUG` to true. + + + + +# Development + +## Maturity + +This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage +to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally +looking for the latest version. + +## Contributions + +While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation. +We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release. + +### SDK Created by [Speakeasy](https://www.speakeasy.com/?utm_source=openrouter&utm_campaign=python) + + \ No newline at end of file diff --git a/USAGE.md b/USAGE.md new file mode 100644 index 0000000..ad55718 --- /dev/null +++ b/USAGE.md @@ -0,0 +1,153 @@ + +```python +# Synchronous Example +from openrouter import OpenRouter +import os + + +with OpenRouter( + api_key=os.getenv("OPENROUTER_API_KEY", ""), +) as open_router: + + res = open_router.beta.responses.send(input=[ + { + "type": "message", + "role": "user", + "content": "Hello, how are you?", + }, + ], metadata={ + "user_id": "123", + "session_id": "abc-def-ghi", + }, tools=[ + { + "type": "function", + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + }, + }, + }, + }, + ], model="anthropic/claude-4.5-sonnet-20250929", text={ + "format_": { + "type": "text", + }, + "verbosity": "medium", + }, reasoning={ + "summary": "auto", + "enabled": True, + }, temperature=0.7, top_p=0.9, prompt={ + "id": "", + "variables": { + "key": { + "type": "input_text", + "text": "Hello, how can I help you?", + }, + }, + }, service_tier="auto", truncation="auto", stream=False, provider={ + "data_collection": "deny", + "zdr": True, + "enforce_distillable_text": True, + "order": [ + "OpenAI", + ], + "only": [ + "OpenAI", + ], + "ignore": [ + "OpenAI", + ], + "quantizations": None, + "sort": "price", + }) + + with res as event_stream: + for event in event_stream: + # handle event + print(event, flush=True) +``` + +
+ +The same SDK client can also be used to make asynchronous requests by importing asyncio. + +```python +# Asynchronous Example +import asyncio +from openrouter import OpenRouter +import os + +async def main(): + + async with OpenRouter( + api_key=os.getenv("OPENROUTER_API_KEY", ""), + ) as open_router: + + res = await open_router.beta.responses.send_async(input=[ + { + "type": "message", + "role": "user", + "content": "Hello, how are you?", + }, + ], metadata={ + "user_id": "123", + "session_id": "abc-def-ghi", + }, tools=[ + { + "type": "function", + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + }, + }, + }, + }, + ], model="anthropic/claude-4.5-sonnet-20250929", text={ + "format_": { + "type": "text", + }, + "verbosity": "medium", + }, reasoning={ + "summary": "auto", + "enabled": True, + }, temperature=0.7, top_p=0.9, prompt={ + "id": "", + "variables": { + "key": { + "type": "input_text", + "text": "Hello, how can I help you?", + }, + }, + }, service_tier="auto", truncation="auto", stream=False, provider={ + "data_collection": "deny", + "zdr": True, + "enforce_distillable_text": True, + "order": [ + "OpenAI", + ], + "only": [ + "OpenAI", + ], + "ignore": [ + "OpenAI", + ], + "quantizations": None, + "sort": "price", + }) + + async with res as event_stream: + async for event in event_stream: + # handle event + print(event, flush=True) + +asyncio.run(main()) +``` + \ No newline at end of file diff --git a/docs/errors/badgatewayresponseerror.md b/docs/errors/badgatewayresponseerror.md new file mode 100644 index 0000000..adea628 --- /dev/null +++ b/docs/errors/badgatewayresponseerror.md @@ -0,0 +1,11 @@ +# BadGatewayResponseError + +Bad Gateway - Provider/upstream API failure + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | +| `error` | [models.BadGatewayResponseErrorData](../models/badgatewayresponseerrordata.md) | :heavy_check_mark: | Error data for BadGatewayResponse | {
"code": 502,
"message": "Provider returned error"
} | +| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/docs/errors/badrequestresponseerror.md b/docs/errors/badrequestresponseerror.md new file mode 100644 index 0000000..65cbd40 --- /dev/null +++ b/docs/errors/badrequestresponseerror.md @@ -0,0 +1,11 @@ +# BadRequestResponseError + +Bad Request - Invalid request parameters or malformed input + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | +| `error` | [models.BadRequestResponseErrorData](../models/badrequestresponseerrordata.md) | :heavy_check_mark: | Error data for BadRequestResponse | {
"code": 400,
"message": "Invalid request parameters"
} | +| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/docs/errors/chaterror.md b/docs/errors/chaterror.md new file mode 100644 index 0000000..7eeb7f4 --- /dev/null +++ b/docs/errors/chaterror.md @@ -0,0 +1,8 @@ +# ChatError + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------- | ---------------------------------------------------- | ---------------------------------------------------- | ---------------------------------------------------- | +| `error` | [models.ChatErrorError](../models/chaterrorerror.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/errors/edgenetworktimeoutresponseerror.md b/docs/errors/edgenetworktimeoutresponseerror.md new file mode 100644 index 0000000..b77d47b --- /dev/null +++ b/docs/errors/edgenetworktimeoutresponseerror.md @@ -0,0 +1,11 @@ +# EdgeNetworkTimeoutResponseError + +Infrastructure Timeout - Provider request timed out at edge network + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | +| `error` | [models.EdgeNetworkTimeoutResponseErrorData](../models/edgenetworktimeoutresponseerrordata.md) | :heavy_check_mark: | Error data for EdgeNetworkTimeoutResponse | {
"code": 524,
"message": "Request timed out. Please try again later."
} | +| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/docs/errors/forbiddenresponseerror.md b/docs/errors/forbiddenresponseerror.md new file mode 100644 index 0000000..8aed20d --- /dev/null +++ b/docs/errors/forbiddenresponseerror.md @@ -0,0 +1,11 @@ +# ForbiddenResponseError + +Forbidden - Authentication successful but insufficient permissions + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | +| `error` | [models.ForbiddenResponseErrorData](../models/forbiddenresponseerrordata.md) | :heavy_check_mark: | Error data for ForbiddenResponse | {
"code": 403,
"message": "Only provisioning keys can perform this operation"
} | +| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/docs/errors/internalserverresponseerror.md b/docs/errors/internalserverresponseerror.md new file mode 100644 index 0000000..7040337 --- /dev/null +++ b/docs/errors/internalserverresponseerror.md @@ -0,0 +1,11 @@ +# InternalServerResponseError + +Internal Server Error - Unexpected server error + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | +| `error` | [models.InternalServerResponseErrorData](../models/internalserverresponseerrordata.md) | :heavy_check_mark: | Error data for InternalServerResponse | {
"code": 500,
"message": "Internal Server Error"
} | +| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/docs/errors/notfoundresponseerror.md b/docs/errors/notfoundresponseerror.md new file mode 100644 index 0000000..973d421 --- /dev/null +++ b/docs/errors/notfoundresponseerror.md @@ -0,0 +1,11 @@ +# NotFoundResponseError + +Not Found - Resource does not exist + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------------------------------------------- | -------------------------------------------------------------------------- | -------------------------------------------------------------------------- | -------------------------------------------------------------------------- | -------------------------------------------------------------------------- | +| `error` | [models.NotFoundResponseErrorData](../models/notfoundresponseerrordata.md) | :heavy_check_mark: | Error data for NotFoundResponse | {
"code": 404,
"message": "Resource not found"
} | +| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/docs/errors/payloadtoolargeresponseerror.md b/docs/errors/payloadtoolargeresponseerror.md new file mode 100644 index 0000000..b05367e --- /dev/null +++ b/docs/errors/payloadtoolargeresponseerror.md @@ -0,0 +1,11 @@ +# PayloadTooLargeResponseError + +Payload Too Large - Request payload exceeds size limits + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | +| `error` | [models.PayloadTooLargeResponseErrorData](../models/payloadtoolargeresponseerrordata.md) | :heavy_check_mark: | Error data for PayloadTooLargeResponse | {
"code": 413,
"message": "Request payload too large"
} | +| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/docs/errors/paymentrequiredresponseerror.md b/docs/errors/paymentrequiredresponseerror.md new file mode 100644 index 0000000..9c2a77c --- /dev/null +++ b/docs/errors/paymentrequiredresponseerror.md @@ -0,0 +1,11 @@ +# PaymentRequiredResponseError + +Payment Required - Insufficient credits or quota to complete request + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | +| `error` | [models.PaymentRequiredResponseErrorData](../models/paymentrequiredresponseerrordata.md) | :heavy_check_mark: | Error data for PaymentRequiredResponse | {
"code": 402,
"message": "Insufficient credits. Add more using https://openrouter.ai/credits"
} | +| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/docs/errors/provideroverloadedresponseerror.md b/docs/errors/provideroverloadedresponseerror.md new file mode 100644 index 0000000..4d27c2e --- /dev/null +++ b/docs/errors/provideroverloadedresponseerror.md @@ -0,0 +1,11 @@ +# ProviderOverloadedResponseError + +Provider Overloaded - Provider is temporarily overloaded + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | +| `error` | [models.ProviderOverloadedResponseErrorData](../models/provideroverloadedresponseerrordata.md) | :heavy_check_mark: | Error data for ProviderOverloadedResponse | {
"code": 529,
"message": "Provider returned error"
} | +| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/docs/errors/requesttimeoutresponseerror.md b/docs/errors/requesttimeoutresponseerror.md new file mode 100644 index 0000000..f28755f --- /dev/null +++ b/docs/errors/requesttimeoutresponseerror.md @@ -0,0 +1,11 @@ +# RequestTimeoutResponseError + +Request Timeout - Operation exceeded time limit + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | +| `error` | [models.RequestTimeoutResponseErrorData](../models/requesttimeoutresponseerrordata.md) | :heavy_check_mark: | Error data for RequestTimeoutResponse | {
"code": 408,
"message": "Operation timed out. Please try again later."
} | +| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/docs/errors/serviceunavailableresponseerror.md b/docs/errors/serviceunavailableresponseerror.md new file mode 100644 index 0000000..b2a5043 --- /dev/null +++ b/docs/errors/serviceunavailableresponseerror.md @@ -0,0 +1,11 @@ +# ServiceUnavailableResponseError + +Service Unavailable - Service temporarily unavailable + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | +| `error` | [models.ServiceUnavailableResponseErrorData](../models/serviceunavailableresponseerrordata.md) | :heavy_check_mark: | Error data for ServiceUnavailableResponse | {
"code": 503,
"message": "Service temporarily unavailable"
} | +| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/docs/errors/toomanyrequestsresponseerror.md b/docs/errors/toomanyrequestsresponseerror.md new file mode 100644 index 0000000..fb533b5 --- /dev/null +++ b/docs/errors/toomanyrequestsresponseerror.md @@ -0,0 +1,11 @@ +# TooManyRequestsResponseError + +Too Many Requests - Rate limit exceeded + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | +| `error` | [models.TooManyRequestsResponseErrorData](../models/toomanyrequestsresponseerrordata.md) | :heavy_check_mark: | Error data for TooManyRequestsResponse | {
"code": 429,
"message": "Rate limit exceeded"
} | +| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/docs/errors/unauthorizedresponseerror.md b/docs/errors/unauthorizedresponseerror.md new file mode 100644 index 0000000..1f6b55e --- /dev/null +++ b/docs/errors/unauthorizedresponseerror.md @@ -0,0 +1,11 @@ +# UnauthorizedResponseError + +Unauthorized - Authentication required or invalid credentials + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | +| `error` | [models.UnauthorizedResponseErrorData](../models/unauthorizedresponseerrordata.md) | :heavy_check_mark: | Error data for UnauthorizedResponse | {
"code": 401,
"message": "Missing Authentication header"
} | +| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/docs/errors/unprocessableentityresponseerror.md b/docs/errors/unprocessableentityresponseerror.md new file mode 100644 index 0000000..1355f82 --- /dev/null +++ b/docs/errors/unprocessableentityresponseerror.md @@ -0,0 +1,11 @@ +# UnprocessableEntityResponseError + +Unprocessable Entity - Semantic validation failure + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | +| `error` | [models.UnprocessableEntityResponseErrorData](../models/unprocessableentityresponseerrordata.md) | :heavy_check_mark: | Error data for UnprocessableEntityResponse | {
"code": 422,
"message": "Invalid argument"
} | +| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/docs/models/activityitem.md b/docs/models/activityitem.md new file mode 100644 index 0000000..570bc52 --- /dev/null +++ b/docs/models/activityitem.md @@ -0,0 +1,18 @@ +# ActivityItem + + +## Fields + +| Field | Type | Required | Description | Example | +| --------------------------------------------------- | --------------------------------------------------- | --------------------------------------------------- | --------------------------------------------------- | --------------------------------------------------- | +| `date_` | *str* | :heavy_check_mark: | Date of the activity (YYYY-MM-DD format) | 2025-08-24 | +| `model` | *str* | :heavy_check_mark: | Model slug (e.g., "openai/gpt-4.1") | openai/gpt-4.1 | +| `model_permaslug` | *str* | :heavy_check_mark: | Model permaslug (e.g., "openai/gpt-4.1-2025-04-14") | openai/gpt-4.1-2025-04-14 | +| `endpoint_id` | *str* | :heavy_check_mark: | Unique identifier for the endpoint | 550e8400-e29b-41d4-a716-446655440000 | +| `provider_name` | *str* | :heavy_check_mark: | Name of the provider serving this endpoint | OpenAI | +| `usage` | *float* | :heavy_check_mark: | Total cost in USD (OpenRouter credits spent) | 0.015 | +| `byok_usage_inference` | *float* | :heavy_check_mark: | BYOK inference cost in USD (external credits spent) | 0.012 | +| `requests` | *float* | :heavy_check_mark: | Number of requests made | 5 | +| `prompt_tokens` | *float* | :heavy_check_mark: | Total prompt tokens used | 50 | +| `completion_tokens` | *float* | :heavy_check_mark: | Total completion tokens generated | 125 | +| `reasoning_tokens` | *float* | :heavy_check_mark: | Total reasoning tokens used | 25 | \ No newline at end of file diff --git a/docs/models/apitype.md b/docs/models/apitype.md new file mode 100644 index 0000000..6cc34e4 --- /dev/null +++ b/docs/models/apitype.md @@ -0,0 +1,11 @@ +# APIType + +Type of API used for the generation + + +## Values + +| Name | Value | +| ------------- | ------------- | +| `COMPLETIONS` | completions | +| `EMBEDDINGS` | embeddings | \ No newline at end of file diff --git a/docs/models/architecture.md b/docs/models/architecture.md new file mode 100644 index 0000000..b74d518 --- /dev/null +++ b/docs/models/architecture.md @@ -0,0 +1,14 @@ +# Architecture + +Model architecture information + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- | +| `tokenizer` | [Nullable[models.Tokenizer]](../models/tokenizer.md) | :heavy_check_mark: | N/A | GPT | +| `instruct_type` | [Nullable[models.InstructType]](../models/instructtype.md) | :heavy_check_mark: | Instruction format type | | +| `modality` | *Nullable[str]* | :heavy_check_mark: | Primary modality of the model | text | +| `input_modalities` | List[[models.InputModality](../models/inputmodality.md)] | :heavy_check_mark: | Supported input modalities | | +| `output_modalities` | List[[models.OutputModality](../models/outputmodality.md)] | :heavy_check_mark: | Supported output modalities | | \ No newline at end of file diff --git a/docs/models/assistantmessage.md b/docs/models/assistantmessage.md new file mode 100644 index 0000000..bd17f09 --- /dev/null +++ b/docs/models/assistantmessage.md @@ -0,0 +1,13 @@ +# AssistantMessage + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | +| `role` | *Literal["assistant"]* | :heavy_check_mark: | N/A | +| `content` | [OptionalNullable[models.AssistantMessageContent]](../models/assistantmessagecontent.md) | :heavy_minus_sign: | N/A | +| `name` | *Optional[str]* | :heavy_minus_sign: | N/A | +| `tool_calls` | List[[models.ChatMessageToolCall](../models/chatmessagetoolcall.md)] | :heavy_minus_sign: | N/A | +| `refusal` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | +| `reasoning` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/assistantmessagecontent.md b/docs/models/assistantmessagecontent.md new file mode 100644 index 0000000..bd14bde --- /dev/null +++ b/docs/models/assistantmessagecontent.md @@ -0,0 +1,17 @@ +# AssistantMessageContent + + +## Supported Types + +### `str` + +```python +value: str = /* values here */ +``` + +### `List[models.ChatMessageContentItem]` + +```python +value: List[models.ChatMessageContentItem] = /* values here */ +``` + diff --git a/docs/models/badgatewayresponseerrordata.md b/docs/models/badgatewayresponseerrordata.md new file mode 100644 index 0000000..9de5a89 --- /dev/null +++ b/docs/models/badgatewayresponseerrordata.md @@ -0,0 +1,12 @@ +# BadGatewayResponseErrorData + +Error data for BadGatewayResponse + + +## Fields + +| Field | Type | Required | Description | +| -------------------------- | -------------------------- | -------------------------- | -------------------------- | +| `code` | *int* | :heavy_check_mark: | N/A | +| `message` | *str* | :heavy_check_mark: | N/A | +| `metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/badrequestresponseerrordata.md b/docs/models/badrequestresponseerrordata.md new file mode 100644 index 0000000..c36a56e --- /dev/null +++ b/docs/models/badrequestresponseerrordata.md @@ -0,0 +1,12 @@ +# BadRequestResponseErrorData + +Error data for BadRequestResponse + + +## Fields + +| Field | Type | Required | Description | +| -------------------------- | -------------------------- | -------------------------- | -------------------------- | +| `code` | *int* | :heavy_check_mark: | N/A | +| `message` | *str* | :heavy_check_mark: | N/A | +| `metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/calldata.md b/docs/models/calldata.md new file mode 100644 index 0000000..de7a031 --- /dev/null +++ b/docs/models/calldata.md @@ -0,0 +1,17 @@ +# CallData + + +## Fields + +| Field | Type | Required | Description | +| -------------------- | -------------------- | -------------------- | -------------------- | +| `deadline` | *str* | :heavy_check_mark: | N/A | +| `fee_amount` | *str* | :heavy_check_mark: | N/A | +| `id` | *str* | :heavy_check_mark: | N/A | +| `operator` | *str* | :heavy_check_mark: | N/A | +| `prefix` | *str* | :heavy_check_mark: | N/A | +| `recipient` | *str* | :heavy_check_mark: | N/A | +| `recipient_amount` | *str* | :heavy_check_mark: | N/A | +| `recipient_currency` | *str* | :heavy_check_mark: | N/A | +| `refund_destination` | *str* | :heavy_check_mark: | N/A | +| `signature` | *str* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/chainid.md b/docs/models/chainid.md new file mode 100644 index 0000000..11579fe --- /dev/null +++ b/docs/models/chainid.md @@ -0,0 +1,10 @@ +# ChainID + + +## Values + +| Name | Value | +| --------------------------------------------- | --------------------------------------------- | +| `ONE` | 1 | +| `ONE_HUNDRED_AND_THIRTY_SEVEN` | 137 | +| `EIGHT_THOUSAND_FOUR_HUNDRED_AND_FIFTY_THREE` | 8453 | \ No newline at end of file diff --git a/docs/models/chatcompletionfinishreason.md b/docs/models/chatcompletionfinishreason.md new file mode 100644 index 0000000..cb9e72c --- /dev/null +++ b/docs/models/chatcompletionfinishreason.md @@ -0,0 +1,12 @@ +# ChatCompletionFinishReason + + +## Values + +| Name | Value | +| ---------------- | ---------------- | +| `TOOL_CALLS` | tool_calls | +| `STOP` | stop | +| `LENGTH` | length | +| `CONTENT_FILTER` | content_filter | +| `ERROR` | error | \ No newline at end of file diff --git a/docs/models/chaterrorerror.md b/docs/models/chaterrorerror.md new file mode 100644 index 0000000..6deb553 --- /dev/null +++ b/docs/models/chaterrorerror.md @@ -0,0 +1,11 @@ +# ChatErrorError + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------ | ------------------------------------------ | ------------------------------------------ | ------------------------------------------ | +| `code` | [Nullable[models.Code]](../models/code.md) | :heavy_check_mark: | N/A | +| `message` | *str* | :heavy_check_mark: | N/A | +| `param` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | +| `type` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/chatgenerationparams.md b/docs/models/chatgenerationparams.md new file mode 100644 index 0000000..04b80d9 --- /dev/null +++ b/docs/models/chatgenerationparams.md @@ -0,0 +1,29 @@ +# ChatGenerationParams + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | +| `messages` | List[[models.Message](../models/message.md)] | :heavy_check_mark: | N/A | +| `model` | *Optional[str]* | :heavy_minus_sign: | N/A | +| `models` | List[*str*] | :heavy_minus_sign: | N/A | +| `frequency_penalty` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | +| `logit_bias` | Dict[str, *float*] | :heavy_minus_sign: | N/A | +| `logprobs` | *OptionalNullable[bool]* | :heavy_minus_sign: | N/A | +| `top_logprobs` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | +| `max_completion_tokens` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | +| `max_tokens` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | +| `metadata` | Dict[str, *str*] | :heavy_minus_sign: | N/A | +| `presence_penalty` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | +| `reasoning` | [Optional[models.Reasoning]](../models/reasoning.md) | :heavy_minus_sign: | N/A | +| `response_format` | [Optional[models.ChatGenerationParamsResponseFormatUnion]](../models/chatgenerationparamsresponseformatunion.md) | :heavy_minus_sign: | N/A | +| `seed` | *OptionalNullable[int]* | :heavy_minus_sign: | N/A | +| `stop` | [OptionalNullable[models.ChatGenerationParamsStop]](../models/chatgenerationparamsstop.md) | :heavy_minus_sign: | N/A | +| `stream` | *Optional[bool]* | :heavy_minus_sign: | N/A | +| `stream_options` | [OptionalNullable[models.ChatStreamOptions]](../models/chatstreamoptions.md) | :heavy_minus_sign: | N/A | +| `temperature` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | +| `tool_choice` | *Optional[Any]* | :heavy_minus_sign: | N/A | +| `tools` | List[[models.ToolDefinitionJSON](../models/tooldefinitionjson.md)] | :heavy_minus_sign: | N/A | +| `top_p` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | +| `user` | *Optional[str]* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/chatgenerationparamsresponseformatjsonobject.md b/docs/models/chatgenerationparamsresponseformatjsonobject.md new file mode 100644 index 0000000..4c9c696 --- /dev/null +++ b/docs/models/chatgenerationparamsresponseformatjsonobject.md @@ -0,0 +1,8 @@ +# ChatGenerationParamsResponseFormatJSONObject + + +## Fields + +| Field | Type | Required | Description | +| ------------------------ | ------------------------ | ------------------------ | ------------------------ | +| `type` | *Literal["json_object"]* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/chatgenerationparamsresponseformatpython.md b/docs/models/chatgenerationparamsresponseformatpython.md new file mode 100644 index 0000000..5b1274c --- /dev/null +++ b/docs/models/chatgenerationparamsresponseformatpython.md @@ -0,0 +1,8 @@ +# ChatGenerationParamsResponseFormatPython + + +## Fields + +| Field | Type | Required | Description | +| ------------------- | ------------------- | ------------------- | ------------------- | +| `type` | *Literal["python"]* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/chatgenerationparamsresponseformattext.md b/docs/models/chatgenerationparamsresponseformattext.md new file mode 100644 index 0000000..9efb0d8 --- /dev/null +++ b/docs/models/chatgenerationparamsresponseformattext.md @@ -0,0 +1,8 @@ +# ChatGenerationParamsResponseFormatText + + +## Fields + +| Field | Type | Required | Description | +| ------------------ | ------------------ | ------------------ | ------------------ | +| `type` | *Literal["text"]* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/chatgenerationparamsresponseformatunion.md b/docs/models/chatgenerationparamsresponseformatunion.md new file mode 100644 index 0000000..4e25dff --- /dev/null +++ b/docs/models/chatgenerationparamsresponseformatunion.md @@ -0,0 +1,35 @@ +# ChatGenerationParamsResponseFormatUnion + + +## Supported Types + +### `models.ChatGenerationParamsResponseFormatText` + +```python +value: models.ChatGenerationParamsResponseFormatText = /* values here */ +``` + +### `models.ChatGenerationParamsResponseFormatJSONObject` + +```python +value: models.ChatGenerationParamsResponseFormatJSONObject = /* values here */ +``` + +### `models.ResponseFormatJSONSchema` + +```python +value: models.ResponseFormatJSONSchema = /* values here */ +``` + +### `models.ResponseFormatTextGrammar` + +```python +value: models.ResponseFormatTextGrammar = /* values here */ +``` + +### `models.ChatGenerationParamsResponseFormatPython` + +```python +value: models.ChatGenerationParamsResponseFormatPython = /* values here */ +``` + diff --git a/docs/models/chatgenerationparamsstop.md b/docs/models/chatgenerationparamsstop.md new file mode 100644 index 0000000..9725523 --- /dev/null +++ b/docs/models/chatgenerationparamsstop.md @@ -0,0 +1,17 @@ +# ChatGenerationParamsStop + + +## Supported Types + +### `str` + +```python +value: str = /* values here */ +``` + +### `List[str]` + +```python +value: List[str] = /* values here */ +``` + diff --git a/docs/models/chatgenerationtokenusage.md b/docs/models/chatgenerationtokenusage.md new file mode 100644 index 0000000..a4649cf --- /dev/null +++ b/docs/models/chatgenerationtokenusage.md @@ -0,0 +1,12 @@ +# ChatGenerationTokenUsage + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | +| `completion_tokens` | *float* | :heavy_check_mark: | N/A | +| `prompt_tokens` | *float* | :heavy_check_mark: | N/A | +| `total_tokens` | *float* | :heavy_check_mark: | N/A | +| `completion_tokens_details` | [OptionalNullable[models.CompletionTokensDetails]](../models/completiontokensdetails.md) | :heavy_minus_sign: | N/A | +| `prompt_tokens_details` | [OptionalNullable[models.PromptTokensDetails]](../models/prompttokensdetails.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/chatmessagecontentitem.md b/docs/models/chatmessagecontentitem.md new file mode 100644 index 0000000..f0e3850 --- /dev/null +++ b/docs/models/chatmessagecontentitem.md @@ -0,0 +1,29 @@ +# ChatMessageContentItem + + +## Supported Types + +### `models.ChatMessageContentItemText` + +```python +value: models.ChatMessageContentItemText = /* values here */ +``` + +### `models.ChatMessageContentItemImage` + +```python +value: models.ChatMessageContentItemImage = /* values here */ +``` + +### `models.ChatMessageContentItemAudio` + +```python +value: models.ChatMessageContentItemAudio = /* values here */ +``` + +### `models.ChatMessageContentItemVideo` + +```python +value: models.ChatMessageContentItemVideo = /* values here */ +``` + diff --git a/docs/models/chatmessagecontentitemaudio.md b/docs/models/chatmessagecontentitemaudio.md new file mode 100644 index 0000000..5f889dd --- /dev/null +++ b/docs/models/chatmessagecontentitemaudio.md @@ -0,0 +1,9 @@ +# ChatMessageContentItemAudio + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | +| `type` | *Literal["input_audio"]* | :heavy_check_mark: | N/A | +| `input_audio` | [models.ChatMessageContentItemAudioInputAudio](../models/chatmessagecontentitemaudioinputaudio.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/chatmessagecontentitemaudioformat.md b/docs/models/chatmessagecontentitemaudioformat.md new file mode 100644 index 0000000..97119c0 --- /dev/null +++ b/docs/models/chatmessagecontentitemaudioformat.md @@ -0,0 +1,14 @@ +# ChatMessageContentItemAudioFormat + + +## Values + +| Name | Value | +| ------- | ------- | +| `WAV` | wav | +| `MP3` | mp3 | +| `FLAC` | flac | +| `M4A` | m4a | +| `OGG` | ogg | +| `PCM16` | pcm16 | +| `PCM24` | pcm24 | \ No newline at end of file diff --git a/docs/models/chatmessagecontentitemaudioinputaudio.md b/docs/models/chatmessagecontentitemaudioinputaudio.md new file mode 100644 index 0000000..20479a9 --- /dev/null +++ b/docs/models/chatmessagecontentitemaudioinputaudio.md @@ -0,0 +1,9 @@ +# ChatMessageContentItemAudioInputAudio + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | +| `data` | *str* | :heavy_check_mark: | N/A | +| `format_` | [models.ChatMessageContentItemAudioFormat](../models/chatmessagecontentitemaudioformat.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/chatmessagecontentitemimage.md b/docs/models/chatmessagecontentitemimage.md new file mode 100644 index 0000000..351244b --- /dev/null +++ b/docs/models/chatmessagecontentitemimage.md @@ -0,0 +1,9 @@ +# ChatMessageContentItemImage + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | +| `type` | *Literal["image_url"]* | :heavy_check_mark: | N/A | +| `image_url` | [models.ImageURL](../models/imageurl.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/chatmessagecontentitemimagedetail.md b/docs/models/chatmessagecontentitemimagedetail.md new file mode 100644 index 0000000..32d58f7 --- /dev/null +++ b/docs/models/chatmessagecontentitemimagedetail.md @@ -0,0 +1,10 @@ +# ChatMessageContentItemImageDetail + + +## Values + +| Name | Value | +| ------ | ------ | +| `AUTO` | auto | +| `LOW` | low | +| `HIGH` | high | \ No newline at end of file diff --git a/docs/models/chatmessagecontentitemtext.md b/docs/models/chatmessagecontentitemtext.md new file mode 100644 index 0000000..4fa8b7b --- /dev/null +++ b/docs/models/chatmessagecontentitemtext.md @@ -0,0 +1,9 @@ +# ChatMessageContentItemText + + +## Fields + +| Field | Type | Required | Description | +| ------------------ | ------------------ | ------------------ | ------------------ | +| `type` | *Literal["text"]* | :heavy_check_mark: | N/A | +| `text` | *str* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/chatmessagecontentitemvideo.md b/docs/models/chatmessagecontentitemvideo.md new file mode 100644 index 0000000..a997158 --- /dev/null +++ b/docs/models/chatmessagecontentitemvideo.md @@ -0,0 +1,9 @@ +# ChatMessageContentItemVideo + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | +| `type` | *Literal["input_video"]* | :heavy_check_mark: | N/A | +| `video_url` | [models.VideoURL](../models/videourl.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/chatmessagetokenlogprob.md b/docs/models/chatmessagetokenlogprob.md new file mode 100644 index 0000000..0d3d72a --- /dev/null +++ b/docs/models/chatmessagetokenlogprob.md @@ -0,0 +1,11 @@ +# ChatMessageTokenLogprob + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------- | -------------------------------------------------- | -------------------------------------------------- | -------------------------------------------------- | +| `token` | *str* | :heavy_check_mark: | N/A | +| `logprob` | *float* | :heavy_check_mark: | N/A | +| `bytes_` | List[*float*] | :heavy_check_mark: | N/A | +| `top_logprobs` | List[[models.TopLogprob](../models/toplogprob.md)] | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/chatmessagetokenlogprobs.md b/docs/models/chatmessagetokenlogprobs.md new file mode 100644 index 0000000..2ed48e4 --- /dev/null +++ b/docs/models/chatmessagetokenlogprobs.md @@ -0,0 +1,9 @@ +# ChatMessageTokenLogprobs + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | +| `content` | List[[models.ChatMessageTokenLogprob](../models/chatmessagetokenlogprob.md)] | :heavy_check_mark: | N/A | +| `refusal` | List[[models.ChatMessageTokenLogprob](../models/chatmessagetokenlogprob.md)] | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/chatmessagetoolcall.md b/docs/models/chatmessagetoolcall.md new file mode 100644 index 0000000..7780d0c --- /dev/null +++ b/docs/models/chatmessagetoolcall.md @@ -0,0 +1,10 @@ +# ChatMessageToolCall + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | +| `id` | *str* | :heavy_check_mark: | N/A | +| `type` | *Literal["function"]* | :heavy_check_mark: | N/A | +| `function` | [models.ChatMessageToolCallFunction](../models/chatmessagetoolcallfunction.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/chatmessagetoolcallfunction.md b/docs/models/chatmessagetoolcallfunction.md new file mode 100644 index 0000000..9ebac2d --- /dev/null +++ b/docs/models/chatmessagetoolcallfunction.md @@ -0,0 +1,9 @@ +# ChatMessageToolCallFunction + + +## Fields + +| Field | Type | Required | Description | +| ------------------ | ------------------ | ------------------ | ------------------ | +| `name` | *str* | :heavy_check_mark: | N/A | +| `arguments` | *str* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/chatresponse.md b/docs/models/chatresponse.md new file mode 100644 index 0000000..2a654c1 --- /dev/null +++ b/docs/models/chatresponse.md @@ -0,0 +1,14 @@ +# ChatResponse + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | +| `id` | *str* | :heavy_check_mark: | N/A | +| `choices` | List[[models.ChatResponseChoice](../models/chatresponsechoice.md)] | :heavy_check_mark: | N/A | +| `created` | *float* | :heavy_check_mark: | N/A | +| `model` | *str* | :heavy_check_mark: | N/A | +| `object` | *Literal["chat.completion"]* | :heavy_check_mark: | N/A | +| `system_fingerprint` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | +| `usage` | [Optional[models.ChatGenerationTokenUsage]](../models/chatgenerationtokenusage.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/chatresponsechoice.md b/docs/models/chatresponsechoice.md new file mode 100644 index 0000000..cb6932b --- /dev/null +++ b/docs/models/chatresponsechoice.md @@ -0,0 +1,11 @@ +# ChatResponseChoice + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | +| `finish_reason` | [Nullable[models.ChatCompletionFinishReason]](../models/chatcompletionfinishreason.md) | :heavy_check_mark: | N/A | +| `index` | *float* | :heavy_check_mark: | N/A | +| `message` | [models.AssistantMessage](../models/assistantmessage.md) | :heavy_check_mark: | N/A | +| `logprobs` | [OptionalNullable[models.ChatMessageTokenLogprobs]](../models/chatmessagetokenlogprobs.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/chatstreamingchoice.md b/docs/models/chatstreamingchoice.md new file mode 100644 index 0000000..6176cca --- /dev/null +++ b/docs/models/chatstreamingchoice.md @@ -0,0 +1,11 @@ +# ChatStreamingChoice + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | +| `delta` | [models.ChatStreamingMessageChunk](../models/chatstreamingmessagechunk.md) | :heavy_check_mark: | N/A | +| `finish_reason` | [Nullable[models.ChatCompletionFinishReason]](../models/chatcompletionfinishreason.md) | :heavy_check_mark: | N/A | +| `index` | *float* | :heavy_check_mark: | N/A | +| `logprobs` | [OptionalNullable[models.ChatMessageTokenLogprobs]](../models/chatmessagetokenlogprobs.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/chatstreamingmessagechunk.md b/docs/models/chatstreamingmessagechunk.md new file mode 100644 index 0000000..ce2730e --- /dev/null +++ b/docs/models/chatstreamingmessagechunk.md @@ -0,0 +1,12 @@ +# ChatStreamingMessageChunk + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | +| `role` | [Optional[models.ChatStreamingMessageChunkRole]](../models/chatstreamingmessagechunkrole.md) | :heavy_minus_sign: | N/A | +| `content` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | +| `reasoning` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | +| `refusal` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | +| `tool_calls` | List[[models.ChatStreamingMessageToolCall](../models/chatstreamingmessagetoolcall.md)] | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/chatstreamingmessagechunkrole.md b/docs/models/chatstreamingmessagechunkrole.md new file mode 100644 index 0000000..28535a6 --- /dev/null +++ b/docs/models/chatstreamingmessagechunkrole.md @@ -0,0 +1,8 @@ +# ChatStreamingMessageChunkRole + + +## Values + +| Name | Value | +| ----------- | ----------- | +| `ASSISTANT` | assistant | \ No newline at end of file diff --git a/docs/models/chatstreamingmessagetoolcall.md b/docs/models/chatstreamingmessagetoolcall.md new file mode 100644 index 0000000..dc26e85 --- /dev/null +++ b/docs/models/chatstreamingmessagetoolcall.md @@ -0,0 +1,11 @@ +# ChatStreamingMessageToolCall + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | +| `index` | *float* | :heavy_check_mark: | N/A | +| `id` | *Optional[str]* | :heavy_minus_sign: | N/A | +| `type` | *Optional[Literal["function"]]* | :heavy_minus_sign: | N/A | +| `function` | [Optional[models.ChatStreamingMessageToolCallFunction]](../models/chatstreamingmessagetoolcallfunction.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/chatstreamingmessagetoolcallfunction.md b/docs/models/chatstreamingmessagetoolcallfunction.md new file mode 100644 index 0000000..cd3af48 --- /dev/null +++ b/docs/models/chatstreamingmessagetoolcallfunction.md @@ -0,0 +1,9 @@ +# ChatStreamingMessageToolCallFunction + + +## Fields + +| Field | Type | Required | Description | +| ------------------ | ------------------ | ------------------ | ------------------ | +| `name` | *Optional[str]* | :heavy_minus_sign: | N/A | +| `arguments` | *Optional[str]* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/chatstreamingresponsechunk.md b/docs/models/chatstreamingresponsechunk.md new file mode 100644 index 0000000..3df63d1 --- /dev/null +++ b/docs/models/chatstreamingresponsechunk.md @@ -0,0 +1,8 @@ +# ChatStreamingResponseChunk + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | +| `data` | [models.ChatStreamingResponseChunkData](../models/chatstreamingresponsechunkdata.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/chatstreamingresponsechunkdata.md b/docs/models/chatstreamingresponsechunkdata.md new file mode 100644 index 0000000..8936ee3 --- /dev/null +++ b/docs/models/chatstreamingresponsechunkdata.md @@ -0,0 +1,15 @@ +# ChatStreamingResponseChunkData + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | +| `id` | *str* | :heavy_check_mark: | N/A | +| `choices` | List[[models.ChatStreamingChoice](../models/chatstreamingchoice.md)] | :heavy_check_mark: | N/A | +| `created` | *float* | :heavy_check_mark: | N/A | +| `model` | *str* | :heavy_check_mark: | N/A | +| `object` | *Literal["chat.completion.chunk"]* | :heavy_check_mark: | N/A | +| `system_fingerprint` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | +| `error` | [Optional[models.ChatStreamingResponseChunkError]](../models/chatstreamingresponsechunkerror.md) | :heavy_minus_sign: | N/A | +| `usage` | [Optional[models.ChatGenerationTokenUsage]](../models/chatgenerationtokenusage.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/chatstreamingresponsechunkerror.md b/docs/models/chatstreamingresponsechunkerror.md new file mode 100644 index 0000000..c394258 --- /dev/null +++ b/docs/models/chatstreamingresponsechunkerror.md @@ -0,0 +1,9 @@ +# ChatStreamingResponseChunkError + + +## Fields + +| Field | Type | Required | Description | +| ------------------ | ------------------ | ------------------ | ------------------ | +| `message` | *str* | :heavy_check_mark: | N/A | +| `code` | *float* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/chatstreamoptions.md b/docs/models/chatstreamoptions.md new file mode 100644 index 0000000..39c4b74 --- /dev/null +++ b/docs/models/chatstreamoptions.md @@ -0,0 +1,8 @@ +# ChatStreamOptions + + +## Fields + +| Field | Type | Required | Description | +| ------------------ | ------------------ | ------------------ | ------------------ | +| `include_usage` | *Optional[bool]* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/code.md b/docs/models/code.md new file mode 100644 index 0000000..9de20c8 --- /dev/null +++ b/docs/models/code.md @@ -0,0 +1,17 @@ +# Code + + +## Supported Types + +### `str` + +```python +value: str = /* values here */ +``` + +### `float` + +```python +value: float = /* values here */ +``` + diff --git a/docs/models/codeenum.md b/docs/models/codeenum.md new file mode 100644 index 0000000..7dd41ac --- /dev/null +++ b/docs/models/codeenum.md @@ -0,0 +1,25 @@ +# CodeEnum + + +## Values + +| Name | Value | +| -------------------------------- | -------------------------------- | +| `SERVER_ERROR` | server_error | +| `RATE_LIMIT_EXCEEDED` | rate_limit_exceeded | +| `INVALID_PROMPT` | invalid_prompt | +| `VECTOR_STORE_TIMEOUT` | vector_store_timeout | +| `INVALID_IMAGE` | invalid_image | +| `INVALID_IMAGE_FORMAT` | invalid_image_format | +| `INVALID_BASE64_IMAGE` | invalid_base64_image | +| `INVALID_IMAGE_URL` | invalid_image_url | +| `IMAGE_TOO_LARGE` | image_too_large | +| `IMAGE_TOO_SMALL` | image_too_small | +| `IMAGE_PARSE_ERROR` | image_parse_error | +| `IMAGE_CONTENT_POLICY_VIOLATION` | image_content_policy_violation | +| `INVALID_IMAGE_MODE` | invalid_image_mode | +| `IMAGE_FILE_TOO_LARGE` | image_file_too_large | +| `UNSUPPORTED_IMAGE_MEDIA_TYPE` | unsupported_image_media_type | +| `EMPTY_IMAGE_FILE` | empty_image_file | +| `FAILED_TO_DOWNLOAD_IMAGE` | failed_to_download_image | +| `IMAGE_FILE_NOT_FOUND` | image_file_not_found | \ No newline at end of file diff --git a/docs/models/completionchoice.md b/docs/models/completionchoice.md new file mode 100644 index 0000000..4e252b9 --- /dev/null +++ b/docs/models/completionchoice.md @@ -0,0 +1,11 @@ +# CompletionChoice + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | +| `text` | *str* | :heavy_check_mark: | N/A | +| `index` | *float* | :heavy_check_mark: | N/A | +| `logprobs` | [Nullable[models.CompletionLogprobs]](../models/completionlogprobs.md) | :heavy_check_mark: | N/A | +| `finish_reason` | [Nullable[models.CompletionFinishReason]](../models/completionfinishreason.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/completioncreateparams.md b/docs/models/completioncreateparams.md new file mode 100644 index 0000000..460abf3 --- /dev/null +++ b/docs/models/completioncreateparams.md @@ -0,0 +1,28 @@ +# CompletionCreateParams + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | +| `model` | *Optional[str]* | :heavy_minus_sign: | N/A | +| `models` | List[*str*] | :heavy_minus_sign: | N/A | +| `prompt` | [models.Prompt](../models/prompt.md) | :heavy_check_mark: | N/A | +| `best_of` | *OptionalNullable[int]* | :heavy_minus_sign: | N/A | +| `echo` | *OptionalNullable[bool]* | :heavy_minus_sign: | N/A | +| `frequency_penalty` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | +| `logit_bias` | Dict[str, *float*] | :heavy_minus_sign: | N/A | +| `logprobs` | *OptionalNullable[int]* | :heavy_minus_sign: | N/A | +| `max_tokens` | *OptionalNullable[int]* | :heavy_minus_sign: | N/A | +| `n` | *OptionalNullable[int]* | :heavy_minus_sign: | N/A | +| `presence_penalty` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | +| `seed` | *OptionalNullable[int]* | :heavy_minus_sign: | N/A | +| `stop` | [OptionalNullable[models.CompletionCreateParamsStop]](../models/completioncreateparamsstop.md) | :heavy_minus_sign: | N/A | +| `stream` | *Optional[bool]* | :heavy_minus_sign: | N/A | +| `stream_options` | [OptionalNullable[models.StreamOptions]](../models/streamoptions.md) | :heavy_minus_sign: | N/A | +| `suffix` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | +| `temperature` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | +| `top_p` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | +| `user` | *Optional[str]* | :heavy_minus_sign: | N/A | +| `metadata` | Dict[str, *str*] | :heavy_minus_sign: | N/A | +| `response_format` | [OptionalNullable[models.CompletionCreateParamsResponseFormatUnion]](../models/completioncreateparamsresponseformatunion.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/completioncreateparamsresponseformatjsonobject.md b/docs/models/completioncreateparamsresponseformatjsonobject.md new file mode 100644 index 0000000..a5c6d3b --- /dev/null +++ b/docs/models/completioncreateparamsresponseformatjsonobject.md @@ -0,0 +1,8 @@ +# CompletionCreateParamsResponseFormatJSONObject + + +## Fields + +| Field | Type | Required | Description | +| ------------------------ | ------------------------ | ------------------------ | ------------------------ | +| `type` | *Literal["json_object"]* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/completioncreateparamsresponseformatpython.md b/docs/models/completioncreateparamsresponseformatpython.md new file mode 100644 index 0000000..e0bcf67 --- /dev/null +++ b/docs/models/completioncreateparamsresponseformatpython.md @@ -0,0 +1,8 @@ +# CompletionCreateParamsResponseFormatPython + + +## Fields + +| Field | Type | Required | Description | +| ------------------- | ------------------- | ------------------- | ------------------- | +| `type` | *Literal["python"]* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/completioncreateparamsresponseformattext.md b/docs/models/completioncreateparamsresponseformattext.md new file mode 100644 index 0000000..bb80891 --- /dev/null +++ b/docs/models/completioncreateparamsresponseformattext.md @@ -0,0 +1,8 @@ +# CompletionCreateParamsResponseFormatText + + +## Fields + +| Field | Type | Required | Description | +| ------------------ | ------------------ | ------------------ | ------------------ | +| `type` | *Literal["text"]* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/completioncreateparamsresponseformatunion.md b/docs/models/completioncreateparamsresponseformatunion.md new file mode 100644 index 0000000..bc32737 --- /dev/null +++ b/docs/models/completioncreateparamsresponseformatunion.md @@ -0,0 +1,35 @@ +# CompletionCreateParamsResponseFormatUnion + + +## Supported Types + +### `models.CompletionCreateParamsResponseFormatText` + +```python +value: models.CompletionCreateParamsResponseFormatText = /* values here */ +``` + +### `models.CompletionCreateParamsResponseFormatJSONObject` + +```python +value: models.CompletionCreateParamsResponseFormatJSONObject = /* values here */ +``` + +### `models.ResponseFormatJSONSchema` + +```python +value: models.ResponseFormatJSONSchema = /* values here */ +``` + +### `models.ResponseFormatTextGrammar` + +```python +value: models.ResponseFormatTextGrammar = /* values here */ +``` + +### `models.CompletionCreateParamsResponseFormatPython` + +```python +value: models.CompletionCreateParamsResponseFormatPython = /* values here */ +``` + diff --git a/docs/models/completioncreateparamsstop.md b/docs/models/completioncreateparamsstop.md new file mode 100644 index 0000000..da48725 --- /dev/null +++ b/docs/models/completioncreateparamsstop.md @@ -0,0 +1,17 @@ +# CompletionCreateParamsStop + + +## Supported Types + +### `str` + +```python +value: str = /* values here */ +``` + +### `List[str]` + +```python +value: List[str] = /* values here */ +``` + diff --git a/docs/models/completionfinishreason.md b/docs/models/completionfinishreason.md new file mode 100644 index 0000000..4a4e249 --- /dev/null +++ b/docs/models/completionfinishreason.md @@ -0,0 +1,10 @@ +# CompletionFinishReason + + +## Values + +| Name | Value | +| ---------------- | ---------------- | +| `STOP` | stop | +| `LENGTH` | length | +| `CONTENT_FILTER` | content_filter | \ No newline at end of file diff --git a/docs/models/completionlogprobs.md b/docs/models/completionlogprobs.md new file mode 100644 index 0000000..9a8b558 --- /dev/null +++ b/docs/models/completionlogprobs.md @@ -0,0 +1,11 @@ +# CompletionLogprobs + + +## Fields + +| Field | Type | Required | Description | +| ------------------------ | ------------------------ | ------------------------ | ------------------------ | +| `tokens` | List[*str*] | :heavy_check_mark: | N/A | +| `token_logprobs` | List[*float*] | :heavy_check_mark: | N/A | +| `top_logprobs` | List[Dict[str, *float*]] | :heavy_check_mark: | N/A | +| `text_offset` | List[*float*] | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/completionresponse.md b/docs/models/completionresponse.md new file mode 100644 index 0000000..b1d5883 --- /dev/null +++ b/docs/models/completionresponse.md @@ -0,0 +1,14 @@ +# CompletionResponse + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------- | +| `id` | *str* | :heavy_check_mark: | N/A | +| `object` | *Literal["text_completion"]* | :heavy_check_mark: | N/A | +| `created` | *float* | :heavy_check_mark: | N/A | +| `model` | *str* | :heavy_check_mark: | N/A | +| `system_fingerprint` | *Optional[str]* | :heavy_minus_sign: | N/A | +| `choices` | List[[models.CompletionChoice](../models/completionchoice.md)] | :heavy_check_mark: | N/A | +| `usage` | [Optional[models.CompletionUsage]](../models/completionusage.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/completiontokensdetails.md b/docs/models/completiontokensdetails.md new file mode 100644 index 0000000..dcac003 --- /dev/null +++ b/docs/models/completiontokensdetails.md @@ -0,0 +1,11 @@ +# CompletionTokensDetails + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------- | ---------------------------- | ---------------------------- | ---------------------------- | +| `reasoning_tokens` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | +| `audio_tokens` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | +| `accepted_prediction_tokens` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | +| `rejected_prediction_tokens` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/completionusage.md b/docs/models/completionusage.md new file mode 100644 index 0000000..e9e3983 --- /dev/null +++ b/docs/models/completionusage.md @@ -0,0 +1,10 @@ +# CompletionUsage + + +## Fields + +| Field | Type | Required | Description | +| ------------------- | ------------------- | ------------------- | ------------------- | +| `prompt_tokens` | *float* | :heavy_check_mark: | N/A | +| `completion_tokens` | *float* | :heavy_check_mark: | N/A | +| `total_tokens` | *float* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/costdetails.md b/docs/models/costdetails.md new file mode 100644 index 0000000..ada009c --- /dev/null +++ b/docs/models/costdetails.md @@ -0,0 +1,10 @@ +# CostDetails + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------- | -------------------------------- | -------------------------------- | -------------------------------- | +| `upstream_inference_cost` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | +| `upstream_inference_input_cost` | *float* | :heavy_check_mark: | N/A | +| `upstream_inference_output_cost` | *float* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/createauthkeyscodecodechallengemethod.md b/docs/models/createauthkeyscodecodechallengemethod.md new file mode 100644 index 0000000..cd496b7 --- /dev/null +++ b/docs/models/createauthkeyscodecodechallengemethod.md @@ -0,0 +1,11 @@ +# CreateAuthKeysCodeCodeChallengeMethod + +The method used to generate the code challenge + + +## Values + +| Name | Value | +| ------- | ------- | +| `S256` | S256 | +| `PLAIN` | plain | \ No newline at end of file diff --git a/docs/models/createauthkeyscodedata.md b/docs/models/createauthkeyscodedata.md new file mode 100644 index 0000000..81adde9 --- /dev/null +++ b/docs/models/createauthkeyscodedata.md @@ -0,0 +1,12 @@ +# CreateAuthKeysCodeData + +Auth code data + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------------------------- | -------------------------------------------------------- | -------------------------------------------------------- | -------------------------------------------------------- | -------------------------------------------------------- | +| `id` | *str* | :heavy_check_mark: | The authorization code ID to use in the exchange request | auth_code_xyz789 | +| `app_id` | *float* | :heavy_check_mark: | The application ID associated with this auth code | 12345 | +| `created_at` | *str* | :heavy_check_mark: | ISO 8601 timestamp of when the auth code was created | 2025-08-24T10:30:00Z | \ No newline at end of file diff --git a/docs/models/createauthkeyscoderequest.md b/docs/models/createauthkeyscoderequest.md new file mode 100644 index 0000000..f27502b --- /dev/null +++ b/docs/models/createauthkeyscoderequest.md @@ -0,0 +1,12 @@ +# CreateAuthKeysCodeRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | +| `callback_url` | *str* | :heavy_check_mark: | The callback URL to redirect to after authorization. Note, only https URLs on ports 443 and 3000 are allowed. | https://myapp.com/auth/callback | +| `code_challenge` | *Optional[str]* | :heavy_minus_sign: | PKCE code challenge for enhanced security | E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM | +| `code_challenge_method` | [Optional[models.CreateAuthKeysCodeCodeChallengeMethod]](../models/createauthkeyscodecodechallengemethod.md) | :heavy_minus_sign: | The method used to generate the code challenge | S256 | +| `limit` | *Optional[float]* | :heavy_minus_sign: | Credit limit for the API key to be created | 100 | +| `expires_at` | [date](https://docs.python.org/3/library/datetime.html#date-objects) | :heavy_minus_sign: | Optional expiration time for the API key to be created | | \ No newline at end of file diff --git a/docs/models/createauthkeyscoderesponse.md b/docs/models/createauthkeyscoderesponse.md new file mode 100644 index 0000000..6b56890 --- /dev/null +++ b/docs/models/createauthkeyscoderesponse.md @@ -0,0 +1,10 @@ +# CreateAuthKeysCodeResponse + +Successfully created authorization code + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | +| `data` | [models.CreateAuthKeysCodeData](../models/createauthkeyscodedata.md) | :heavy_check_mark: | Auth code data | {
"id": "auth_code_xyz789",
"app_id": 12345,
"created_at": "2025-08-24T10:30:00Z"
} | \ No newline at end of file diff --git a/docs/models/createchargerequest.md b/docs/models/createchargerequest.md new file mode 100644 index 0000000..f532eef --- /dev/null +++ b/docs/models/createchargerequest.md @@ -0,0 +1,12 @@ +# CreateChargeRequest + +Create a Coinbase charge for crypto payment + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------- | -------------------------------------- | -------------------------------------- | -------------------------------------- | +| `amount` | *float* | :heavy_check_mark: | N/A | +| `sender` | *str* | :heavy_check_mark: | N/A | +| `chain_id` | [models.ChainID](../models/chainid.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/createcoinbasechargedata.md b/docs/models/createcoinbasechargedata.md new file mode 100644 index 0000000..d4c4385 --- /dev/null +++ b/docs/models/createcoinbasechargedata.md @@ -0,0 +1,11 @@ +# CreateCoinbaseChargeData + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | +| `id` | *str* | :heavy_check_mark: | N/A | +| `created_at` | *str* | :heavy_check_mark: | N/A | +| `expires_at` | *str* | :heavy_check_mark: | N/A | +| `web3_data` | [models.Web3Data](../models/web3data.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/createcoinbasechargeresponse.md b/docs/models/createcoinbasechargeresponse.md new file mode 100644 index 0000000..49bd60a --- /dev/null +++ b/docs/models/createcoinbasechargeresponse.md @@ -0,0 +1,10 @@ +# CreateCoinbaseChargeResponse + +Returns the calldata to fulfill the transaction + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | +| `data` | [models.CreateCoinbaseChargeData](../models/createcoinbasechargedata.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/createcoinbasechargesecurity.md b/docs/models/createcoinbasechargesecurity.md new file mode 100644 index 0000000..7d58a21 --- /dev/null +++ b/docs/models/createcoinbasechargesecurity.md @@ -0,0 +1,8 @@ +# CreateCoinbaseChargeSecurity + + +## Fields + +| Field | Type | Required | Description | +| ------------------ | ------------------ | ------------------ | ------------------ | +| `bearer` | *str* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/createembeddingsdata.md b/docs/models/createembeddingsdata.md new file mode 100644 index 0000000..27f78d9 --- /dev/null +++ b/docs/models/createembeddingsdata.md @@ -0,0 +1,10 @@ +# CreateEmbeddingsData + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------ | ------------------------------------------------------ | ------------------------------------------------------ | ------------------------------------------------------ | +| `object` | [models.ObjectEmbedding](../models/objectembedding.md) | :heavy_check_mark: | N/A | +| `embedding` | [models.Embedding](../models/embedding.md) | :heavy_check_mark: | N/A | +| `index` | *Optional[float]* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/createembeddingsdatacollection.md b/docs/models/createembeddingsdatacollection.md new file mode 100644 index 0000000..ab20171 --- /dev/null +++ b/docs/models/createembeddingsdatacollection.md @@ -0,0 +1,14 @@ +# CreateEmbeddingsDataCollection + +Data collection setting. If no available model provider meets the requirement, your request will return an error. +- allow: (default) allow providers which store user data non-transiently and may train on it +- deny: use only providers which do not collect user data. + + + +## Values + +| Name | Value | +| ------- | ------- | +| `DENY` | deny | +| `ALLOW` | allow | \ No newline at end of file diff --git a/docs/models/createembeddingsignore.md b/docs/models/createembeddingsignore.md new file mode 100644 index 0000000..a71ce57 --- /dev/null +++ b/docs/models/createembeddingsignore.md @@ -0,0 +1,17 @@ +# CreateEmbeddingsIgnore + + +## Supported Types + +### `models.ProviderName` + +```python +value: models.ProviderName = /* values here */ +``` + +### `str` + +```python +value: str = /* values here */ +``` + diff --git a/docs/models/createembeddingsmaxprice.md b/docs/models/createembeddingsmaxprice.md new file mode 100644 index 0000000..80e9618 --- /dev/null +++ b/docs/models/createembeddingsmaxprice.md @@ -0,0 +1,14 @@ +# CreateEmbeddingsMaxPrice + +The object specifying the maximum price you want to pay for this request. USD price per million tokens, for prompt and completion. + + +## Fields + +| Field | Type | Required | Description | +| --------------------------------------------------------- | --------------------------------------------------------- | --------------------------------------------------------- | --------------------------------------------------------- | +| `prompt` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number | +| `completion` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number | +| `image` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number | +| `audio` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number | +| `request` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number | \ No newline at end of file diff --git a/docs/models/createembeddingsobject.md b/docs/models/createembeddingsobject.md new file mode 100644 index 0000000..2512c32 --- /dev/null +++ b/docs/models/createembeddingsobject.md @@ -0,0 +1,8 @@ +# CreateEmbeddingsObject + + +## Values + +| Name | Value | +| ------ | ------ | +| `LIST` | list | \ No newline at end of file diff --git a/docs/models/createembeddingsonly.md b/docs/models/createembeddingsonly.md new file mode 100644 index 0000000..2ec1289 --- /dev/null +++ b/docs/models/createembeddingsonly.md @@ -0,0 +1,17 @@ +# CreateEmbeddingsOnly + + +## Supported Types + +### `models.ProviderName` + +```python +value: models.ProviderName = /* values here */ +``` + +### `str` + +```python +value: str = /* values here */ +``` + diff --git a/docs/models/createembeddingsorder.md b/docs/models/createembeddingsorder.md new file mode 100644 index 0000000..ffaa8ac --- /dev/null +++ b/docs/models/createembeddingsorder.md @@ -0,0 +1,17 @@ +# CreateEmbeddingsOrder + + +## Supported Types + +### `models.ProviderName` + +```python +value: models.ProviderName = /* values here */ +``` + +### `str` + +```python +value: str = /* values here */ +``` + diff --git a/docs/models/createembeddingsprovider.md b/docs/models/createembeddingsprovider.md new file mode 100644 index 0000000..0491b6a --- /dev/null +++ b/docs/models/createembeddingsprovider.md @@ -0,0 +1,18 @@ +# CreateEmbeddingsProvider + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `allow_fallbacks` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to allow backup providers to serve requests
- true: (default) when the primary provider (or your custom providers in "order") is unavailable, use the next best provider.
- false: use only the primary/custom provider, and return the upstream error if it's unavailable.
| | +| `require_parameters` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to filter providers to only those that support the parameters you've provided. If this setting is omitted or set to false, then providers will receive only the parameters they support, and ignore the rest. | | +| `data_collection` | [OptionalNullable[models.CreateEmbeddingsDataCollection]](../models/createembeddingsdatacollection.md) | :heavy_minus_sign: | Data collection setting. If no available model provider meets the requirement, your request will return an error.
- allow: (default) allow providers which store user data non-transiently and may train on it
- deny: use only providers which do not collect user data.
| deny | +| `zdr` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to restrict routing to only ZDR (Zero Data Retention) endpoints. When true, only endpoints that do not retain prompts will be used. | true | +| `enforce_distillable_text` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to restrict routing to only models that allow text distillation. When true, only models where the author has allowed distillation will be used. | true | +| `order` | List[[models.CreateEmbeddingsOrder](../models/createembeddingsorder.md)] | :heavy_minus_sign: | An ordered list of provider slugs. The router will attempt to use the first provider in the subset of this list that supports your requested model, and fall back to the next if it is unavailable. If no providers are available, the request will fail with an error message. | | +| `only` | List[[models.CreateEmbeddingsOnly](../models/createembeddingsonly.md)] | :heavy_minus_sign: | List of provider slugs to allow. If provided, this list is merged with your account-wide allowed provider settings for this request. | | +| `ignore` | List[[models.CreateEmbeddingsIgnore](../models/createembeddingsignore.md)] | :heavy_minus_sign: | List of provider slugs to ignore. If provided, this list is merged with your account-wide ignored provider settings for this request. | | +| `quantizations` | List[[models.Quantization](../models/quantization.md)] | :heavy_minus_sign: | A list of quantization levels to filter the provider by. | | +| `sort` | [OptionalNullable[models.CreateEmbeddingsSort]](../models/createembeddingssort.md) | :heavy_minus_sign: | The sorting strategy to use for this request, if "order" is not specified. When set, no load balancing is performed. | price | +| `max_price` | [Optional[models.CreateEmbeddingsMaxPrice]](../models/createembeddingsmaxprice.md) | :heavy_minus_sign: | The object specifying the maximum price you want to pay for this request. USD price per million tokens, for prompt and completion. | | \ No newline at end of file diff --git a/docs/models/createembeddingsrequest.md b/docs/models/createembeddingsrequest.md new file mode 100644 index 0000000..77d58ac --- /dev/null +++ b/docs/models/createembeddingsrequest.md @@ -0,0 +1,12 @@ +# CreateEmbeddingsRequest + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | +| `input` | [models.Input](../models/input.md) | :heavy_check_mark: | N/A | +| `model` | *str* | :heavy_check_mark: | N/A | +| `provider` | [Optional[models.CreateEmbeddingsProvider]](../models/createembeddingsprovider.md) | :heavy_minus_sign: | N/A | +| `encoding_format` | [Optional[models.EncodingFormat]](../models/encodingformat.md) | :heavy_minus_sign: | N/A | +| `user` | *Optional[str]* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/createembeddingsresponse.md b/docs/models/createembeddingsresponse.md new file mode 100644 index 0000000..0cfb1ef --- /dev/null +++ b/docs/models/createembeddingsresponse.md @@ -0,0 +1,17 @@ +# CreateEmbeddingsResponse + + +## Supported Types + +### `models.CreateEmbeddingsResponseBody` + +```python +value: models.CreateEmbeddingsResponseBody = /* values here */ +``` + +### `str` + +```python +value: str = /* values here */ +``` + diff --git a/docs/models/createembeddingsresponsebody.md b/docs/models/createembeddingsresponsebody.md new file mode 100644 index 0000000..fa578ac --- /dev/null +++ b/docs/models/createembeddingsresponsebody.md @@ -0,0 +1,14 @@ +# CreateEmbeddingsResponseBody + +Embedding response + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | +| `id` | *Optional[str]* | :heavy_minus_sign: | N/A | +| `object` | [models.CreateEmbeddingsObject](../models/createembeddingsobject.md) | :heavy_check_mark: | N/A | +| `data` | List[[models.CreateEmbeddingsData](../models/createembeddingsdata.md)] | :heavy_check_mark: | N/A | +| `model` | *str* | :heavy_check_mark: | N/A | +| `usage` | [Optional[models.Usage]](../models/usage.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/createembeddingssort.md b/docs/models/createembeddingssort.md new file mode 100644 index 0000000..6043e0c --- /dev/null +++ b/docs/models/createembeddingssort.md @@ -0,0 +1,12 @@ +# CreateEmbeddingsSort + +The sorting strategy to use for this request, if "order" is not specified. When set, no load balancing is performed. + + +## Values + +| Name | Value | +| ------------ | ------------ | +| `PRICE` | price | +| `THROUGHPUT` | throughput | +| `LATENCY` | latency | \ No newline at end of file diff --git a/docs/models/createkeysdata.md b/docs/models/createkeysdata.md new file mode 100644 index 0000000..33e9681 --- /dev/null +++ b/docs/models/createkeysdata.md @@ -0,0 +1,28 @@ +# CreateKeysData + +The created API key information + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | +| `hash` | *str* | :heavy_check_mark: | Unique hash identifier for the API key | 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 | +| `name` | *str* | :heavy_check_mark: | Name of the API key | My Production Key | +| `label` | *str* | :heavy_check_mark: | Human-readable label for the API key | Production API Key | +| `disabled` | *bool* | :heavy_check_mark: | Whether the API key is disabled | false | +| `limit` | *Nullable[float]* | :heavy_check_mark: | Spending limit for the API key in USD | 100 | +| `limit_remaining` | *Nullable[float]* | :heavy_check_mark: | Remaining spending limit in USD | 74.5 | +| `limit_reset` | *Nullable[str]* | :heavy_check_mark: | Type of limit reset for the API key | monthly | +| `include_byok_in_limit` | *bool* | :heavy_check_mark: | Whether to include external BYOK usage in the credit limit | false | +| `usage` | *float* | :heavy_check_mark: | Total OpenRouter credit usage (in USD) for the API key | 25.5 | +| `usage_daily` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC day | 25.5 | +| `usage_weekly` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday) | 25.5 | +| `usage_monthly` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC month | 25.5 | +| `byok_usage` | *float* | :heavy_check_mark: | Total external BYOK usage (in USD) for the API key | 17.38 | +| `byok_usage_daily` | *float* | :heavy_check_mark: | External BYOK usage (in USD) for the current UTC day | 17.38 | +| `byok_usage_weekly` | *float* | :heavy_check_mark: | External BYOK usage (in USD) for the current UTC week (Monday-Sunday) | 17.38 | +| `byok_usage_monthly` | *float* | :heavy_check_mark: | External BYOK usage (in USD) for current UTC month | 17.38 | +| `created_at` | *str* | :heavy_check_mark: | ISO 8601 timestamp of when the API key was created | 2025-08-24T10:30:00Z | +| `updated_at` | *Nullable[str]* | :heavy_check_mark: | ISO 8601 timestamp of when the API key was last updated | 2025-08-24T15:45:00Z | +| `expires_at` | [date](https://docs.python.org/3/library/datetime.html#date-objects) | :heavy_minus_sign: | ISO 8601 UTC timestamp when the API key expires, or null if no expiration | 2027-12-31T23:59:59Z | \ No newline at end of file diff --git a/docs/models/createkeyslimitreset.md b/docs/models/createkeyslimitreset.md new file mode 100644 index 0000000..5d1659c --- /dev/null +++ b/docs/models/createkeyslimitreset.md @@ -0,0 +1,12 @@ +# CreateKeysLimitReset + +Type of limit reset for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday. + + +## Values + +| Name | Value | +| --------- | --------- | +| `DAILY` | daily | +| `WEEKLY` | weekly | +| `MONTHLY` | monthly | \ No newline at end of file diff --git a/docs/models/createkeysrequest.md b/docs/models/createkeysrequest.md new file mode 100644 index 0000000..bd3d811 --- /dev/null +++ b/docs/models/createkeysrequest.md @@ -0,0 +1,12 @@ +# CreateKeysRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `name` | *str* | :heavy_check_mark: | Name for the new API key | My New API Key | +| `limit` | *OptionalNullable[float]* | :heavy_minus_sign: | Optional spending limit for the API key in USD | 50 | +| `limit_reset` | [OptionalNullable[models.CreateKeysLimitReset]](../models/createkeyslimitreset.md) | :heavy_minus_sign: | Type of limit reset for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday. | monthly | +| `include_byok_in_limit` | *Optional[bool]* | :heavy_minus_sign: | Whether to include BYOK usage in the limit | true | +| `expires_at` | [date](https://docs.python.org/3/library/datetime.html#date-objects) | :heavy_minus_sign: | Optional ISO 8601 UTC timestamp when the API key should expire. Must be UTC, other timezones will be rejected | 2027-12-31T23:59:59Z | \ No newline at end of file diff --git a/docs/models/createkeysresponse.md b/docs/models/createkeysresponse.md new file mode 100644 index 0000000..376a9b8 --- /dev/null +++ b/docs/models/createkeysresponse.md @@ -0,0 +1,11 @@ +# CreateKeysResponse + +API key created successfully + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `data` | [models.CreateKeysData](../models/createkeysdata.md) | :heavy_check_mark: | The created API key information | {
"hash": "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",
"name": "My Production Key",
"label": "Production API Key",
"disabled": false,
"limit": 100,
"limit_remaining": 74.5,
"limit_reset": "monthly",
"include_byok_in_limit": false,
"usage": 25.5,
"usage_daily": 25.5,
"usage_weekly": 25.5,
"usage_monthly": 25.5,
"byok_usage": 17.38,
"byok_usage_daily": 17.38,
"byok_usage_weekly": 17.38,
"byok_usage_monthly": 17.38,
"created_at": "2025-08-24T10:30:00Z",
"updated_at": "2025-08-24T15:45:00Z",
"expires_at": "2027-12-31T23:59:59Z"
} | +| `key` | *str* | :heavy_check_mark: | The actual API key string (only shown once) | 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 | \ No newline at end of file diff --git a/docs/models/createresponsesresponse.md b/docs/models/createresponsesresponse.md new file mode 100644 index 0000000..7efe200 --- /dev/null +++ b/docs/models/createresponsesresponse.md @@ -0,0 +1,17 @@ +# CreateResponsesResponse + + +## Supported Types + +### `models.OpenResponsesNonStreamingResponse` + +```python +value: models.OpenResponsesNonStreamingResponse = /* values here */ +``` + +### `Union[eventstreaming.EventStream[models.CreateResponsesResponseBody], eventstreaming.EventStreamAsync[models.CreateResponsesResponseBody]]` + +```python +value: Union[eventstreaming.EventStream[models.CreateResponsesResponseBody], eventstreaming.EventStreamAsync[models.CreateResponsesResponseBody]] = /* values here */ +``` + diff --git a/docs/models/createresponsesresponsebody.md b/docs/models/createresponsesresponsebody.md new file mode 100644 index 0000000..407e563 --- /dev/null +++ b/docs/models/createresponsesresponsebody.md @@ -0,0 +1,10 @@ +# CreateResponsesResponseBody + +Successful response + + +## Fields + +| Field | Type | Required | Description | Example | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `data` | [models.OpenResponsesStreamEvent](../models/openresponsesstreamevent.md) | :heavy_check_mark: | Union of all possible event types emitted during response streaming | {
"type": "response.created",
"response": {
"id": "resp-abc123",
"object": "response",
"created_at": 1704067200,
"model": "gpt-4",
"status": "in_progress",
"output": [],
"tools": [],
"tool_choice": "auto",
"parallel_tool_calls": true,
"error": null,
"incomplete_details": null,
"metadata": null,
"instructions": null,
"temperature": null,
"top_p": null,
"max_output_tokens": null
},
"sequence_number": 0
} | \ No newline at end of file diff --git a/docs/models/datacollection.md b/docs/models/datacollection.md new file mode 100644 index 0000000..bb07fc4 --- /dev/null +++ b/docs/models/datacollection.md @@ -0,0 +1,14 @@ +# DataCollection + +Data collection setting. If no available model provider meets the requirement, your request will return an error. +- allow: (default) allow providers which store user data non-transiently and may train on it +- deny: use only providers which do not collect user data. + + + +## Values + +| Name | Value | +| ------- | ------- | +| `DENY` | deny | +| `ALLOW` | allow | \ No newline at end of file diff --git a/docs/models/defaultparameters.md b/docs/models/defaultparameters.md new file mode 100644 index 0000000..b343b60 --- /dev/null +++ b/docs/models/defaultparameters.md @@ -0,0 +1,12 @@ +# DefaultParameters + +Default parameters for this model + + +## Fields + +| Field | Type | Required | Description | +| ------------------------- | ------------------------- | ------------------------- | ------------------------- | +| `temperature` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | +| `top_p` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | +| `frequency_penalty` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/deletekeysrequest.md b/docs/models/deletekeysrequest.md new file mode 100644 index 0000000..b3fc3f3 --- /dev/null +++ b/docs/models/deletekeysrequest.md @@ -0,0 +1,8 @@ +# DeleteKeysRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | +| `hash` | *str* | :heavy_check_mark: | The hash identifier of the API key to delete | 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 | \ No newline at end of file diff --git a/docs/models/deletekeysresponse.md b/docs/models/deletekeysresponse.md new file mode 100644 index 0000000..cc7cddb --- /dev/null +++ b/docs/models/deletekeysresponse.md @@ -0,0 +1,10 @@ +# DeleteKeysResponse + +API key deleted successfully + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------- | ----------------------------------------- | ----------------------------------------- | ----------------------------------------- | ----------------------------------------- | +| `deleted` | *Literal[True]* | :heavy_check_mark: | Confirmation that the API key was deleted | true | \ No newline at end of file diff --git a/docs/models/edgenetworktimeoutresponseerrordata.md b/docs/models/edgenetworktimeoutresponseerrordata.md new file mode 100644 index 0000000..f460fe4 --- /dev/null +++ b/docs/models/edgenetworktimeoutresponseerrordata.md @@ -0,0 +1,12 @@ +# EdgeNetworkTimeoutResponseErrorData + +Error data for EdgeNetworkTimeoutResponse + + +## Fields + +| Field | Type | Required | Description | +| -------------------------- | -------------------------- | -------------------------- | -------------------------- | +| `code` | *int* | :heavy_check_mark: | N/A | +| `message` | *str* | :heavy_check_mark: | N/A | +| `metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/effort.md b/docs/models/effort.md new file mode 100644 index 0000000..b4f7dbb --- /dev/null +++ b/docs/models/effort.md @@ -0,0 +1,11 @@ +# Effort + + +## Values + +| Name | Value | +| --------- | --------- | +| `MINIMAL` | minimal | +| `LOW` | low | +| `MEDIUM` | medium | +| `HIGH` | high | \ No newline at end of file diff --git a/docs/models/embedding.md b/docs/models/embedding.md new file mode 100644 index 0000000..59f08e3 --- /dev/null +++ b/docs/models/embedding.md @@ -0,0 +1,17 @@ +# Embedding + + +## Supported Types + +### `List[float]` + +```python +value: List[float] = /* values here */ +``` + +### `str` + +```python +value: str = /* values here */ +``` + diff --git a/docs/models/encodingformat.md b/docs/models/encodingformat.md new file mode 100644 index 0000000..1083105 --- /dev/null +++ b/docs/models/encodingformat.md @@ -0,0 +1,17 @@ +# EncodingFormat + + +## Supported Types + +### `models.EncodingFormatFloat` + +```python +value: models.EncodingFormatFloat = /* values here */ +``` + +### `models.EncodingFormatBase64` + +```python +value: models.EncodingFormatBase64 = /* values here */ +``` + diff --git a/docs/models/encodingformatbase64.md b/docs/models/encodingformatbase64.md new file mode 100644 index 0000000..859a006 --- /dev/null +++ b/docs/models/encodingformatbase64.md @@ -0,0 +1,8 @@ +# EncodingFormatBase64 + + +## Values + +| Name | Value | +| -------- | -------- | +| `BASE64` | base64 | \ No newline at end of file diff --git a/docs/models/encodingformatfloat.md b/docs/models/encodingformatfloat.md new file mode 100644 index 0000000..4d95449 --- /dev/null +++ b/docs/models/encodingformatfloat.md @@ -0,0 +1,8 @@ +# EncodingFormatFloat + + +## Values + +| Name | Value | +| ------- | ------- | +| `FLOAT` | float | \ No newline at end of file diff --git a/docs/models/endpointslistendpointsresponse.md b/docs/models/endpointslistendpointsresponse.md new file mode 100644 index 0000000..bfd5534 --- /dev/null +++ b/docs/models/endpointslistendpointsresponse.md @@ -0,0 +1,10 @@ +# EndpointsListEndpointsResponse + +Returns a list of endpoints + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `data` | [models.ListEndpointsResponse](../models/listendpointsresponse.md) | :heavy_check_mark: | List of available endpoints for a model | {
"id": "openai/gpt-4",
"name": "GPT-4",
"created": 1692901234,
"description": "GPT-4 is a large multimodal model that can solve difficult problems with greater accuracy.",
"architecture": {
"tokenizer": "GPT",
"instruct_type": "chatml",
"modality": "text-\u003etext",
"input_modalities": [
"text"
],
"output_modalities": [
"text"
]
},
"endpoints": [
{
"name": "OpenAI: GPT-4",
"model_name": "GPT-4",
"context_length": 8192,
"pricing": {
"prompt": "0.00003",
"completion": "0.00006",
"request": "0",
"image": "0"
},
"provider_name": "OpenAI",
"tag": "openai",
"quantization": "fp16",
"max_completion_tokens": 4096,
"max_prompt_tokens": 8192,
"supported_parameters": [
"temperature",
"top_p",
"max_tokens",
"frequency_penalty",
"presence_penalty"
],
"status": "default",
"uptime_last_30m": 99.5,
"supports_implicit_caching": true
}
]
} | \ No newline at end of file diff --git a/docs/models/endpointstatus.md b/docs/models/endpointstatus.md new file mode 100644 index 0000000..dd89005 --- /dev/null +++ b/docs/models/endpointstatus.md @@ -0,0 +1,13 @@ +# EndpointStatus + + +## Values + +| Name | Value | +| ---------- | ---------- | +| `ZERO` | 0 | +| `MINUS_1` | -1 | +| `MINUS_2` | -2 | +| `MINUS_3` | -3 | +| `MINUS_5` | -5 | +| `MINUS_10` | -10 | \ No newline at end of file diff --git a/docs/models/engine.md b/docs/models/engine.md new file mode 100644 index 0000000..fcea19c --- /dev/null +++ b/docs/models/engine.md @@ -0,0 +1,9 @@ +# Engine + + +## Values + +| Name | Value | +| -------- | -------- | +| `NATIVE` | native | +| `EXA` | exa | \ No newline at end of file diff --git a/docs/models/exchangeauthcodeforapikeycodechallengemethod.md b/docs/models/exchangeauthcodeforapikeycodechallengemethod.md new file mode 100644 index 0000000..eec31e8 --- /dev/null +++ b/docs/models/exchangeauthcodeforapikeycodechallengemethod.md @@ -0,0 +1,11 @@ +# ExchangeAuthCodeForAPIKeyCodeChallengeMethod + +The method used to generate the code challenge + + +## Values + +| Name | Value | +| ------- | ------- | +| `S256` | S256 | +| `PLAIN` | plain | \ No newline at end of file diff --git a/docs/models/exchangeauthcodeforapikeyrequest.md b/docs/models/exchangeauthcodeforapikeyrequest.md new file mode 100644 index 0000000..a189fbc --- /dev/null +++ b/docs/models/exchangeauthcodeforapikeyrequest.md @@ -0,0 +1,10 @@ +# ExchangeAuthCodeForAPIKeyRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | +| `code` | *str* | :heavy_check_mark: | The authorization code received from the OAuth redirect | auth_code_abc123def456 | +| `code_verifier` | *Optional[str]* | :heavy_minus_sign: | The code verifier if code_challenge was used in the authorization request | dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk | +| `code_challenge_method` | [OptionalNullable[models.ExchangeAuthCodeForAPIKeyCodeChallengeMethod]](../models/exchangeauthcodeforapikeycodechallengemethod.md) | :heavy_minus_sign: | The method used to generate the code challenge | S256 | \ No newline at end of file diff --git a/docs/models/exchangeauthcodeforapikeyresponse.md b/docs/models/exchangeauthcodeforapikeyresponse.md new file mode 100644 index 0000000..11975e0 --- /dev/null +++ b/docs/models/exchangeauthcodeforapikeyresponse.md @@ -0,0 +1,11 @@ +# ExchangeAuthCodeForAPIKeyResponse + +Successfully exchanged code for an API key + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | +| `key` | *str* | :heavy_check_mark: | The API key to use for OpenRouter requests | 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 | +| `user_id` | *Nullable[str]* | :heavy_check_mark: | User ID associated with the API key | user_2yOPcMpKoQhcd4bVgSMlELRaIah | \ No newline at end of file diff --git a/docs/models/filecitation.md b/docs/models/filecitation.md new file mode 100644 index 0000000..b2eb3fb --- /dev/null +++ b/docs/models/filecitation.md @@ -0,0 +1,11 @@ +# FileCitation + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------- | -------------------------------------------------------- | -------------------------------------------------------- | -------------------------------------------------------- | +| `type` | [models.FileCitationType](../models/filecitationtype.md) | :heavy_check_mark: | N/A | +| `file_id` | *str* | :heavy_check_mark: | N/A | +| `filename` | *str* | :heavy_check_mark: | N/A | +| `index` | *float* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/filecitationtype.md b/docs/models/filecitationtype.md new file mode 100644 index 0000000..787e254 --- /dev/null +++ b/docs/models/filecitationtype.md @@ -0,0 +1,8 @@ +# FileCitationType + + +## Values + +| Name | Value | +| --------------- | --------------- | +| `FILE_CITATION` | file_citation | \ No newline at end of file diff --git a/docs/models/filepath.md b/docs/models/filepath.md new file mode 100644 index 0000000..c237eac --- /dev/null +++ b/docs/models/filepath.md @@ -0,0 +1,10 @@ +# FilePath + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------ | ------------------------------------------------ | ------------------------------------------------ | ------------------------------------------------ | +| `type` | [models.FilePathType](../models/filepathtype.md) | :heavy_check_mark: | N/A | +| `file_id` | *str* | :heavy_check_mark: | N/A | +| `index` | *float* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/filepathtype.md b/docs/models/filepathtype.md new file mode 100644 index 0000000..8edc6ad --- /dev/null +++ b/docs/models/filepathtype.md @@ -0,0 +1,8 @@ +# FilePathType + + +## Values + +| Name | Value | +| ----------- | ----------- | +| `FILE_PATH` | file_path | \ No newline at end of file diff --git a/docs/models/forbiddenresponseerrordata.md b/docs/models/forbiddenresponseerrordata.md new file mode 100644 index 0000000..37e2199 --- /dev/null +++ b/docs/models/forbiddenresponseerrordata.md @@ -0,0 +1,12 @@ +# ForbiddenResponseErrorData + +Error data for ForbiddenResponse + + +## Fields + +| Field | Type | Required | Description | +| -------------------------- | -------------------------- | -------------------------- | -------------------------- | +| `code` | *int* | :heavy_check_mark: | N/A | +| `message` | *str* | :heavy_check_mark: | N/A | +| `metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/getcreditsresponse.md b/docs/models/getcreditsresponse.md new file mode 100644 index 0000000..c52bc01 --- /dev/null +++ b/docs/models/getcreditsresponse.md @@ -0,0 +1,9 @@ +# GetCreditsResponse + +Total credits purchased and used + + +## Fields + +| Field | Type | Required | Description | +| ----------- | ----------- | ----------- | ----------- | \ No newline at end of file diff --git a/docs/models/getcurrentkeydata.md b/docs/models/getcurrentkeydata.md new file mode 100644 index 0000000..267c3eb --- /dev/null +++ b/docs/models/getcurrentkeydata.md @@ -0,0 +1,26 @@ +# GetCurrentKeyData + +Current API key information + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `label` | *str* | :heavy_check_mark: | Human-readable label for the API key | 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 | +| `limit` | *Nullable[float]* | :heavy_check_mark: | Spending limit for the API key in USD | 100 | +| `usage` | *float* | :heavy_check_mark: | Total OpenRouter credit usage (in USD) for the API key | 25.5 | +| `usage_daily` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC day | 25.5 | +| `usage_weekly` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday) | 25.5 | +| `usage_monthly` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC month | 25.5 | +| `byok_usage` | *float* | :heavy_check_mark: | Total external BYOK usage (in USD) for the API key | 17.38 | +| `byok_usage_daily` | *float* | :heavy_check_mark: | External BYOK usage (in USD) for the current UTC day | 17.38 | +| `byok_usage_weekly` | *float* | :heavy_check_mark: | External BYOK usage (in USD) for the current UTC week (Monday-Sunday) | 17.38 | +| `byok_usage_monthly` | *float* | :heavy_check_mark: | External BYOK usage (in USD) for current UTC month | 17.38 | +| `is_free_tier` | *bool* | :heavy_check_mark: | Whether this is a free tier API key | false | +| `is_provisioning_key` | *bool* | :heavy_check_mark: | Whether this is a provisioning key | false | +| `limit_remaining` | *Nullable[float]* | :heavy_check_mark: | Remaining spending limit in USD | 74.5 | +| `limit_reset` | *Nullable[str]* | :heavy_check_mark: | Type of limit reset for the API key | monthly | +| `include_byok_in_limit` | *bool* | :heavy_check_mark: | Whether to include external BYOK usage in the credit limit | false | +| `expires_at` | [date](https://docs.python.org/3/library/datetime.html#date-objects) | :heavy_minus_sign: | ISO 8601 UTC timestamp when the API key expires, or null if no expiration | 2027-12-31T23:59:59Z | +| ~~`rate_limit`~~ | [models.RateLimit](../models/ratelimit.md) | :heavy_check_mark: | : warning: ** DEPRECATED **: This will be removed in a future release, please migrate away from it as soon as possible.

Legacy rate limit information about a key. Will always return -1. | {
"requests": 1000,
"interval": "1h",
"note": "This field is deprecated and safe to ignore."
} | \ No newline at end of file diff --git a/docs/models/getcurrentkeyresponse.md b/docs/models/getcurrentkeyresponse.md new file mode 100644 index 0000000..1e65392 --- /dev/null +++ b/docs/models/getcurrentkeyresponse.md @@ -0,0 +1,10 @@ +# GetCurrentKeyResponse + +API key details + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `data` | [models.GetCurrentKeyData](../models/getcurrentkeydata.md) | :heavy_check_mark: | Current API key information | {
"label": "sk-or-v1-au78b3456789012345678901234567890",
"limit": 100,
"usage": 25.5,
"usage_daily": 25.5,
"usage_weekly": 25.5,
"usage_monthly": 25.5,
"byok_usage": 17.38,
"byok_usage_daily": 17.38,
"byok_usage_weekly": 17.38,
"byok_usage_monthly": 17.38,
"is_free_tier": false,
"is_provisioning_key": false,
"limit_remaining": 74.5,
"limit_reset": "monthly",
"include_byok_in_limit": false,
"expires_at": "2027-12-31T23:59:59Z",
"rate_limit": {
"requests": 1000,
"interval": "1h",
"note": "This field is deprecated and safe to ignore."
}
} | \ No newline at end of file diff --git a/docs/models/getgenerationdata.md b/docs/models/getgenerationdata.md new file mode 100644 index 0000000..d68c548 --- /dev/null +++ b/docs/models/getgenerationdata.md @@ -0,0 +1,41 @@ +# GetGenerationData + +Generation data + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------ | ------------------------------------------------------ | ------------------------------------------------------ | ------------------------------------------------------ | ------------------------------------------------------ | +| `id` | *str* | :heavy_check_mark: | Unique identifier for the generation | gen-3bhGkxlo4XFrqiabUM7NDtwDzWwG | +| `upstream_id` | *Nullable[str]* | :heavy_check_mark: | Upstream provider's identifier for this generation | chatcmpl-791bcf62-080e-4568-87d0-94c72e3b4946 | +| `total_cost` | *float* | :heavy_check_mark: | Total cost of the generation in USD | 0.0015 | +| `cache_discount` | *Nullable[float]* | :heavy_check_mark: | Discount applied due to caching | 0.0002 | +| `upstream_inference_cost` | *Nullable[float]* | :heavy_check_mark: | Cost charged by the upstream provider | 0.0012 | +| `created_at` | *str* | :heavy_check_mark: | ISO 8601 timestamp of when the generation was created | 2024-07-15T23:33:19.433273+00:00 | +| `model` | *str* | :heavy_check_mark: | Model used for the generation | sao10k/l3-stheno-8b | +| `app_id` | *Nullable[float]* | :heavy_check_mark: | ID of the app that made the request | 12345 | +| `streamed` | *Nullable[bool]* | :heavy_check_mark: | Whether the response was streamed | true | +| `cancelled` | *Nullable[bool]* | :heavy_check_mark: | Whether the generation was cancelled | false | +| `provider_name` | *Nullable[str]* | :heavy_check_mark: | Name of the provider that served the request | Infermatic | +| `latency` | *Nullable[float]* | :heavy_check_mark: | Total latency in milliseconds | 1250 | +| `moderation_latency` | *Nullable[float]* | :heavy_check_mark: | Moderation latency in milliseconds | 50 | +| `generation_time` | *Nullable[float]* | :heavy_check_mark: | Time taken for generation in milliseconds | 1200 | +| `finish_reason` | *Nullable[str]* | :heavy_check_mark: | Reason the generation finished | stop | +| `tokens_prompt` | *Nullable[float]* | :heavy_check_mark: | Number of tokens in the prompt | 10 | +| `tokens_completion` | *Nullable[float]* | :heavy_check_mark: | Number of tokens in the completion | 25 | +| `native_tokens_prompt` | *Nullable[float]* | :heavy_check_mark: | Native prompt tokens as reported by provider | 10 | +| `native_tokens_completion` | *Nullable[float]* | :heavy_check_mark: | Native completion tokens as reported by provider | 25 | +| `native_tokens_completion_images` | *Nullable[float]* | :heavy_check_mark: | Native completion image tokens as reported by provider | 0 | +| `native_tokens_reasoning` | *Nullable[float]* | :heavy_check_mark: | Native reasoning tokens as reported by provider | 5 | +| `native_tokens_cached` | *Nullable[float]* | :heavy_check_mark: | Native cached tokens as reported by provider | 3 | +| `num_media_prompt` | *Nullable[float]* | :heavy_check_mark: | Number of media items in the prompt | 1 | +| `num_input_audio_prompt` | *Nullable[float]* | :heavy_check_mark: | Number of audio inputs in the prompt | 0 | +| `num_media_completion` | *Nullable[float]* | :heavy_check_mark: | Number of media items in the completion | 0 | +| `num_search_results` | *Nullable[float]* | :heavy_check_mark: | Number of search results included | 5 | +| `origin` | *str* | :heavy_check_mark: | Origin URL of the request | https://openrouter.ai/ | +| `usage` | *float* | :heavy_check_mark: | Usage amount in USD | 0.0015 | +| `is_byok` | *bool* | :heavy_check_mark: | Whether this used bring-your-own-key | false | +| `native_finish_reason` | *Nullable[str]* | :heavy_check_mark: | Native finish reason as reported by provider | stop | +| `external_user` | *Nullable[str]* | :heavy_check_mark: | External user identifier | user-123 | +| `api_type` | [Nullable[models.APIType]](../models/apitype.md) | :heavy_check_mark: | Type of API used for the generation | | \ No newline at end of file diff --git a/docs/models/getgenerationrequest.md b/docs/models/getgenerationrequest.md new file mode 100644 index 0000000..6c59a6a --- /dev/null +++ b/docs/models/getgenerationrequest.md @@ -0,0 +1,8 @@ +# GetGenerationRequest + + +## Fields + +| Field | Type | Required | Description | +| ------------------ | ------------------ | ------------------ | ------------------ | +| `id` | *str* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/getgenerationresponse.md b/docs/models/getgenerationresponse.md new file mode 100644 index 0000000..f44a3e9 --- /dev/null +++ b/docs/models/getgenerationresponse.md @@ -0,0 +1,10 @@ +# GetGenerationResponse + +Generation response + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- | +| `data` | [models.GetGenerationData](../models/getgenerationdata.md) | :heavy_check_mark: | Generation data | \ No newline at end of file diff --git a/docs/models/getkeydata.md b/docs/models/getkeydata.md new file mode 100644 index 0000000..dd61419 --- /dev/null +++ b/docs/models/getkeydata.md @@ -0,0 +1,28 @@ +# GetKeyData + +The API key information + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | +| `hash` | *str* | :heavy_check_mark: | Unique hash identifier for the API key | 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 | +| `name` | *str* | :heavy_check_mark: | Name of the API key | My Production Key | +| `label` | *str* | :heavy_check_mark: | Human-readable label for the API key | Production API Key | +| `disabled` | *bool* | :heavy_check_mark: | Whether the API key is disabled | false | +| `limit` | *Nullable[float]* | :heavy_check_mark: | Spending limit for the API key in USD | 100 | +| `limit_remaining` | *Nullable[float]* | :heavy_check_mark: | Remaining spending limit in USD | 74.5 | +| `limit_reset` | *Nullable[str]* | :heavy_check_mark: | Type of limit reset for the API key | monthly | +| `include_byok_in_limit` | *bool* | :heavy_check_mark: | Whether to include external BYOK usage in the credit limit | false | +| `usage` | *float* | :heavy_check_mark: | Total OpenRouter credit usage (in USD) for the API key | 25.5 | +| `usage_daily` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC day | 25.5 | +| `usage_weekly` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday) | 25.5 | +| `usage_monthly` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC month | 25.5 | +| `byok_usage` | *float* | :heavy_check_mark: | Total external BYOK usage (in USD) for the API key | 17.38 | +| `byok_usage_daily` | *float* | :heavy_check_mark: | External BYOK usage (in USD) for the current UTC day | 17.38 | +| `byok_usage_weekly` | *float* | :heavy_check_mark: | External BYOK usage (in USD) for the current UTC week (Monday-Sunday) | 17.38 | +| `byok_usage_monthly` | *float* | :heavy_check_mark: | External BYOK usage (in USD) for current UTC month | 17.38 | +| `created_at` | *str* | :heavy_check_mark: | ISO 8601 timestamp of when the API key was created | 2025-08-24T10:30:00Z | +| `updated_at` | *Nullable[str]* | :heavy_check_mark: | ISO 8601 timestamp of when the API key was last updated | 2025-08-24T15:45:00Z | +| `expires_at` | [date](https://docs.python.org/3/library/datetime.html#date-objects) | :heavy_minus_sign: | ISO 8601 UTC timestamp when the API key expires, or null if no expiration | 2027-12-31T23:59:59Z | \ No newline at end of file diff --git a/docs/models/getkeyrequest.md b/docs/models/getkeyrequest.md new file mode 100644 index 0000000..0f125f6 --- /dev/null +++ b/docs/models/getkeyrequest.md @@ -0,0 +1,8 @@ +# GetKeyRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | +| `hash` | *str* | :heavy_check_mark: | The hash identifier of the API key to retrieve | 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 | \ No newline at end of file diff --git a/docs/models/getkeyresponse.md b/docs/models/getkeyresponse.md new file mode 100644 index 0000000..d70de31 --- /dev/null +++ b/docs/models/getkeyresponse.md @@ -0,0 +1,10 @@ +# GetKeyResponse + +API key details + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `data` | [models.GetKeyData](../models/getkeydata.md) | :heavy_check_mark: | The API key information | {
"hash": "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",
"name": "My Production Key",
"label": "Production API Key",
"disabled": false,
"limit": 100,
"limit_remaining": 74.5,
"limit_reset": "monthly",
"include_byok_in_limit": false,
"usage": 25.5,
"usage_daily": 25.5,
"usage_weekly": 25.5,
"usage_monthly": 25.5,
"byok_usage": 17.38,
"byok_usage_daily": 17.38,
"byok_usage_weekly": 17.38,
"byok_usage_monthly": 17.38,
"created_at": "2025-08-24T10:30:00Z",
"updated_at": "2025-08-24T15:45:00Z",
"expires_at": "2027-12-31T23:59:59Z"
} | \ No newline at end of file diff --git a/docs/models/getmodelsrequest.md b/docs/models/getmodelsrequest.md new file mode 100644 index 0000000..b08feb5 --- /dev/null +++ b/docs/models/getmodelsrequest.md @@ -0,0 +1,9 @@ +# GetModelsRequest + + +## Fields + +| Field | Type | Required | Description | +| ---------------------- | ---------------------- | ---------------------- | ---------------------- | +| `category` | *Optional[str]* | :heavy_minus_sign: | N/A | +| `supported_parameters` | *Optional[str]* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/getparametersdata.md b/docs/models/getparametersdata.md new file mode 100644 index 0000000..c2a542c --- /dev/null +++ b/docs/models/getparametersdata.md @@ -0,0 +1,11 @@ +# GetParametersData + +Parameter analytics data + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | +| `model` | *str* | :heavy_check_mark: | Model identifier | openai/gpt-4 | +| `supported_parameters` | List[[models.SupportedParameter](../models/supportedparameter.md)] | :heavy_check_mark: | List of parameters supported by this model | [
"temperature",
"top_p",
"max_tokens"
] | \ No newline at end of file diff --git a/docs/models/getparametersprovider.md b/docs/models/getparametersprovider.md new file mode 100644 index 0000000..233a4ed --- /dev/null +++ b/docs/models/getparametersprovider.md @@ -0,0 +1,75 @@ +# GetParametersProvider + + +## Values + +| Name | Value | +| ------------------ | ------------------ | +| `AI21` | AI21 | +| `AION_LABS` | AionLabs | +| `ALIBABA` | Alibaba | +| `AMAZON_BEDROCK` | Amazon Bedrock | +| `ANTHROPIC` | Anthropic | +| `ATLAS_CLOUD` | AtlasCloud | +| `ATOMA` | Atoma | +| `AVIAN` | Avian | +| `AZURE` | Azure | +| `BASE_TEN` | BaseTen | +| `CEREBRAS` | Cerebras | +| `CHUTES` | Chutes | +| `CIRRASCALE` | Cirrascale | +| `CLARIFAI` | Clarifai | +| `CLOUDFLARE` | Cloudflare | +| `COHERE` | Cohere | +| `CROF_AI` | CrofAI | +| `CRUSOE` | Crusoe | +| `DEEP_INFRA` | DeepInfra | +| `DEEP_SEEK` | DeepSeek | +| `ENFER` | Enfer | +| `FEATHERLESS` | Featherless | +| `FIREWORKS` | Fireworks | +| `FRIENDLI` | Friendli | +| `GMI_CLOUD` | GMICloud | +| `GOOGLE` | Google | +| `GOOGLE_AI_STUDIO` | Google AI Studio | +| `GROQ` | Groq | +| `HYPERBOLIC` | Hyperbolic | +| `INCEPTION` | Inception | +| `INFERENCE_NET` | InferenceNet | +| `INFERMATIC` | Infermatic | +| `INFLECTION` | Inflection | +| `KLUSTER` | Kluster | +| `LAMBDA` | Lambda | +| `LIQUID` | Liquid | +| `MANCER_2` | Mancer 2 | +| `META` | Meta | +| `MINIMAX` | Minimax | +| `MODEL_RUN` | ModelRun | +| `MISTRAL` | Mistral | +| `MODULAR` | Modular | +| `MOONSHOT_AI` | Moonshot AI | +| `MORPH` | Morph | +| `N_COMPASS` | NCompass | +| `NEBIUS` | Nebius | +| `NEXT_BIT` | NextBit | +| `NINETEEN` | Nineteen | +| `NOVITA` | Novita | +| `NVIDIA` | Nvidia | +| `OPEN_AI` | OpenAI | +| `OPEN_INFERENCE` | OpenInference | +| `PARASAIL` | Parasail | +| `PERPLEXITY` | Perplexity | +| `PHALA` | Phala | +| `RELACE` | Relace | +| `SAMBA_NOVA` | SambaNova | +| `SILICON_FLOW` | SiliconFlow | +| `STEALTH` | Stealth | +| `SWITCHPOINT` | Switchpoint | +| `TARGON` | Targon | +| `TOGETHER` | Together | +| `UBICLOUD` | Ubicloud | +| `VENICE` | Venice | +| `WAND_B` | WandB | +| `X_AI` | xAI | +| `Z_AI` | Z.AI | +| `FAKE_PROVIDER` | FakeProvider | \ No newline at end of file diff --git a/docs/models/getparametersrequest.md b/docs/models/getparametersrequest.md new file mode 100644 index 0000000..f84578f --- /dev/null +++ b/docs/models/getparametersrequest.md @@ -0,0 +1,10 @@ +# GetParametersRequest + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | +| `author` | *str* | :heavy_check_mark: | N/A | +| `slug` | *str* | :heavy_check_mark: | N/A | +| `provider` | [Optional[models.GetParametersProvider]](../models/getparametersprovider.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/getparametersresponse.md b/docs/models/getparametersresponse.md new file mode 100644 index 0000000..a495578 --- /dev/null +++ b/docs/models/getparametersresponse.md @@ -0,0 +1,10 @@ +# GetParametersResponse + +Returns the parameters for the specified model + + +## Fields + +| Field | Type | Required | Description | Example | +| --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | +| `data` | [models.GetParametersData](../models/getparametersdata.md) | :heavy_check_mark: | Parameter analytics data | {
"model": "openai/gpt-4",
"supported_parameters": [
"temperature",
"top_p",
"max_tokens"
]
} | \ No newline at end of file diff --git a/docs/models/getparameterssecurity.md b/docs/models/getparameterssecurity.md new file mode 100644 index 0000000..7f8062f --- /dev/null +++ b/docs/models/getparameterssecurity.md @@ -0,0 +1,8 @@ +# GetParametersSecurity + + +## Fields + +| Field | Type | Required | Description | +| ------------------ | ------------------ | ------------------ | ------------------ | +| `bearer` | *str* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/getuseractivityrequest.md b/docs/models/getuseractivityrequest.md new file mode 100644 index 0000000..6df2f76 --- /dev/null +++ b/docs/models/getuseractivityrequest.md @@ -0,0 +1,8 @@ +# GetUserActivityRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------------------------------------- | -------------------------------------------------------------------- | -------------------------------------------------------------------- | -------------------------------------------------------------------- | -------------------------------------------------------------------- | +| `date_` | *Optional[str]* | :heavy_minus_sign: | Filter by a single UTC date in the last 30 days (YYYY-MM-DD format). | 2025-08-24 | \ No newline at end of file diff --git a/docs/models/getuseractivityresponse.md b/docs/models/getuseractivityresponse.md new file mode 100644 index 0000000..2f8d773 --- /dev/null +++ b/docs/models/getuseractivityresponse.md @@ -0,0 +1,10 @@ +# GetUserActivityResponse + +Returns user activity data grouped by endpoint + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------ | ------------------------------------------------------ | ------------------------------------------------------ | ------------------------------------------------------ | +| `data` | List[[models.ActivityItem](../models/activityitem.md)] | :heavy_check_mark: | List of activity items | \ No newline at end of file diff --git a/docs/models/idfileparser.md b/docs/models/idfileparser.md new file mode 100644 index 0000000..1a27fa0 --- /dev/null +++ b/docs/models/idfileparser.md @@ -0,0 +1,8 @@ +# IDFileParser + + +## Values + +| Name | Value | +| ------------- | ------------- | +| `FILE_PARSER` | file-parser | \ No newline at end of file diff --git a/docs/models/idmoderation.md b/docs/models/idmoderation.md new file mode 100644 index 0000000..2284d6c --- /dev/null +++ b/docs/models/idmoderation.md @@ -0,0 +1,8 @@ +# IDModeration + + +## Values + +| Name | Value | +| ------------ | ------------ | +| `MODERATION` | moderation | \ No newline at end of file diff --git a/docs/models/idweb.md b/docs/models/idweb.md new file mode 100644 index 0000000..8c668e6 --- /dev/null +++ b/docs/models/idweb.md @@ -0,0 +1,8 @@ +# IDWeb + + +## Values + +| Name | Value | +| ----- | ----- | +| `WEB` | web | \ No newline at end of file diff --git a/docs/models/ignore.md b/docs/models/ignore.md new file mode 100644 index 0000000..4d6f43d --- /dev/null +++ b/docs/models/ignore.md @@ -0,0 +1,17 @@ +# Ignore + + +## Supported Types + +### `models.ProviderName` + +```python +value: models.ProviderName = /* values here */ +``` + +### `str` + +```python +value: str = /* values here */ +``` + diff --git a/docs/models/imagegenerationstatus.md b/docs/models/imagegenerationstatus.md new file mode 100644 index 0000000..22e0541 --- /dev/null +++ b/docs/models/imagegenerationstatus.md @@ -0,0 +1,11 @@ +# ImageGenerationStatus + + +## Values + +| Name | Value | +| ------------- | ------------- | +| `IN_PROGRESS` | in_progress | +| `COMPLETED` | completed | +| `GENERATING` | generating | +| `FAILED` | failed | \ No newline at end of file diff --git a/docs/models/imageurl.md b/docs/models/imageurl.md new file mode 100644 index 0000000..dcc57eb --- /dev/null +++ b/docs/models/imageurl.md @@ -0,0 +1,9 @@ +# ImageURL + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | +| `url` | *str* | :heavy_check_mark: | N/A | +| `detail` | [Optional[models.ChatMessageContentItemImageDetail]](../models/chatmessagecontentitemimagedetail.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/input.md b/docs/models/input.md new file mode 100644 index 0000000..e02d970 --- /dev/null +++ b/docs/models/input.md @@ -0,0 +1,29 @@ +# Input + + +## Supported Types + +### `str` + +```python +value: str = /* values here */ +``` + +### `List[str]` + +```python +value: List[str] = /* values here */ +``` + +### `List[float]` + +```python +value: List[float] = /* values here */ +``` + +### `List[List[float]]` + +```python +value: List[List[float]] = /* values here */ +``` + diff --git a/docs/models/inputmodality.md b/docs/models/inputmodality.md new file mode 100644 index 0000000..89bdc2a --- /dev/null +++ b/docs/models/inputmodality.md @@ -0,0 +1,12 @@ +# InputModality + + +## Values + +| Name | Value | +| ------- | ------- | +| `TEXT` | text | +| `IMAGE` | image | +| `FILE` | file | +| `AUDIO` | audio | +| `VIDEO` | video | \ No newline at end of file diff --git a/docs/models/inputtokensdetails.md b/docs/models/inputtokensdetails.md new file mode 100644 index 0000000..40de8ec --- /dev/null +++ b/docs/models/inputtokensdetails.md @@ -0,0 +1,8 @@ +# InputTokensDetails + + +## Fields + +| Field | Type | Required | Description | +| ------------------ | ------------------ | ------------------ | ------------------ | +| `cached_tokens` | *float* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/instructtype.md b/docs/models/instructtype.md new file mode 100644 index 0000000..44c350d --- /dev/null +++ b/docs/models/instructtype.md @@ -0,0 +1,31 @@ +# InstructType + +Instruction format type + + +## Values + +| Name | Value | +| --------------- | --------------- | +| `NONE` | none | +| `AIROBOROS` | airoboros | +| `ALPACA` | alpaca | +| `ALPACA_MODIF` | alpaca-modif | +| `CHATML` | chatml | +| `CLAUDE` | claude | +| `CODE_LLAMA` | code-llama | +| `GEMMA` | gemma | +| `LLAMA2` | llama2 | +| `LLAMA3` | llama3 | +| `MISTRAL` | mistral | +| `NEMOTRON` | nemotron | +| `NEURAL` | neural | +| `OPENCHAT` | openchat | +| `PHI3` | phi3 | +| `RWKV` | rwkv | +| `VICUNA` | vicuna | +| `ZEPHYR` | zephyr | +| `DEEPSEEK_R1` | deepseek-r1 | +| `DEEPSEEK_V3_1` | deepseek-v3.1 | +| `QWQ` | qwq | +| `QWEN3` | qwen3 | \ No newline at end of file diff --git a/docs/models/internalserverresponseerrordata.md b/docs/models/internalserverresponseerrordata.md new file mode 100644 index 0000000..b320ded --- /dev/null +++ b/docs/models/internalserverresponseerrordata.md @@ -0,0 +1,12 @@ +# InternalServerResponseErrorData + +Error data for InternalServerResponse + + +## Fields + +| Field | Type | Required | Description | +| -------------------------- | -------------------------- | -------------------------- | -------------------------- | +| `code` | *int* | :heavy_check_mark: | N/A | +| `message` | *str* | :heavy_check_mark: | N/A | +| `metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/jsonschemaconfig.md b/docs/models/jsonschemaconfig.md new file mode 100644 index 0000000..e51339a --- /dev/null +++ b/docs/models/jsonschemaconfig.md @@ -0,0 +1,11 @@ +# JSONSchemaConfig + + +## Fields + +| Field | Type | Required | Description | +| ------------------------ | ------------------------ | ------------------------ | ------------------------ | +| `name` | *str* | :heavy_check_mark: | N/A | +| `description` | *Optional[str]* | :heavy_minus_sign: | N/A | +| `schema_` | Dict[str, *Any*] | :heavy_minus_sign: | N/A | +| `strict` | *OptionalNullable[bool]* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/listdata.md b/docs/models/listdata.md new file mode 100644 index 0000000..edebb91 --- /dev/null +++ b/docs/models/listdata.md @@ -0,0 +1,26 @@ +# ListData + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | +| `hash` | *str* | :heavy_check_mark: | Unique hash identifier for the API key | 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 | +| `name` | *str* | :heavy_check_mark: | Name of the API key | My Production Key | +| `label` | *str* | :heavy_check_mark: | Human-readable label for the API key | Production API Key | +| `disabled` | *bool* | :heavy_check_mark: | Whether the API key is disabled | false | +| `limit` | *Nullable[float]* | :heavy_check_mark: | Spending limit for the API key in USD | 100 | +| `limit_remaining` | *Nullable[float]* | :heavy_check_mark: | Remaining spending limit in USD | 74.5 | +| `limit_reset` | *Nullable[str]* | :heavy_check_mark: | Type of limit reset for the API key | monthly | +| `include_byok_in_limit` | *bool* | :heavy_check_mark: | Whether to include external BYOK usage in the credit limit | false | +| `usage` | *float* | :heavy_check_mark: | Total OpenRouter credit usage (in USD) for the API key | 25.5 | +| `usage_daily` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC day | 25.5 | +| `usage_weekly` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday) | 25.5 | +| `usage_monthly` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC month | 25.5 | +| `byok_usage` | *float* | :heavy_check_mark: | Total external BYOK usage (in USD) for the API key | 17.38 | +| `byok_usage_daily` | *float* | :heavy_check_mark: | External BYOK usage (in USD) for the current UTC day | 17.38 | +| `byok_usage_weekly` | *float* | :heavy_check_mark: | External BYOK usage (in USD) for the current UTC week (Monday-Sunday) | 17.38 | +| `byok_usage_monthly` | *float* | :heavy_check_mark: | External BYOK usage (in USD) for current UTC month | 17.38 | +| `created_at` | *str* | :heavy_check_mark: | ISO 8601 timestamp of when the API key was created | 2025-08-24T10:30:00Z | +| `updated_at` | *Nullable[str]* | :heavy_check_mark: | ISO 8601 timestamp of when the API key was last updated | 2025-08-24T15:45:00Z | +| `expires_at` | [date](https://docs.python.org/3/library/datetime.html#date-objects) | :heavy_minus_sign: | ISO 8601 UTC timestamp when the API key expires, or null if no expiration | 2027-12-31T23:59:59Z | \ No newline at end of file diff --git a/docs/models/listendpointsrequest.md b/docs/models/listendpointsrequest.md new file mode 100644 index 0000000..5d7e3e4 --- /dev/null +++ b/docs/models/listendpointsrequest.md @@ -0,0 +1,9 @@ +# ListEndpointsRequest + + +## Fields + +| Field | Type | Required | Description | +| ------------------ | ------------------ | ------------------ | ------------------ | +| `author` | *str* | :heavy_check_mark: | N/A | +| `slug` | *str* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/listendpointsresponse.md b/docs/models/listendpointsresponse.md new file mode 100644 index 0000000..ef3094d --- /dev/null +++ b/docs/models/listendpointsresponse.md @@ -0,0 +1,15 @@ +# ListEndpointsResponse + +List of available endpoints for a model + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | +| `id` | *str* | :heavy_check_mark: | Unique identifier for the model | openai/gpt-4 | +| `name` | *str* | :heavy_check_mark: | Display name of the model | GPT-4 | +| `created` | *float* | :heavy_check_mark: | Unix timestamp of when the model was created | 1692901234 | +| `description` | *str* | :heavy_check_mark: | Description of the model | GPT-4 is a large multimodal model that can solve difficult problems with greater accuracy. | +| `architecture` | [models.Architecture](../models/architecture.md) | :heavy_check_mark: | N/A | {
"tokenizer": "GPT",
"instruct_type": "chatml",
"modality": "text-\u003etext",
"input_modalities": [
"text"
],
"output_modalities": [
"text"
]
} | +| `endpoints` | List[[models.PublicEndpoint](../models/publicendpoint.md)] | :heavy_check_mark: | List of available endpoints for this model | | \ No newline at end of file diff --git a/docs/models/listendpointszdrresponse.md b/docs/models/listendpointszdrresponse.md new file mode 100644 index 0000000..eaae76c --- /dev/null +++ b/docs/models/listendpointszdrresponse.md @@ -0,0 +1,10 @@ +# ListEndpointsZdrResponse + +Returns a list of endpoints + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- | +| `data` | List[[models.PublicEndpoint](../models/publicendpoint.md)] | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/listmodelsusersecurity.md b/docs/models/listmodelsusersecurity.md new file mode 100644 index 0000000..3d42e13 --- /dev/null +++ b/docs/models/listmodelsusersecurity.md @@ -0,0 +1,8 @@ +# ListModelsUserSecurity + + +## Fields + +| Field | Type | Required | Description | +| ------------------ | ------------------ | ------------------ | ------------------ | +| `bearer` | *str* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/listprovidersdata.md b/docs/models/listprovidersdata.md new file mode 100644 index 0000000..9679171 --- /dev/null +++ b/docs/models/listprovidersdata.md @@ -0,0 +1,12 @@ +# ListProvidersData + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | +| `name` | *str* | :heavy_check_mark: | Display name of the provider | OpenAI | +| `slug` | *str* | :heavy_check_mark: | URL-friendly identifier for the provider | openai | +| `privacy_policy_url` | *Nullable[str]* | :heavy_check_mark: | URL to the provider's privacy policy | https://openai.com/privacy | +| `terms_of_service_url` | *OptionalNullable[str]* | :heavy_minus_sign: | URL to the provider's terms of service | https://openai.com/terms | +| `status_page_url` | *OptionalNullable[str]* | :heavy_minus_sign: | URL to the provider's status page | https://status.openai.com | \ No newline at end of file diff --git a/docs/models/listprovidersresponse.md b/docs/models/listprovidersresponse.md new file mode 100644 index 0000000..bbd7209 --- /dev/null +++ b/docs/models/listprovidersresponse.md @@ -0,0 +1,10 @@ +# ListProvidersResponse + +Returns a list of providers + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------- | +| `data` | List[[models.ListProvidersData](../models/listprovidersdata.md)] | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/listrequest.md b/docs/models/listrequest.md new file mode 100644 index 0000000..4911cc1 --- /dev/null +++ b/docs/models/listrequest.md @@ -0,0 +1,9 @@ +# ListRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------- | ---------------------------------------------------- | ---------------------------------------------------- | ---------------------------------------------------- | ---------------------------------------------------- | +| `include_disabled` | *Optional[str]* | :heavy_minus_sign: | Whether to include disabled API keys in the response | false | +| `offset` | *Optional[str]* | :heavy_minus_sign: | Number of API keys to skip for pagination | 0 | \ No newline at end of file diff --git a/docs/models/listresponse.md b/docs/models/listresponse.md new file mode 100644 index 0000000..d33242c --- /dev/null +++ b/docs/models/listresponse.md @@ -0,0 +1,10 @@ +# ListResponse + +List of API keys + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------- | ---------------------------------------------- | ---------------------------------------------- | ---------------------------------------------- | +| `data` | List[[models.ListData](../models/listdata.md)] | :heavy_check_mark: | List of API keys | \ No newline at end of file diff --git a/docs/models/maxprice.md b/docs/models/maxprice.md new file mode 100644 index 0000000..fd88c78 --- /dev/null +++ b/docs/models/maxprice.md @@ -0,0 +1,14 @@ +# MaxPrice + +The object specifying the maximum price you want to pay for this request. USD price per million tokens, for prompt and completion. + + +## Fields + +| Field | Type | Required | Description | +| --------------------------------------------------------- | --------------------------------------------------------- | --------------------------------------------------------- | --------------------------------------------------------- | +| `prompt` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number | +| `completion` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number | +| `image` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number | +| `audio` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number | +| `request` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number | \ No newline at end of file diff --git a/docs/models/message.md b/docs/models/message.md new file mode 100644 index 0000000..4fa98b6 --- /dev/null +++ b/docs/models/message.md @@ -0,0 +1,35 @@ +# Message + + +## Supported Types + +### `models.SystemMessage` + +```python +value: models.SystemMessage = /* values here */ +``` + +### `models.UserMessage` + +```python +value: models.UserMessage = /* values here */ +``` + +### `models.MessageDeveloper` + +```python +value: models.MessageDeveloper = /* values here */ +``` + +### `models.AssistantMessage` + +```python +value: models.AssistantMessage = /* values here */ +``` + +### `models.ToolResponseMessage` + +```python +value: models.ToolResponseMessage = /* values here */ +``` + diff --git a/docs/models/messagecontent.md b/docs/models/messagecontent.md new file mode 100644 index 0000000..0edfefd --- /dev/null +++ b/docs/models/messagecontent.md @@ -0,0 +1,17 @@ +# MessageContent + + +## Supported Types + +### `str` + +```python +value: str = /* values here */ +``` + +### `List[models.ChatMessageContentItemText]` + +```python +value: List[models.ChatMessageContentItemText] = /* values here */ +``` + diff --git a/docs/models/messagedeveloper.md b/docs/models/messagedeveloper.md new file mode 100644 index 0000000..698364d --- /dev/null +++ b/docs/models/messagedeveloper.md @@ -0,0 +1,10 @@ +# MessageDeveloper + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------- | ---------------------------------------------------- | ---------------------------------------------------- | ---------------------------------------------------- | +| `role` | *Literal["developer"]* | :heavy_check_mark: | N/A | +| `content` | [models.MessageContent](../models/messagecontent.md) | :heavy_check_mark: | N/A | +| `name` | *Optional[str]* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/metadata.md b/docs/models/metadata.md new file mode 100644 index 0000000..87bf7e3 --- /dev/null +++ b/docs/models/metadata.md @@ -0,0 +1,10 @@ +# Metadata + + +## Fields + +| Field | Type | Required | Description | +| ------------------ | ------------------ | ------------------ | ------------------ | +| `chain_id` | *float* | :heavy_check_mark: | N/A | +| `contract_address` | *str* | :heavy_check_mark: | N/A | +| `sender` | *str* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/model.md b/docs/models/model.md new file mode 100644 index 0000000..c7b09ad --- /dev/null +++ b/docs/models/model.md @@ -0,0 +1,22 @@ +# Model + +Information about an AI model available on OpenRouter + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | +| `id` | *str* | :heavy_check_mark: | Unique identifier for the model | openai/gpt-4 | +| `canonical_slug` | *str* | :heavy_check_mark: | Canonical slug for the model | openai/gpt-4 | +| `hugging_face_id` | *OptionalNullable[str]* | :heavy_minus_sign: | Hugging Face model identifier, if applicable | microsoft/DialoGPT-medium | +| `name` | *str* | :heavy_check_mark: | Display name of the model | GPT-4 | +| `created` | *float* | :heavy_check_mark: | Unix timestamp of when the model was created | 1692901234 | +| `description` | *Optional[str]* | :heavy_minus_sign: | Description of the model | GPT-4 is a large multimodal model that can solve difficult problems with greater accuracy. | +| `pricing` | [models.PublicPricing](../models/publicpricing.md) | :heavy_check_mark: | Pricing information for the model | {
"prompt": "0.00003",
"completion": "0.00006",
"request": "0",
"image": "0"
} | +| `context_length` | *Nullable[float]* | :heavy_check_mark: | Maximum context length in tokens | 8192 | +| `architecture` | [models.ModelArchitecture](../models/modelarchitecture.md) | :heavy_check_mark: | Model architecture information | {
"tokenizer": "GPT",
"instruct_type": "chatml",
"modality": "text-\u003etext",
"input_modalities": [
"text"
],
"output_modalities": [
"text"
]
} | +| `top_provider` | [models.TopProviderInfo](../models/topproviderinfo.md) | :heavy_check_mark: | Information about the top provider for this model | {
"context_length": 8192,
"max_completion_tokens": 4096,
"is_moderated": true
} | +| `per_request_limits` | [Nullable[models.PerRequestLimits]](../models/perrequestlimits.md) | :heavy_check_mark: | Per-request token limits | {
"prompt_tokens": 1000,
"completion_tokens": 1000
} | +| `supported_parameters` | List[[models.Parameter](../models/parameter.md)] | :heavy_check_mark: | List of supported parameters for this model | | +| `default_parameters` | [Nullable[models.DefaultParameters]](../models/defaultparameters.md) | :heavy_check_mark: | Default parameters for this model | {
"temperature": 0.7,
"top_p": 0.9,
"frequency_penalty": 0
} | \ No newline at end of file diff --git a/docs/models/modelarchitecture.md b/docs/models/modelarchitecture.md new file mode 100644 index 0000000..6a311c6 --- /dev/null +++ b/docs/models/modelarchitecture.md @@ -0,0 +1,14 @@ +# ModelArchitecture + +Model architecture information + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | +| `tokenizer` | [Optional[models.ModelGroup]](../models/modelgroup.md) | :heavy_minus_sign: | Tokenizer type used by the model | GPT | +| `instruct_type` | [OptionalNullable[models.ModelArchitectureInstructType]](../models/modelarchitectureinstructtype.md) | :heavy_minus_sign: | Instruction format type | chatml | +| `modality` | *Nullable[str]* | :heavy_check_mark: | Primary modality of the model | text->text | +| `input_modalities` | List[[models.InputModality](../models/inputmodality.md)] | :heavy_check_mark: | Supported input modalities | | +| `output_modalities` | List[[models.OutputModality](../models/outputmodality.md)] | :heavy_check_mark: | Supported output modalities | | \ No newline at end of file diff --git a/docs/models/modelarchitectureinstructtype.md b/docs/models/modelarchitectureinstructtype.md new file mode 100644 index 0000000..eabbbe3 --- /dev/null +++ b/docs/models/modelarchitectureinstructtype.md @@ -0,0 +1,31 @@ +# ModelArchitectureInstructType + +Instruction format type + + +## Values + +| Name | Value | +| --------------- | --------------- | +| `NONE` | none | +| `AIROBOROS` | airoboros | +| `ALPACA` | alpaca | +| `ALPACA_MODIF` | alpaca-modif | +| `CHATML` | chatml | +| `CLAUDE` | claude | +| `CODE_LLAMA` | code-llama | +| `GEMMA` | gemma | +| `LLAMA2` | llama2 | +| `LLAMA3` | llama3 | +| `MISTRAL` | mistral | +| `NEMOTRON` | nemotron | +| `NEURAL` | neural | +| `OPENCHAT` | openchat | +| `PHI3` | phi3 | +| `RWKV` | rwkv | +| `VICUNA` | vicuna | +| `ZEPHYR` | zephyr | +| `DEEPSEEK_R1` | deepseek-r1 | +| `DEEPSEEK_V3_1` | deepseek-v3.1 | +| `QWQ` | qwq | +| `QWEN3` | qwen3 | \ No newline at end of file diff --git a/docs/models/modelgroup.md b/docs/models/modelgroup.md new file mode 100644 index 0000000..377c57c --- /dev/null +++ b/docs/models/modelgroup.md @@ -0,0 +1,28 @@ +# ModelGroup + +Tokenizer type used by the model + + +## Values + +| Name | Value | +| ----------- | ----------- | +| `ROUTER` | Router | +| `MEDIA` | Media | +| `OTHER` | Other | +| `GPT` | GPT | +| `CLAUDE` | Claude | +| `GEMINI` | Gemini | +| `GROK` | Grok | +| `COHERE` | Cohere | +| `NOVA` | Nova | +| `QWEN` | Qwen | +| `YI` | Yi | +| `DEEP_SEEK` | DeepSeek | +| `MISTRAL` | Mistral | +| `LLAMA2` | Llama2 | +| `LLAMA3` | Llama3 | +| `LLAMA4` | Llama4 | +| `PA_LM` | PaLM | +| `RWKV` | RWKV | +| `QWEN3` | Qwen3 | \ No newline at end of file diff --git a/docs/models/modelscountresponse.md b/docs/models/modelscountresponse.md new file mode 100644 index 0000000..887e7fc --- /dev/null +++ b/docs/models/modelscountresponse.md @@ -0,0 +1,10 @@ +# ModelsCountResponse + +Model count data + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | +| `data` | [models.ModelsCountResponseData](../models/modelscountresponsedata.md) | :heavy_check_mark: | Model count data | {
"count": 150
} | \ No newline at end of file diff --git a/docs/models/modelscountresponsedata.md b/docs/models/modelscountresponsedata.md new file mode 100644 index 0000000..ff995d4 --- /dev/null +++ b/docs/models/modelscountresponsedata.md @@ -0,0 +1,10 @@ +# ModelsCountResponseData + +Model count data + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------- | -------------------------------- | -------------------------------- | -------------------------------- | -------------------------------- | +| `count` | *float* | :heavy_check_mark: | Total number of available models | 150 | \ No newline at end of file diff --git a/docs/models/modelslistresponse.md b/docs/models/modelslistresponse.md new file mode 100644 index 0000000..a6fd460 --- /dev/null +++ b/docs/models/modelslistresponse.md @@ -0,0 +1,10 @@ +# ModelsListResponse + +List of available models + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | +| `data` | List[[models.Model](../models/model.md)] | :heavy_check_mark: | List of available models | \ No newline at end of file diff --git a/docs/models/namedtoolchoice.md b/docs/models/namedtoolchoice.md new file mode 100644 index 0000000..3685d60 --- /dev/null +++ b/docs/models/namedtoolchoice.md @@ -0,0 +1,9 @@ +# NamedToolChoice + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | +| `type` | *Literal["function"]* | :heavy_check_mark: | N/A | +| `function` | [models.NamedToolChoiceFunction](../models/namedtoolchoicefunction.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/namedtoolchoicefunction.md b/docs/models/namedtoolchoicefunction.md new file mode 100644 index 0000000..a4f8434 --- /dev/null +++ b/docs/models/namedtoolchoicefunction.md @@ -0,0 +1,8 @@ +# NamedToolChoiceFunction + + +## Fields + +| Field | Type | Required | Description | +| ------------------ | ------------------ | ------------------ | ------------------ | +| `name` | *str* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/notfoundresponseerrordata.md b/docs/models/notfoundresponseerrordata.md new file mode 100644 index 0000000..0ba2485 --- /dev/null +++ b/docs/models/notfoundresponseerrordata.md @@ -0,0 +1,12 @@ +# NotFoundResponseErrorData + +Error data for NotFoundResponse + + +## Fields + +| Field | Type | Required | Description | +| -------------------------- | -------------------------- | -------------------------- | -------------------------- | +| `code` | *int* | :heavy_check_mark: | N/A | +| `message` | *str* | :heavy_check_mark: | N/A | +| `metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/object.md b/docs/models/object.md new file mode 100644 index 0000000..6e2df0c --- /dev/null +++ b/docs/models/object.md @@ -0,0 +1,8 @@ +# Object + + +## Values + +| Name | Value | +| ---------- | ---------- | +| `RESPONSE` | response | \ No newline at end of file diff --git a/docs/models/objectembedding.md b/docs/models/objectembedding.md new file mode 100644 index 0000000..4f8c20d --- /dev/null +++ b/docs/models/objectembedding.md @@ -0,0 +1,8 @@ +# ObjectEmbedding + + +## Values + +| Name | Value | +| ----------- | ----------- | +| `EMBEDDING` | embedding | \ No newline at end of file diff --git a/docs/models/only.md b/docs/models/only.md new file mode 100644 index 0000000..5d94dd8 --- /dev/null +++ b/docs/models/only.md @@ -0,0 +1,17 @@ +# Only + + +## Supported Types + +### `models.ProviderName` + +```python +value: models.ProviderName = /* values here */ +``` + +### `str` + +```python +value: str = /* values here */ +``` + diff --git a/docs/models/openairesponsesannotation.md b/docs/models/openairesponsesannotation.md new file mode 100644 index 0000000..2460021 --- /dev/null +++ b/docs/models/openairesponsesannotation.md @@ -0,0 +1,23 @@ +# OpenAIResponsesAnnotation + + +## Supported Types + +### `models.FileCitation` + +```python +value: models.FileCitation = /* values here */ +``` + +### `models.URLCitation` + +```python +value: models.URLCitation = /* values here */ +``` + +### `models.FilePath` + +```python +value: models.FilePath = /* values here */ +``` + diff --git a/docs/models/openairesponsesincludable.md b/docs/models/openairesponsesincludable.md new file mode 100644 index 0000000..d3abf01 --- /dev/null +++ b/docs/models/openairesponsesincludable.md @@ -0,0 +1,12 @@ +# OpenAIResponsesIncludable + + +## Values + +| Name | Value | +| --------------------------------------- | --------------------------------------- | +| `FILE_SEARCH_CALL_RESULTS` | file_search_call.results | +| `MESSAGE_INPUT_IMAGE_IMAGE_URL` | message.input_image.image_url | +| `COMPUTER_CALL_OUTPUT_OUTPUT_IMAGE_URL` | computer_call_output.output.image_url | +| `REASONING_ENCRYPTED_CONTENT` | reasoning.encrypted_content | +| `CODE_INTERPRETER_CALL_OUTPUTS` | code_interpreter_call.outputs | \ No newline at end of file diff --git a/docs/models/openairesponsesincompletedetails.md b/docs/models/openairesponsesincompletedetails.md new file mode 100644 index 0000000..889f598 --- /dev/null +++ b/docs/models/openairesponsesincompletedetails.md @@ -0,0 +1,8 @@ +# OpenAIResponsesIncompleteDetails + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------- | ---------------------------------------------- | ---------------------------------------------- | ---------------------------------------------- | +| `reason` | [Optional[models.Reason]](../models/reason.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/openairesponsesinputcontent1.md b/docs/models/openairesponsesinputcontent1.md new file mode 100644 index 0000000..63399a2 --- /dev/null +++ b/docs/models/openairesponsesinputcontent1.md @@ -0,0 +1,29 @@ +# OpenAIResponsesInputContent1 + + +## Supported Types + +### `models.ResponseInputText` + +```python +value: models.ResponseInputText = /* values here */ +``` + +### `models.ResponseInputImage` + +```python +value: models.ResponseInputImage = /* values here */ +``` + +### `models.ResponseInputFile` + +```python +value: models.ResponseInputFile = /* values here */ +``` + +### `models.ResponseInputAudio` + +```python +value: models.ResponseInputAudio = /* values here */ +``` + diff --git a/docs/models/openairesponsesinputcontent2.md b/docs/models/openairesponsesinputcontent2.md new file mode 100644 index 0000000..1877559 --- /dev/null +++ b/docs/models/openairesponsesinputcontent2.md @@ -0,0 +1,17 @@ +# OpenAIResponsesInputContent2 + + +## Supported Types + +### `List[models.OpenAIResponsesInputContent1]` + +```python +value: List[models.OpenAIResponsesInputContent1] = /* values here */ +``` + +### `str` + +```python +value: str = /* values here */ +``` + diff --git a/docs/models/openairesponsesinputcontent3.md b/docs/models/openairesponsesinputcontent3.md new file mode 100644 index 0000000..eb18949 --- /dev/null +++ b/docs/models/openairesponsesinputcontent3.md @@ -0,0 +1,29 @@ +# OpenAIResponsesInputContent3 + + +## Supported Types + +### `models.ResponseInputText` + +```python +value: models.ResponseInputText = /* values here */ +``` + +### `models.ResponseInputImage` + +```python +value: models.ResponseInputImage = /* values here */ +``` + +### `models.ResponseInputFile` + +```python +value: models.ResponseInputFile = /* values here */ +``` + +### `models.ResponseInputAudio` + +```python +value: models.ResponseInputAudio = /* values here */ +``` + diff --git a/docs/models/openairesponsesinputfunctioncall.md b/docs/models/openairesponsesinputfunctioncall.md new file mode 100644 index 0000000..677c4da --- /dev/null +++ b/docs/models/openairesponsesinputfunctioncall.md @@ -0,0 +1,13 @@ +# OpenAIResponsesInputFunctionCall + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | +| `type` | [models.OpenAIResponsesInputTypeFunctionCall](../models/openairesponsesinputtypefunctioncall.md) | :heavy_check_mark: | N/A | | +| `call_id` | *str* | :heavy_check_mark: | N/A | | +| `name` | *str* | :heavy_check_mark: | N/A | | +| `arguments` | *str* | :heavy_check_mark: | N/A | | +| `id` | *Optional[str]* | :heavy_minus_sign: | N/A | | +| `status` | [OptionalNullable[models.ToolCallStatus]](../models/toolcallstatus.md) | :heavy_minus_sign: | N/A | completed | \ No newline at end of file diff --git a/docs/models/openairesponsesinputfunctioncalloutput.md b/docs/models/openairesponsesinputfunctioncalloutput.md new file mode 100644 index 0000000..1248ae8 --- /dev/null +++ b/docs/models/openairesponsesinputfunctioncalloutput.md @@ -0,0 +1,12 @@ +# OpenAIResponsesInputFunctionCallOutput + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ | +| `type` | [models.OpenAIResponsesInputTypeFunctionCallOutput](../models/openairesponsesinputtypefunctioncalloutput.md) | :heavy_check_mark: | N/A | | +| `id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | | +| `call_id` | *str* | :heavy_check_mark: | N/A | | +| `output` | *str* | :heavy_check_mark: | N/A | | +| `status` | [OptionalNullable[models.ToolCallStatus]](../models/toolcallstatus.md) | :heavy_minus_sign: | N/A | completed | \ No newline at end of file diff --git a/docs/models/openairesponsesinputmessage1.md b/docs/models/openairesponsesinputmessage1.md new file mode 100644 index 0000000..974bced --- /dev/null +++ b/docs/models/openairesponsesinputmessage1.md @@ -0,0 +1,10 @@ +# OpenAIResponsesInputMessage1 + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | +| `type` | [Optional[models.OpenAIResponsesInputTypeMessage1]](../models/openairesponsesinputtypemessage1.md) | :heavy_minus_sign: | N/A | +| `role` | [models.OpenAIResponsesInputRoleUnion1](../models/openairesponsesinputroleunion1.md) | :heavy_check_mark: | N/A | +| `content` | [models.OpenAIResponsesInputContent2](../models/openairesponsesinputcontent2.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/openairesponsesinputmessage2.md b/docs/models/openairesponsesinputmessage2.md new file mode 100644 index 0000000..e96c6a3 --- /dev/null +++ b/docs/models/openairesponsesinputmessage2.md @@ -0,0 +1,11 @@ +# OpenAIResponsesInputMessage2 + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | +| `id` | *str* | :heavy_check_mark: | N/A | +| `type` | [Optional[models.OpenAIResponsesInputTypeMessage2]](../models/openairesponsesinputtypemessage2.md) | :heavy_minus_sign: | N/A | +| `role` | [models.OpenAIResponsesInputRoleUnion2](../models/openairesponsesinputroleunion2.md) | :heavy_check_mark: | N/A | +| `content` | List[[models.OpenAIResponsesInputContent3](../models/openairesponsesinputcontent3.md)] | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/openairesponsesinputroleassistant.md b/docs/models/openairesponsesinputroleassistant.md new file mode 100644 index 0000000..11b1a65 --- /dev/null +++ b/docs/models/openairesponsesinputroleassistant.md @@ -0,0 +1,8 @@ +# OpenAIResponsesInputRoleAssistant + + +## Values + +| Name | Value | +| ----------- | ----------- | +| `ASSISTANT` | assistant | \ No newline at end of file diff --git a/docs/models/openairesponsesinputroledeveloper1.md b/docs/models/openairesponsesinputroledeveloper1.md new file mode 100644 index 0000000..96b7d42 --- /dev/null +++ b/docs/models/openairesponsesinputroledeveloper1.md @@ -0,0 +1,8 @@ +# OpenAIResponsesInputRoleDeveloper1 + + +## Values + +| Name | Value | +| ----------- | ----------- | +| `DEVELOPER` | developer | \ No newline at end of file diff --git a/docs/models/openairesponsesinputroledeveloper2.md b/docs/models/openairesponsesinputroledeveloper2.md new file mode 100644 index 0000000..bc3bdeb --- /dev/null +++ b/docs/models/openairesponsesinputroledeveloper2.md @@ -0,0 +1,8 @@ +# OpenAIResponsesInputRoleDeveloper2 + + +## Values + +| Name | Value | +| ----------- | ----------- | +| `DEVELOPER` | developer | \ No newline at end of file diff --git a/docs/models/openairesponsesinputrolesystem1.md b/docs/models/openairesponsesinputrolesystem1.md new file mode 100644 index 0000000..be6e117 --- /dev/null +++ b/docs/models/openairesponsesinputrolesystem1.md @@ -0,0 +1,8 @@ +# OpenAIResponsesInputRoleSystem1 + + +## Values + +| Name | Value | +| -------- | -------- | +| `SYSTEM` | system | \ No newline at end of file diff --git a/docs/models/openairesponsesinputrolesystem2.md b/docs/models/openairesponsesinputrolesystem2.md new file mode 100644 index 0000000..4781f31 --- /dev/null +++ b/docs/models/openairesponsesinputrolesystem2.md @@ -0,0 +1,8 @@ +# OpenAIResponsesInputRoleSystem2 + + +## Values + +| Name | Value | +| -------- | -------- | +| `SYSTEM` | system | \ No newline at end of file diff --git a/docs/models/openairesponsesinputroleunion1.md b/docs/models/openairesponsesinputroleunion1.md new file mode 100644 index 0000000..e73ff35 --- /dev/null +++ b/docs/models/openairesponsesinputroleunion1.md @@ -0,0 +1,29 @@ +# OpenAIResponsesInputRoleUnion1 + + +## Supported Types + +### `models.OpenAIResponsesInputRoleUser1` + +```python +value: models.OpenAIResponsesInputRoleUser1 = /* values here */ +``` + +### `models.OpenAIResponsesInputRoleSystem1` + +```python +value: models.OpenAIResponsesInputRoleSystem1 = /* values here */ +``` + +### `models.OpenAIResponsesInputRoleAssistant` + +```python +value: models.OpenAIResponsesInputRoleAssistant = /* values here */ +``` + +### `models.OpenAIResponsesInputRoleDeveloper1` + +```python +value: models.OpenAIResponsesInputRoleDeveloper1 = /* values here */ +``` + diff --git a/docs/models/openairesponsesinputroleunion2.md b/docs/models/openairesponsesinputroleunion2.md new file mode 100644 index 0000000..af6fa9e --- /dev/null +++ b/docs/models/openairesponsesinputroleunion2.md @@ -0,0 +1,23 @@ +# OpenAIResponsesInputRoleUnion2 + + +## Supported Types + +### `models.OpenAIResponsesInputRoleUser2` + +```python +value: models.OpenAIResponsesInputRoleUser2 = /* values here */ +``` + +### `models.OpenAIResponsesInputRoleSystem2` + +```python +value: models.OpenAIResponsesInputRoleSystem2 = /* values here */ +``` + +### `models.OpenAIResponsesInputRoleDeveloper2` + +```python +value: models.OpenAIResponsesInputRoleDeveloper2 = /* values here */ +``` + diff --git a/docs/models/openairesponsesinputroleuser1.md b/docs/models/openairesponsesinputroleuser1.md new file mode 100644 index 0000000..13fbb4c --- /dev/null +++ b/docs/models/openairesponsesinputroleuser1.md @@ -0,0 +1,8 @@ +# OpenAIResponsesInputRoleUser1 + + +## Values + +| Name | Value | +| ------ | ------ | +| `USER` | user | \ No newline at end of file diff --git a/docs/models/openairesponsesinputroleuser2.md b/docs/models/openairesponsesinputroleuser2.md new file mode 100644 index 0000000..8aa3c81 --- /dev/null +++ b/docs/models/openairesponsesinputroleuser2.md @@ -0,0 +1,8 @@ +# OpenAIResponsesInputRoleUser2 + + +## Values + +| Name | Value | +| ------ | ------ | +| `USER` | user | \ No newline at end of file diff --git a/docs/models/openairesponsesinputtypefunctioncall.md b/docs/models/openairesponsesinputtypefunctioncall.md new file mode 100644 index 0000000..575822c --- /dev/null +++ b/docs/models/openairesponsesinputtypefunctioncall.md @@ -0,0 +1,8 @@ +# OpenAIResponsesInputTypeFunctionCall + + +## Values + +| Name | Value | +| --------------- | --------------- | +| `FUNCTION_CALL` | function_call | \ No newline at end of file diff --git a/docs/models/openairesponsesinputtypefunctioncalloutput.md b/docs/models/openairesponsesinputtypefunctioncalloutput.md new file mode 100644 index 0000000..1b85dff --- /dev/null +++ b/docs/models/openairesponsesinputtypefunctioncalloutput.md @@ -0,0 +1,8 @@ +# OpenAIResponsesInputTypeFunctionCallOutput + + +## Values + +| Name | Value | +| ---------------------- | ---------------------- | +| `FUNCTION_CALL_OUTPUT` | function_call_output | \ No newline at end of file diff --git a/docs/models/openairesponsesinputtypemessage1.md b/docs/models/openairesponsesinputtypemessage1.md new file mode 100644 index 0000000..347cece --- /dev/null +++ b/docs/models/openairesponsesinputtypemessage1.md @@ -0,0 +1,8 @@ +# OpenAIResponsesInputTypeMessage1 + + +## Values + +| Name | Value | +| --------- | --------- | +| `MESSAGE` | message | \ No newline at end of file diff --git a/docs/models/openairesponsesinputtypemessage2.md b/docs/models/openairesponsesinputtypemessage2.md new file mode 100644 index 0000000..b90c11f --- /dev/null +++ b/docs/models/openairesponsesinputtypemessage2.md @@ -0,0 +1,8 @@ +# OpenAIResponsesInputTypeMessage2 + + +## Values + +| Name | Value | +| --------- | --------- | +| `MESSAGE` | message | \ No newline at end of file diff --git a/docs/models/openairesponsesinputunion.md b/docs/models/openairesponsesinputunion.md new file mode 100644 index 0000000..16a1317 --- /dev/null +++ b/docs/models/openairesponsesinputunion.md @@ -0,0 +1,23 @@ +# OpenAIResponsesInputUnion + + +## Supported Types + +### `str` + +```python +value: str = /* values here */ +``` + +### `List[models.OpenAIResponsesInputUnion1]` + +```python +value: List[models.OpenAIResponsesInputUnion1] = /* values here */ +``` + +### `Any` + +```python +value: Any = /* values here */ +``` + diff --git a/docs/models/openairesponsesinputunion1.md b/docs/models/openairesponsesinputunion1.md new file mode 100644 index 0000000..2d09bdd --- /dev/null +++ b/docs/models/openairesponsesinputunion1.md @@ -0,0 +1,41 @@ +# OpenAIResponsesInputUnion1 + + +## Supported Types + +### `models.OpenAIResponsesInputMessage1` + +```python +value: models.OpenAIResponsesInputMessage1 = /* values here */ +``` + +### `models.OpenAIResponsesInputMessage2` + +```python +value: models.OpenAIResponsesInputMessage2 = /* values here */ +``` + +### `models.OpenAIResponsesInputFunctionCallOutput` + +```python +value: models.OpenAIResponsesInputFunctionCallOutput = /* values here */ +``` + +### `models.OpenAIResponsesInputFunctionCall` + +```python +value: models.OpenAIResponsesInputFunctionCall = /* values here */ +``` + +### `models.OutputItemImageGenerationCall` + +```python +value: models.OutputItemImageGenerationCall = /* values here */ +``` + +### `models.OutputMessage` + +```python +value: models.OutputMessage = /* values here */ +``` + diff --git a/docs/models/openairesponsesprompt.md b/docs/models/openairesponsesprompt.md new file mode 100644 index 0000000..0d887d9 --- /dev/null +++ b/docs/models/openairesponsesprompt.md @@ -0,0 +1,9 @@ +# OpenAIResponsesPrompt + + +## Fields + +| Field | Type | Required | Description | +| ----------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- | +| `id` | *str* | :heavy_check_mark: | N/A | +| `variables` | Dict[str, [models.Variables](../models/variables.md)] | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/openairesponsesreasoningconfig.md b/docs/models/openairesponsesreasoningconfig.md new file mode 100644 index 0000000..6943fd0 --- /dev/null +++ b/docs/models/openairesponsesreasoningconfig.md @@ -0,0 +1,9 @@ +# OpenAIResponsesReasoningConfig + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | +| `effort` | [OptionalNullable[models.OpenAIResponsesReasoningEffort]](../models/openairesponsesreasoningeffort.md) | :heavy_minus_sign: | N/A | +| `summary` | [Optional[models.ReasoningSummaryVerbosity]](../models/reasoningsummaryverbosity.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/openairesponsesreasoningeffort.md b/docs/models/openairesponsesreasoningeffort.md new file mode 100644 index 0000000..bce9e5a --- /dev/null +++ b/docs/models/openairesponsesreasoningeffort.md @@ -0,0 +1,11 @@ +# OpenAIResponsesReasoningEffort + + +## Values + +| Name | Value | +| --------- | --------- | +| `HIGH` | high | +| `MEDIUM` | medium | +| `LOW` | low | +| `MINIMAL` | minimal | \ No newline at end of file diff --git a/docs/models/openairesponsesrefusalcontent.md b/docs/models/openairesponsesrefusalcontent.md new file mode 100644 index 0000000..5b3d9b4 --- /dev/null +++ b/docs/models/openairesponsesrefusalcontent.md @@ -0,0 +1,9 @@ +# OpenAIResponsesRefusalContent + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | +| `type` | [models.OpenAIResponsesRefusalContentType](../models/openairesponsesrefusalcontenttype.md) | :heavy_check_mark: | N/A | +| `refusal` | *str* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/openairesponsesrefusalcontenttype.md b/docs/models/openairesponsesrefusalcontenttype.md new file mode 100644 index 0000000..e94bdd2 --- /dev/null +++ b/docs/models/openairesponsesrefusalcontenttype.md @@ -0,0 +1,8 @@ +# OpenAIResponsesRefusalContentType + + +## Values + +| Name | Value | +| --------- | --------- | +| `REFUSAL` | refusal | \ No newline at end of file diff --git a/docs/models/openairesponsesresponsestatus.md b/docs/models/openairesponsesresponsestatus.md new file mode 100644 index 0000000..a362844 --- /dev/null +++ b/docs/models/openairesponsesresponsestatus.md @@ -0,0 +1,13 @@ +# OpenAIResponsesResponseStatus + + +## Values + +| Name | Value | +| ------------- | ------------- | +| `COMPLETED` | completed | +| `INCOMPLETE` | incomplete | +| `IN_PROGRESS` | in_progress | +| `FAILED` | failed | +| `CANCELLED` | cancelled | +| `QUEUED` | queued | \ No newline at end of file diff --git a/docs/models/openairesponsesservicetier.md b/docs/models/openairesponsesservicetier.md new file mode 100644 index 0000000..2ce2fd8 --- /dev/null +++ b/docs/models/openairesponsesservicetier.md @@ -0,0 +1,12 @@ +# OpenAIResponsesServiceTier + + +## Values + +| Name | Value | +| ---------- | ---------- | +| `AUTO` | auto | +| `DEFAULT` | default | +| `FLEX` | flex | +| `PRIORITY` | priority | +| `SCALE` | scale | \ No newline at end of file diff --git a/docs/models/openairesponsestoolchoice.md b/docs/models/openairesponsestoolchoice.md new file mode 100644 index 0000000..dd90be9 --- /dev/null +++ b/docs/models/openairesponsestoolchoice.md @@ -0,0 +1,8 @@ +# OpenAIResponsesToolChoice + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------- | -------------------------------- | -------------------------------- | -------------------------------- | +| `type` | [models.Type](../models/type.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/openairesponsestoolchoiceauto.md b/docs/models/openairesponsestoolchoiceauto.md new file mode 100644 index 0000000..5a958ab --- /dev/null +++ b/docs/models/openairesponsestoolchoiceauto.md @@ -0,0 +1,8 @@ +# OpenAIResponsesToolChoiceAuto + + +## Values + +| Name | Value | +| ------ | ------ | +| `AUTO` | auto | \ No newline at end of file diff --git a/docs/models/openairesponsestoolchoicefunction.md b/docs/models/openairesponsestoolchoicefunction.md new file mode 100644 index 0000000..a9d6714 --- /dev/null +++ b/docs/models/openairesponsestoolchoicefunction.md @@ -0,0 +1,9 @@ +# OpenAIResponsesToolChoiceFunction + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | +| `type` | [models.OpenAIResponsesToolChoiceTypeFunction](../models/openairesponsestoolchoicetypefunction.md) | :heavy_check_mark: | N/A | +| `name` | *str* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/openairesponsestoolchoicenone.md b/docs/models/openairesponsestoolchoicenone.md new file mode 100644 index 0000000..d5c51ac --- /dev/null +++ b/docs/models/openairesponsestoolchoicenone.md @@ -0,0 +1,8 @@ +# OpenAIResponsesToolChoiceNone + + +## Values + +| Name | Value | +| ------ | ------ | +| `NONE` | none | \ No newline at end of file diff --git a/docs/models/openairesponsestoolchoicerequired.md b/docs/models/openairesponsestoolchoicerequired.md new file mode 100644 index 0000000..57aefba --- /dev/null +++ b/docs/models/openairesponsestoolchoicerequired.md @@ -0,0 +1,8 @@ +# OpenAIResponsesToolChoiceRequired + + +## Values + +| Name | Value | +| ---------- | ---------- | +| `REQUIRED` | required | \ No newline at end of file diff --git a/docs/models/openairesponsestoolchoicetypefunction.md b/docs/models/openairesponsestoolchoicetypefunction.md new file mode 100644 index 0000000..de3caa3 --- /dev/null +++ b/docs/models/openairesponsestoolchoicetypefunction.md @@ -0,0 +1,8 @@ +# OpenAIResponsesToolChoiceTypeFunction + + +## Values + +| Name | Value | +| ---------- | ---------- | +| `FUNCTION` | function | \ No newline at end of file diff --git a/docs/models/openairesponsestoolchoicetypewebsearchpreview.md b/docs/models/openairesponsestoolchoicetypewebsearchpreview.md new file mode 100644 index 0000000..93b161b --- /dev/null +++ b/docs/models/openairesponsestoolchoicetypewebsearchpreview.md @@ -0,0 +1,8 @@ +# OpenAIResponsesToolChoiceTypeWebSearchPreview + + +## Values + +| Name | Value | +| -------------------- | -------------------- | +| `WEB_SEARCH_PREVIEW` | web_search_preview | \ No newline at end of file diff --git a/docs/models/openairesponsestoolchoicetypewebsearchpreview20250311.md b/docs/models/openairesponsestoolchoicetypewebsearchpreview20250311.md new file mode 100644 index 0000000..3162d39 --- /dev/null +++ b/docs/models/openairesponsestoolchoicetypewebsearchpreview20250311.md @@ -0,0 +1,8 @@ +# OpenAIResponsesToolChoiceTypeWebSearchPreview20250311 + + +## Values + +| Name | Value | +| ------------------------------- | ------------------------------- | +| `WEB_SEARCH_PREVIEW_2025_03_11` | web_search_preview_2025_03_11 | \ No newline at end of file diff --git a/docs/models/openairesponsestoolchoiceunion.md b/docs/models/openairesponsestoolchoiceunion.md new file mode 100644 index 0000000..b869a18 --- /dev/null +++ b/docs/models/openairesponsestoolchoiceunion.md @@ -0,0 +1,35 @@ +# OpenAIResponsesToolChoiceUnion + + +## Supported Types + +### `models.OpenAIResponsesToolChoiceAuto` + +```python +value: models.OpenAIResponsesToolChoiceAuto = /* values here */ +``` + +### `models.OpenAIResponsesToolChoiceNone` + +```python +value: models.OpenAIResponsesToolChoiceNone = /* values here */ +``` + +### `models.OpenAIResponsesToolChoiceRequired` + +```python +value: models.OpenAIResponsesToolChoiceRequired = /* values here */ +``` + +### `models.OpenAIResponsesToolChoiceFunction` + +```python +value: models.OpenAIResponsesToolChoiceFunction = /* values here */ +``` + +### `models.OpenAIResponsesToolChoice` + +```python +value: models.OpenAIResponsesToolChoice = /* values here */ +``` + diff --git a/docs/models/openairesponsestruncation.md b/docs/models/openairesponsestruncation.md new file mode 100644 index 0000000..aafecae --- /dev/null +++ b/docs/models/openairesponsestruncation.md @@ -0,0 +1,9 @@ +# OpenAIResponsesTruncation + + +## Values + +| Name | Value | +| ---------- | ---------- | +| `AUTO` | auto | +| `DISABLED` | disabled | \ No newline at end of file diff --git a/docs/models/openresponseseasyinputmessage.md b/docs/models/openresponseseasyinputmessage.md new file mode 100644 index 0000000..1ce49f7 --- /dev/null +++ b/docs/models/openresponseseasyinputmessage.md @@ -0,0 +1,10 @@ +# OpenResponsesEasyInputMessage + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | +| `type` | [Optional[models.OpenResponsesEasyInputMessageType]](../models/openresponseseasyinputmessagetype.md) | :heavy_minus_sign: | N/A | +| `role` | [models.OpenResponsesEasyInputMessageRoleUnion](../models/openresponseseasyinputmessageroleunion.md) | :heavy_check_mark: | N/A | +| `content` | [models.OpenResponsesEasyInputMessageContent2](../models/openresponseseasyinputmessagecontent2.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/openresponseseasyinputmessagecontent1.md b/docs/models/openresponseseasyinputmessagecontent1.md new file mode 100644 index 0000000..9dc36e2 --- /dev/null +++ b/docs/models/openresponseseasyinputmessagecontent1.md @@ -0,0 +1,29 @@ +# OpenResponsesEasyInputMessageContent1 + + +## Supported Types + +### `models.ResponseInputText` + +```python +value: models.ResponseInputText = /* values here */ +``` + +### `models.ResponseInputImage` + +```python +value: models.ResponseInputImage = /* values here */ +``` + +### `models.ResponseInputFile` + +```python +value: models.ResponseInputFile = /* values here */ +``` + +### `models.ResponseInputAudio` + +```python +value: models.ResponseInputAudio = /* values here */ +``` + diff --git a/docs/models/openresponseseasyinputmessagecontent2.md b/docs/models/openresponseseasyinputmessagecontent2.md new file mode 100644 index 0000000..fe0e91d --- /dev/null +++ b/docs/models/openresponseseasyinputmessagecontent2.md @@ -0,0 +1,17 @@ +# OpenResponsesEasyInputMessageContent2 + + +## Supported Types + +### `List[models.OpenResponsesEasyInputMessageContent1]` + +```python +value: List[models.OpenResponsesEasyInputMessageContent1] = /* values here */ +``` + +### `str` + +```python +value: str = /* values here */ +``` + diff --git a/docs/models/openresponseseasyinputmessageroleassistant.md b/docs/models/openresponseseasyinputmessageroleassistant.md new file mode 100644 index 0000000..680dd73 --- /dev/null +++ b/docs/models/openresponseseasyinputmessageroleassistant.md @@ -0,0 +1,8 @@ +# OpenResponsesEasyInputMessageRoleAssistant + + +## Values + +| Name | Value | +| ----------- | ----------- | +| `ASSISTANT` | assistant | \ No newline at end of file diff --git a/docs/models/openresponseseasyinputmessageroledeveloper.md b/docs/models/openresponseseasyinputmessageroledeveloper.md new file mode 100644 index 0000000..5bd1d42 --- /dev/null +++ b/docs/models/openresponseseasyinputmessageroledeveloper.md @@ -0,0 +1,8 @@ +# OpenResponsesEasyInputMessageRoleDeveloper + + +## Values + +| Name | Value | +| ----------- | ----------- | +| `DEVELOPER` | developer | \ No newline at end of file diff --git a/docs/models/openresponseseasyinputmessagerolesystem.md b/docs/models/openresponseseasyinputmessagerolesystem.md new file mode 100644 index 0000000..9f66fe1 --- /dev/null +++ b/docs/models/openresponseseasyinputmessagerolesystem.md @@ -0,0 +1,8 @@ +# OpenResponsesEasyInputMessageRoleSystem + + +## Values + +| Name | Value | +| -------- | -------- | +| `SYSTEM` | system | \ No newline at end of file diff --git a/docs/models/openresponseseasyinputmessageroleunion.md b/docs/models/openresponseseasyinputmessageroleunion.md new file mode 100644 index 0000000..13cefd4 --- /dev/null +++ b/docs/models/openresponseseasyinputmessageroleunion.md @@ -0,0 +1,29 @@ +# OpenResponsesEasyInputMessageRoleUnion + + +## Supported Types + +### `models.OpenResponsesEasyInputMessageRoleUser` + +```python +value: models.OpenResponsesEasyInputMessageRoleUser = /* values here */ +``` + +### `models.OpenResponsesEasyInputMessageRoleSystem` + +```python +value: models.OpenResponsesEasyInputMessageRoleSystem = /* values here */ +``` + +### `models.OpenResponsesEasyInputMessageRoleAssistant` + +```python +value: models.OpenResponsesEasyInputMessageRoleAssistant = /* values here */ +``` + +### `models.OpenResponsesEasyInputMessageRoleDeveloper` + +```python +value: models.OpenResponsesEasyInputMessageRoleDeveloper = /* values here */ +``` + diff --git a/docs/models/openresponseseasyinputmessageroleuser.md b/docs/models/openresponseseasyinputmessageroleuser.md new file mode 100644 index 0000000..b704af0 --- /dev/null +++ b/docs/models/openresponseseasyinputmessageroleuser.md @@ -0,0 +1,8 @@ +# OpenResponsesEasyInputMessageRoleUser + + +## Values + +| Name | Value | +| ------ | ------ | +| `USER` | user | \ No newline at end of file diff --git a/docs/models/openresponseseasyinputmessagetype.md b/docs/models/openresponseseasyinputmessagetype.md new file mode 100644 index 0000000..d34a701 --- /dev/null +++ b/docs/models/openresponseseasyinputmessagetype.md @@ -0,0 +1,8 @@ +# OpenResponsesEasyInputMessageType + + +## Values + +| Name | Value | +| --------- | --------- | +| `MESSAGE` | message | \ No newline at end of file diff --git a/docs/models/openresponseserrorevent.md b/docs/models/openresponseserrorevent.md new file mode 100644 index 0000000..f827546 --- /dev/null +++ b/docs/models/openresponseserrorevent.md @@ -0,0 +1,14 @@ +# OpenResponsesErrorEvent + +Event emitted when an error occurs during streaming + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | +| `type` | [models.OpenResponsesErrorEventType](../models/openresponseserroreventtype.md) | :heavy_check_mark: | N/A | +| `code` | *Nullable[str]* | :heavy_check_mark: | N/A | +| `message` | *str* | :heavy_check_mark: | N/A | +| `param` | *Nullable[str]* | :heavy_check_mark: | N/A | +| `sequence_number` | *float* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/openresponseserroreventtype.md b/docs/models/openresponseserroreventtype.md new file mode 100644 index 0000000..32e832c --- /dev/null +++ b/docs/models/openresponseserroreventtype.md @@ -0,0 +1,8 @@ +# OpenResponsesErrorEventType + + +## Values + +| Name | Value | +| ------- | ------- | +| `ERROR` | error | \ No newline at end of file diff --git a/docs/models/openresponsesfunctioncalloutput.md b/docs/models/openresponsesfunctioncalloutput.md new file mode 100644 index 0000000..5a0c310 --- /dev/null +++ b/docs/models/openresponsesfunctioncalloutput.md @@ -0,0 +1,14 @@ +# OpenResponsesFunctionCallOutput + +The output from a function call execution + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | +| `type` | [models.OpenResponsesFunctionCallOutputType](../models/openresponsesfunctioncalloutputtype.md) | :heavy_check_mark: | N/A | | +| `id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | | +| `call_id` | *str* | :heavy_check_mark: | N/A | | +| `output` | *str* | :heavy_check_mark: | N/A | | +| `status` | [OptionalNullable[models.ToolCallStatus]](../models/toolcallstatus.md) | :heavy_minus_sign: | N/A | completed | \ No newline at end of file diff --git a/docs/models/openresponsesfunctioncalloutputtype.md b/docs/models/openresponsesfunctioncalloutputtype.md new file mode 100644 index 0000000..41370cf --- /dev/null +++ b/docs/models/openresponsesfunctioncalloutputtype.md @@ -0,0 +1,8 @@ +# OpenResponsesFunctionCallOutputType + + +## Values + +| Name | Value | +| ---------------------- | ---------------------- | +| `FUNCTION_CALL_OUTPUT` | function_call_output | \ No newline at end of file diff --git a/docs/models/openresponsesfunctiontoolcall.md b/docs/models/openresponsesfunctiontoolcall.md new file mode 100644 index 0000000..e6f68d3 --- /dev/null +++ b/docs/models/openresponsesfunctiontoolcall.md @@ -0,0 +1,15 @@ +# OpenResponsesFunctionToolCall + +A function call initiated by the model + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | +| `type` | [models.OpenResponsesFunctionToolCallType](../models/openresponsesfunctiontoolcalltype.md) | :heavy_check_mark: | N/A | | +| `call_id` | *str* | :heavy_check_mark: | N/A | | +| `name` | *str* | :heavy_check_mark: | N/A | | +| `arguments` | *str* | :heavy_check_mark: | N/A | | +| `id` | *str* | :heavy_check_mark: | N/A | | +| `status` | [OptionalNullable[models.ToolCallStatus]](../models/toolcallstatus.md) | :heavy_minus_sign: | N/A | completed | \ No newline at end of file diff --git a/docs/models/openresponsesfunctiontoolcalltype.md b/docs/models/openresponsesfunctiontoolcalltype.md new file mode 100644 index 0000000..e7b6246 --- /dev/null +++ b/docs/models/openresponsesfunctiontoolcalltype.md @@ -0,0 +1,8 @@ +# OpenResponsesFunctionToolCallType + + +## Values + +| Name | Value | +| --------------- | --------------- | +| `FUNCTION_CALL` | function_call | \ No newline at end of file diff --git a/docs/models/openresponsesimagegencallcompleted.md b/docs/models/openresponsesimagegencallcompleted.md new file mode 100644 index 0000000..98f64f3 --- /dev/null +++ b/docs/models/openresponsesimagegencallcompleted.md @@ -0,0 +1,13 @@ +# OpenResponsesImageGenCallCompleted + +Image generation call completed + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | +| `type` | [models.OpenResponsesImageGenCallCompletedType](../models/openresponsesimagegencallcompletedtype.md) | :heavy_check_mark: | N/A | +| `item_id` | *str* | :heavy_check_mark: | N/A | +| `output_index` | *float* | :heavy_check_mark: | N/A | +| `sequence_number` | *float* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/openresponsesimagegencallcompletedtype.md b/docs/models/openresponsesimagegencallcompletedtype.md new file mode 100644 index 0000000..a7316e0 --- /dev/null +++ b/docs/models/openresponsesimagegencallcompletedtype.md @@ -0,0 +1,8 @@ +# OpenResponsesImageGenCallCompletedType + + +## Values + +| Name | Value | +| ------------------------------------------ | ------------------------------------------ | +| `RESPONSE_IMAGE_GENERATION_CALL_COMPLETED` | response.image_generation_call.completed | \ No newline at end of file diff --git a/docs/models/openresponsesimagegencallgenerating.md b/docs/models/openresponsesimagegencallgenerating.md new file mode 100644 index 0000000..552f033 --- /dev/null +++ b/docs/models/openresponsesimagegencallgenerating.md @@ -0,0 +1,13 @@ +# OpenResponsesImageGenCallGenerating + +Image generation call is generating + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | +| `type` | [models.OpenResponsesImageGenCallGeneratingType](../models/openresponsesimagegencallgeneratingtype.md) | :heavy_check_mark: | N/A | +| `item_id` | *str* | :heavy_check_mark: | N/A | +| `output_index` | *float* | :heavy_check_mark: | N/A | +| `sequence_number` | *float* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/openresponsesimagegencallgeneratingtype.md b/docs/models/openresponsesimagegencallgeneratingtype.md new file mode 100644 index 0000000..68c6984 --- /dev/null +++ b/docs/models/openresponsesimagegencallgeneratingtype.md @@ -0,0 +1,8 @@ +# OpenResponsesImageGenCallGeneratingType + + +## Values + +| Name | Value | +| ------------------------------------------- | ------------------------------------------- | +| `RESPONSE_IMAGE_GENERATION_CALL_GENERATING` | response.image_generation_call.generating | \ No newline at end of file diff --git a/docs/models/openresponsesimagegencallinprogress.md b/docs/models/openresponsesimagegencallinprogress.md new file mode 100644 index 0000000..6db198f --- /dev/null +++ b/docs/models/openresponsesimagegencallinprogress.md @@ -0,0 +1,13 @@ +# OpenResponsesImageGenCallInProgress + +Image generation call in progress + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | +| `type` | [models.OpenResponsesImageGenCallInProgressType](../models/openresponsesimagegencallinprogresstype.md) | :heavy_check_mark: | N/A | +| `item_id` | *str* | :heavy_check_mark: | N/A | +| `output_index` | *float* | :heavy_check_mark: | N/A | +| `sequence_number` | *float* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/openresponsesimagegencallinprogresstype.md b/docs/models/openresponsesimagegencallinprogresstype.md new file mode 100644 index 0000000..f681053 --- /dev/null +++ b/docs/models/openresponsesimagegencallinprogresstype.md @@ -0,0 +1,8 @@ +# OpenResponsesImageGenCallInProgressType + + +## Values + +| Name | Value | +| -------------------------------------------- | -------------------------------------------- | +| `RESPONSE_IMAGE_GENERATION_CALL_IN_PROGRESS` | response.image_generation_call.in_progress | \ No newline at end of file diff --git a/docs/models/openresponsesimagegencallpartialimage.md b/docs/models/openresponsesimagegencallpartialimage.md new file mode 100644 index 0000000..c0e325d --- /dev/null +++ b/docs/models/openresponsesimagegencallpartialimage.md @@ -0,0 +1,15 @@ +# OpenResponsesImageGenCallPartialImage + +Image generation call with partial image + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | +| `type` | [models.OpenResponsesImageGenCallPartialImageType](../models/openresponsesimagegencallpartialimagetype.md) | :heavy_check_mark: | N/A | +| `item_id` | *str* | :heavy_check_mark: | N/A | +| `output_index` | *float* | :heavy_check_mark: | N/A | +| `sequence_number` | *float* | :heavy_check_mark: | N/A | +| `partial_image_b64` | *str* | :heavy_check_mark: | N/A | +| `partial_image_index` | *float* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/openresponsesimagegencallpartialimagetype.md b/docs/models/openresponsesimagegencallpartialimagetype.md new file mode 100644 index 0000000..b2cc016 --- /dev/null +++ b/docs/models/openresponsesimagegencallpartialimagetype.md @@ -0,0 +1,8 @@ +# OpenResponsesImageGenCallPartialImageType + + +## Values + +| Name | Value | +| ---------------------------------------------- | ---------------------------------------------- | +| `RESPONSE_IMAGE_GENERATION_CALL_PARTIAL_IMAGE` | response.image_generation_call.partial_image | \ No newline at end of file diff --git a/docs/models/openresponsesinput.md b/docs/models/openresponsesinput.md new file mode 100644 index 0000000..199b09d --- /dev/null +++ b/docs/models/openresponsesinput.md @@ -0,0 +1,19 @@ +# OpenResponsesInput + +Input for a response request - can be a string or array of items + + +## Supported Types + +### `str` + +```python +value: str = /* values here */ +``` + +### `List[models.OpenResponsesInput1]` + +```python +value: List[models.OpenResponsesInput1] = /* values here */ +``` + diff --git a/docs/models/openresponsesinput1.md b/docs/models/openresponsesinput1.md new file mode 100644 index 0000000..5362f5a --- /dev/null +++ b/docs/models/openresponsesinput1.md @@ -0,0 +1,71 @@ +# OpenResponsesInput1 + + +## Supported Types + +### `models.OpenResponsesReasoning` + +```python +value: models.OpenResponsesReasoning = /* values here */ +``` + +### `models.OpenResponsesEasyInputMessage` + +```python +value: models.OpenResponsesEasyInputMessage = /* values here */ +``` + +### `models.OpenResponsesInputMessageItem` + +```python +value: models.OpenResponsesInputMessageItem = /* values here */ +``` + +### `models.OpenResponsesFunctionToolCall` + +```python +value: models.OpenResponsesFunctionToolCall = /* values here */ +``` + +### `models.OpenResponsesFunctionCallOutput` + +```python +value: models.OpenResponsesFunctionCallOutput = /* values here */ +``` + +### `models.ResponsesOutputMessage` + +```python +value: models.ResponsesOutputMessage = /* values here */ +``` + +### `models.ResponsesOutputItemReasoning` + +```python +value: models.ResponsesOutputItemReasoning = /* values here */ +``` + +### `models.ResponsesOutputItemFunctionCall` + +```python +value: models.ResponsesOutputItemFunctionCall = /* values here */ +``` + +### `models.ResponsesWebSearchCallOutput` + +```python +value: models.ResponsesWebSearchCallOutput = /* values here */ +``` + +### `models.ResponsesOutputItemFileSearchCall` + +```python +value: models.ResponsesOutputItemFileSearchCall = /* values here */ +``` + +### `models.ResponsesImageGenerationCall` + +```python +value: models.ResponsesImageGenerationCall = /* values here */ +``` + diff --git a/docs/models/openresponsesinputmessageitem.md b/docs/models/openresponsesinputmessageitem.md new file mode 100644 index 0000000..8636256 --- /dev/null +++ b/docs/models/openresponsesinputmessageitem.md @@ -0,0 +1,11 @@ +# OpenResponsesInputMessageItem + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | +| `id` | *Optional[str]* | :heavy_minus_sign: | N/A | +| `type` | [Optional[models.OpenResponsesInputMessageItemType]](../models/openresponsesinputmessageitemtype.md) | :heavy_minus_sign: | N/A | +| `role` | [models.OpenResponsesInputMessageItemRoleUnion](../models/openresponsesinputmessageitemroleunion.md) | :heavy_check_mark: | N/A | +| `content` | List[[models.OpenResponsesInputMessageItemContent](../models/openresponsesinputmessageitemcontent.md)] | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/openresponsesinputmessageitemcontent.md b/docs/models/openresponsesinputmessageitemcontent.md new file mode 100644 index 0000000..0a06d74 --- /dev/null +++ b/docs/models/openresponsesinputmessageitemcontent.md @@ -0,0 +1,29 @@ +# OpenResponsesInputMessageItemContent + + +## Supported Types + +### `models.ResponseInputText` + +```python +value: models.ResponseInputText = /* values here */ +``` + +### `models.ResponseInputImage` + +```python +value: models.ResponseInputImage = /* values here */ +``` + +### `models.ResponseInputFile` + +```python +value: models.ResponseInputFile = /* values here */ +``` + +### `models.ResponseInputAudio` + +```python +value: models.ResponseInputAudio = /* values here */ +``` + diff --git a/docs/models/openresponsesinputmessageitemroledeveloper.md b/docs/models/openresponsesinputmessageitemroledeveloper.md new file mode 100644 index 0000000..13450f7 --- /dev/null +++ b/docs/models/openresponsesinputmessageitemroledeveloper.md @@ -0,0 +1,8 @@ +# OpenResponsesInputMessageItemRoleDeveloper + + +## Values + +| Name | Value | +| ----------- | ----------- | +| `DEVELOPER` | developer | \ No newline at end of file diff --git a/docs/models/openresponsesinputmessageitemrolesystem.md b/docs/models/openresponsesinputmessageitemrolesystem.md new file mode 100644 index 0000000..e42d972 --- /dev/null +++ b/docs/models/openresponsesinputmessageitemrolesystem.md @@ -0,0 +1,8 @@ +# OpenResponsesInputMessageItemRoleSystem + + +## Values + +| Name | Value | +| -------- | -------- | +| `SYSTEM` | system | \ No newline at end of file diff --git a/docs/models/openresponsesinputmessageitemroleunion.md b/docs/models/openresponsesinputmessageitemroleunion.md new file mode 100644 index 0000000..8c873a8 --- /dev/null +++ b/docs/models/openresponsesinputmessageitemroleunion.md @@ -0,0 +1,23 @@ +# OpenResponsesInputMessageItemRoleUnion + + +## Supported Types + +### `models.OpenResponsesInputMessageItemRoleUser` + +```python +value: models.OpenResponsesInputMessageItemRoleUser = /* values here */ +``` + +### `models.OpenResponsesInputMessageItemRoleSystem` + +```python +value: models.OpenResponsesInputMessageItemRoleSystem = /* values here */ +``` + +### `models.OpenResponsesInputMessageItemRoleDeveloper` + +```python +value: models.OpenResponsesInputMessageItemRoleDeveloper = /* values here */ +``` + diff --git a/docs/models/openresponsesinputmessageitemroleuser.md b/docs/models/openresponsesinputmessageitemroleuser.md new file mode 100644 index 0000000..5e8163c --- /dev/null +++ b/docs/models/openresponsesinputmessageitemroleuser.md @@ -0,0 +1,8 @@ +# OpenResponsesInputMessageItemRoleUser + + +## Values + +| Name | Value | +| ------ | ------ | +| `USER` | user | \ No newline at end of file diff --git a/docs/models/openresponsesinputmessageitemtype.md b/docs/models/openresponsesinputmessageitemtype.md new file mode 100644 index 0000000..a468aee --- /dev/null +++ b/docs/models/openresponsesinputmessageitemtype.md @@ -0,0 +1,8 @@ +# OpenResponsesInputMessageItemType + + +## Values + +| Name | Value | +| --------- | --------- | +| `MESSAGE` | message | \ No newline at end of file diff --git a/docs/models/openresponseslogprobs.md b/docs/models/openresponseslogprobs.md new file mode 100644 index 0000000..d577144 --- /dev/null +++ b/docs/models/openresponseslogprobs.md @@ -0,0 +1,12 @@ +# OpenResponsesLogProbs + +Log probability information for a token + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | +| `logprob` | *float* | :heavy_check_mark: | N/A | +| `token` | *str* | :heavy_check_mark: | N/A | +| `top_logprobs` | List[[models.OpenResponsesTopLogprobs](../models/openresponsestoplogprobs.md)] | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/openresponsesnonstreamingresponse.md b/docs/models/openresponsesnonstreamingresponse.md new file mode 100644 index 0000000..f56ebfc --- /dev/null +++ b/docs/models/openresponsesnonstreamingresponse.md @@ -0,0 +1,40 @@ +# OpenResponsesNonStreamingResponse + +Complete non-streaming response from the Responses API + + +## Fields + +| Field | Type | Required | Description | Example | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `id` | *str* | :heavy_check_mark: | N/A | | +| `object` | [models.Object](../models/object.md) | :heavy_check_mark: | N/A | | +| `created_at` | *float* | :heavy_check_mark: | N/A | | +| `model` | *str* | :heavy_check_mark: | N/A | | +| `status` | [Optional[models.OpenAIResponsesResponseStatus]](../models/openairesponsesresponsestatus.md) | :heavy_minus_sign: | N/A | | +| `output` | List[[models.ResponsesOutputItem](../models/responsesoutputitem.md)] | :heavy_check_mark: | N/A | | +| `user` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | | +| `output_text` | *Optional[str]* | :heavy_minus_sign: | N/A | | +| `prompt_cache_key` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | | +| `safety_identifier` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | | +| `error` | [Nullable[models.ResponsesErrorField]](../models/responseserrorfield.md) | :heavy_check_mark: | Error information returned from the API | {
"code": "rate_limit_exceeded",
"message": "Rate limit exceeded. Please try again later."
} | +| `incomplete_details` | [Nullable[models.OpenAIResponsesIncompleteDetails]](../models/openairesponsesincompletedetails.md) | :heavy_check_mark: | N/A | | +| `usage` | [Optional[models.OpenResponsesUsage]](../models/openresponsesusage.md) | :heavy_minus_sign: | Token usage information for the response | {
"input_tokens": 10,
"output_tokens": 25,
"total_tokens": 35,
"input_tokens_details": {
"cached_tokens": 0
},
"output_tokens_details": {
"reasoning_tokens": 0
},
"cost": 0.0012,
"cost_details": {
"upstream_inference_cost": null,
"upstream_inference_input_cost": 0.0008,
"upstream_inference_output_cost": 0.0004
}
} | +| `max_tool_calls` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | | +| `top_logprobs` | *Optional[float]* | :heavy_minus_sign: | N/A | | +| `max_output_tokens` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | | +| `temperature` | *Nullable[float]* | :heavy_check_mark: | N/A | | +| `top_p` | *Nullable[float]* | :heavy_check_mark: | N/A | | +| `instructions` | [Nullable[models.OpenAIResponsesInputUnion]](../models/openairesponsesinputunion.md) | :heavy_check_mark: | N/A | | +| `metadata` | Dict[str, *str*] | :heavy_check_mark: | Metadata key-value pairs for the request. Keys must be ≤64 characters and cannot contain brackets. Values must be ≤512 characters. Maximum 16 pairs allowed. | {
"user_id": "123",
"session_id": "abc-def-ghi"
} | +| `tools` | List[[models.OpenResponsesNonStreamingResponseToolUnion](../models/openresponsesnonstreamingresponsetoolunion.md)] | :heavy_check_mark: | N/A | | +| `tool_choice` | [models.OpenAIResponsesToolChoiceUnion](../models/openairesponsestoolchoiceunion.md) | :heavy_check_mark: | N/A | | +| `parallel_tool_calls` | *bool* | :heavy_check_mark: | N/A | | +| `prompt` | [OptionalNullable[models.OpenAIResponsesPrompt]](../models/openairesponsesprompt.md) | :heavy_minus_sign: | N/A | | +| `background` | *OptionalNullable[bool]* | :heavy_minus_sign: | N/A | | +| `previous_response_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | | +| `reasoning` | [OptionalNullable[models.OpenAIResponsesReasoningConfig]](../models/openairesponsesreasoningconfig.md) | :heavy_minus_sign: | N/A | | +| `service_tier` | [OptionalNullable[models.OpenAIResponsesServiceTier]](../models/openairesponsesservicetier.md) | :heavy_minus_sign: | N/A | | +| `store` | *Optional[bool]* | :heavy_minus_sign: | N/A | | +| `truncation` | [OptionalNullable[models.OpenAIResponsesTruncation]](../models/openairesponsestruncation.md) | :heavy_minus_sign: | N/A | | +| `text` | [Optional[models.ResponseTextConfig]](../models/responsetextconfig.md) | :heavy_minus_sign: | Text output configuration including format and verbosity | {
"format": {
"type": "text"
},
"verbosity": "medium"
} | \ No newline at end of file diff --git a/docs/models/openresponsesnonstreamingresponsetoolfunction.md b/docs/models/openresponsesnonstreamingresponsetoolfunction.md new file mode 100644 index 0000000..5992ce2 --- /dev/null +++ b/docs/models/openresponsesnonstreamingresponsetoolfunction.md @@ -0,0 +1,14 @@ +# OpenResponsesNonStreamingResponseToolFunction + +Function tool definition + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | +| `type` | [models.OpenResponsesNonStreamingResponseType](../models/openresponsesnonstreamingresponsetype.md) | :heavy_check_mark: | N/A | +| `name` | *str* | :heavy_check_mark: | N/A | +| `description` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | +| `strict` | *OptionalNullable[bool]* | :heavy_minus_sign: | N/A | +| `parameters` | Dict[str, *Nullable[Any]*] | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/openresponsesnonstreamingresponsetoolunion.md b/docs/models/openresponsesnonstreamingresponsetoolunion.md new file mode 100644 index 0000000..92f975c --- /dev/null +++ b/docs/models/openresponsesnonstreamingresponsetoolunion.md @@ -0,0 +1,35 @@ +# OpenResponsesNonStreamingResponseToolUnion + + +## Supported Types + +### `models.OpenResponsesNonStreamingResponseToolFunction` + +```python +value: models.OpenResponsesNonStreamingResponseToolFunction = /* values here */ +``` + +### `models.OpenResponsesWebSearchPreviewTool` + +```python +value: models.OpenResponsesWebSearchPreviewTool = /* values here */ +``` + +### `models.OpenResponsesWebSearchPreview20250311Tool` + +```python +value: models.OpenResponsesWebSearchPreview20250311Tool = /* values here */ +``` + +### `models.OpenResponsesWebSearchTool` + +```python +value: models.OpenResponsesWebSearchTool = /* values here */ +``` + +### `models.OpenResponsesWebSearch20250826Tool` + +```python +value: models.OpenResponsesWebSearch20250826Tool = /* values here */ +``` + diff --git a/docs/models/openresponsesnonstreamingresponsetype.md b/docs/models/openresponsesnonstreamingresponsetype.md new file mode 100644 index 0000000..5c2d918 --- /dev/null +++ b/docs/models/openresponsesnonstreamingresponsetype.md @@ -0,0 +1,8 @@ +# OpenResponsesNonStreamingResponseType + + +## Values + +| Name | Value | +| ---------- | ---------- | +| `FUNCTION` | function | \ No newline at end of file diff --git a/docs/models/openresponsesreasoning.md b/docs/models/openresponsesreasoning.md new file mode 100644 index 0000000..f2fcf09 --- /dev/null +++ b/docs/models/openresponsesreasoning.md @@ -0,0 +1,17 @@ +# OpenResponsesReasoning + +Reasoning output item with signature and format extensions + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | +| `type` | [models.OpenResponsesReasoningType](../models/openresponsesreasoningtype.md) | :heavy_check_mark: | N/A | +| `id` | *str* | :heavy_check_mark: | N/A | +| `content` | List[[models.ReasoningTextContent](../models/reasoningtextcontent.md)] | :heavy_minus_sign: | N/A | +| `summary` | List[[models.ReasoningSummaryText](../models/reasoningsummarytext.md)] | :heavy_check_mark: | N/A | +| `encrypted_content` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | +| `status` | [Optional[models.OpenResponsesReasoningStatusUnion]](../models/openresponsesreasoningstatusunion.md) | :heavy_minus_sign: | N/A | +| `signature` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | +| `format_` | [OptionalNullable[models.OpenResponsesReasoningFormat]](../models/openresponsesreasoningformat.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/openresponsesreasoningconfig.md b/docs/models/openresponsesreasoningconfig.md new file mode 100644 index 0000000..36fcf9c --- /dev/null +++ b/docs/models/openresponsesreasoningconfig.md @@ -0,0 +1,13 @@ +# OpenResponsesReasoningConfig + +Configuration for reasoning mode in the response + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | +| `effort` | [OptionalNullable[models.OpenAIResponsesReasoningEffort]](../models/openairesponsesreasoningeffort.md) | :heavy_minus_sign: | N/A | +| `summary` | [Optional[models.ReasoningSummaryVerbosity]](../models/reasoningsummaryverbosity.md) | :heavy_minus_sign: | N/A | +| `max_tokens` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | +| `enabled` | *OptionalNullable[bool]* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/openresponsesreasoningdeltaevent.md b/docs/models/openresponsesreasoningdeltaevent.md new file mode 100644 index 0000000..ef8d648 --- /dev/null +++ b/docs/models/openresponsesreasoningdeltaevent.md @@ -0,0 +1,15 @@ +# OpenResponsesReasoningDeltaEvent + +Event emitted when reasoning text delta is streamed + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | +| `type` | [models.OpenResponsesReasoningDeltaEventType](../models/openresponsesreasoningdeltaeventtype.md) | :heavy_check_mark: | N/A | +| `output_index` | *float* | :heavy_check_mark: | N/A | +| `item_id` | *str* | :heavy_check_mark: | N/A | +| `content_index` | *float* | :heavy_check_mark: | N/A | +| `delta` | *str* | :heavy_check_mark: | N/A | +| `sequence_number` | *float* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/openresponsesreasoningdeltaeventtype.md b/docs/models/openresponsesreasoningdeltaeventtype.md new file mode 100644 index 0000000..9edb675 --- /dev/null +++ b/docs/models/openresponsesreasoningdeltaeventtype.md @@ -0,0 +1,8 @@ +# OpenResponsesReasoningDeltaEventType + + +## Values + +| Name | Value | +| ------------------------------- | ------------------------------- | +| `RESPONSE_REASONING_TEXT_DELTA` | response.reasoning_text.delta | \ No newline at end of file diff --git a/docs/models/openresponsesreasoningdoneevent.md b/docs/models/openresponsesreasoningdoneevent.md new file mode 100644 index 0000000..9d457e0 --- /dev/null +++ b/docs/models/openresponsesreasoningdoneevent.md @@ -0,0 +1,15 @@ +# OpenResponsesReasoningDoneEvent + +Event emitted when reasoning text streaming is complete + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | +| `type` | [models.OpenResponsesReasoningDoneEventType](../models/openresponsesreasoningdoneeventtype.md) | :heavy_check_mark: | N/A | +| `output_index` | *float* | :heavy_check_mark: | N/A | +| `item_id` | *str* | :heavy_check_mark: | N/A | +| `content_index` | *float* | :heavy_check_mark: | N/A | +| `text` | *str* | :heavy_check_mark: | N/A | +| `sequence_number` | *float* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/openresponsesreasoningdoneeventtype.md b/docs/models/openresponsesreasoningdoneeventtype.md new file mode 100644 index 0000000..acd40e2 --- /dev/null +++ b/docs/models/openresponsesreasoningdoneeventtype.md @@ -0,0 +1,8 @@ +# OpenResponsesReasoningDoneEventType + + +## Values + +| Name | Value | +| ------------------------------ | ------------------------------ | +| `RESPONSE_REASONING_TEXT_DONE` | response.reasoning_text.done | \ No newline at end of file diff --git a/docs/models/openresponsesreasoningformat.md b/docs/models/openresponsesreasoningformat.md new file mode 100644 index 0000000..491cc90 --- /dev/null +++ b/docs/models/openresponsesreasoningformat.md @@ -0,0 +1,11 @@ +# OpenResponsesReasoningFormat + + +## Values + +| Name | Value | +| --------------------- | --------------------- | +| `UNKNOWN` | unknown | +| `OPENAI_RESPONSES_V1` | openai-responses-v1 | +| `XAI_RESPONSES_V1` | xai-responses-v1 | +| `ANTHROPIC_CLAUDE_V1` | anthropic-claude-v1 | \ No newline at end of file diff --git a/docs/models/openresponsesreasoningstatuscompleted.md b/docs/models/openresponsesreasoningstatuscompleted.md new file mode 100644 index 0000000..f484dd1 --- /dev/null +++ b/docs/models/openresponsesreasoningstatuscompleted.md @@ -0,0 +1,8 @@ +# OpenResponsesReasoningStatusCompleted + + +## Values + +| Name | Value | +| ----------- | ----------- | +| `COMPLETED` | completed | \ No newline at end of file diff --git a/docs/models/openresponsesreasoningstatusincomplete.md b/docs/models/openresponsesreasoningstatusincomplete.md new file mode 100644 index 0000000..c075e66 --- /dev/null +++ b/docs/models/openresponsesreasoningstatusincomplete.md @@ -0,0 +1,8 @@ +# OpenResponsesReasoningStatusIncomplete + + +## Values + +| Name | Value | +| ------------ | ------------ | +| `INCOMPLETE` | incomplete | \ No newline at end of file diff --git a/docs/models/openresponsesreasoningstatusinprogress.md b/docs/models/openresponsesreasoningstatusinprogress.md new file mode 100644 index 0000000..be49f96 --- /dev/null +++ b/docs/models/openresponsesreasoningstatusinprogress.md @@ -0,0 +1,8 @@ +# OpenResponsesReasoningStatusInProgress + + +## Values + +| Name | Value | +| ------------- | ------------- | +| `IN_PROGRESS` | in_progress | \ No newline at end of file diff --git a/docs/models/openresponsesreasoningstatusunion.md b/docs/models/openresponsesreasoningstatusunion.md new file mode 100644 index 0000000..9bb37df --- /dev/null +++ b/docs/models/openresponsesreasoningstatusunion.md @@ -0,0 +1,23 @@ +# OpenResponsesReasoningStatusUnion + + +## Supported Types + +### `models.OpenResponsesReasoningStatusCompleted` + +```python +value: models.OpenResponsesReasoningStatusCompleted = /* values here */ +``` + +### `models.OpenResponsesReasoningStatusIncomplete` + +```python +value: models.OpenResponsesReasoningStatusIncomplete = /* values here */ +``` + +### `models.OpenResponsesReasoningStatusInProgress` + +```python +value: models.OpenResponsesReasoningStatusInProgress = /* values here */ +``` + diff --git a/docs/models/openresponsesreasoningsummarypartaddedevent.md b/docs/models/openresponsesreasoningsummarypartaddedevent.md new file mode 100644 index 0000000..57b4fc6 --- /dev/null +++ b/docs/models/openresponsesreasoningsummarypartaddedevent.md @@ -0,0 +1,15 @@ +# OpenResponsesReasoningSummaryPartAddedEvent + +Event emitted when a reasoning summary part is added + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | +| `type` | [models.OpenResponsesReasoningSummaryPartAddedEventType](../models/openresponsesreasoningsummarypartaddedeventtype.md) | :heavy_check_mark: | N/A | | +| `output_index` | *float* | :heavy_check_mark: | N/A | | +| `item_id` | *str* | :heavy_check_mark: | N/A | | +| `summary_index` | *float* | :heavy_check_mark: | N/A | | +| `part` | [models.ReasoningSummaryText](../models/reasoningsummarytext.md) | :heavy_check_mark: | N/A | {
"type": "summary_text",
"text": "Analyzed the problem using first principles"
} | +| `sequence_number` | *float* | :heavy_check_mark: | N/A | | \ No newline at end of file diff --git a/docs/models/openresponsesreasoningsummarypartaddedeventtype.md b/docs/models/openresponsesreasoningsummarypartaddedeventtype.md new file mode 100644 index 0000000..30a9e35 --- /dev/null +++ b/docs/models/openresponsesreasoningsummarypartaddedeventtype.md @@ -0,0 +1,8 @@ +# OpenResponsesReasoningSummaryPartAddedEventType + + +## Values + +| Name | Value | +| --------------------------------------- | --------------------------------------- | +| `RESPONSE_REASONING_SUMMARY_PART_ADDED` | response.reasoning_summary_part.added | \ No newline at end of file diff --git a/docs/models/openresponsesreasoningsummarytextdeltaevent.md b/docs/models/openresponsesreasoningsummarytextdeltaevent.md new file mode 100644 index 0000000..d42781c --- /dev/null +++ b/docs/models/openresponsesreasoningsummarytextdeltaevent.md @@ -0,0 +1,15 @@ +# OpenResponsesReasoningSummaryTextDeltaEvent + +Event emitted when reasoning summary text delta is streamed + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | +| `type` | [models.OpenResponsesReasoningSummaryTextDeltaEventType](../models/openresponsesreasoningsummarytextdeltaeventtype.md) | :heavy_check_mark: | N/A | +| `item_id` | *str* | :heavy_check_mark: | N/A | +| `output_index` | *float* | :heavy_check_mark: | N/A | +| `summary_index` | *float* | :heavy_check_mark: | N/A | +| `delta` | *str* | :heavy_check_mark: | N/A | +| `sequence_number` | *float* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/openresponsesreasoningsummarytextdeltaeventtype.md b/docs/models/openresponsesreasoningsummarytextdeltaeventtype.md new file mode 100644 index 0000000..1c60ce2 --- /dev/null +++ b/docs/models/openresponsesreasoningsummarytextdeltaeventtype.md @@ -0,0 +1,8 @@ +# OpenResponsesReasoningSummaryTextDeltaEventType + + +## Values + +| Name | Value | +| --------------------------------------- | --------------------------------------- | +| `RESPONSE_REASONING_SUMMARY_TEXT_DELTA` | response.reasoning_summary_text.delta | \ No newline at end of file diff --git a/docs/models/openresponsesreasoningsummarytextdoneevent.md b/docs/models/openresponsesreasoningsummarytextdoneevent.md new file mode 100644 index 0000000..6f38d1f --- /dev/null +++ b/docs/models/openresponsesreasoningsummarytextdoneevent.md @@ -0,0 +1,15 @@ +# OpenResponsesReasoningSummaryTextDoneEvent + +Event emitted when reasoning summary text streaming is complete + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | +| `type` | [models.OpenResponsesReasoningSummaryTextDoneEventType](../models/openresponsesreasoningsummarytextdoneeventtype.md) | :heavy_check_mark: | N/A | +| `item_id` | *str* | :heavy_check_mark: | N/A | +| `output_index` | *float* | :heavy_check_mark: | N/A | +| `summary_index` | *float* | :heavy_check_mark: | N/A | +| `text` | *str* | :heavy_check_mark: | N/A | +| `sequence_number` | *float* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/openresponsesreasoningsummarytextdoneeventtype.md b/docs/models/openresponsesreasoningsummarytextdoneeventtype.md new file mode 100644 index 0000000..c2c83e3 --- /dev/null +++ b/docs/models/openresponsesreasoningsummarytextdoneeventtype.md @@ -0,0 +1,8 @@ +# OpenResponsesReasoningSummaryTextDoneEventType + + +## Values + +| Name | Value | +| -------------------------------------- | -------------------------------------- | +| `RESPONSE_REASONING_SUMMARY_TEXT_DONE` | response.reasoning_summary_text.done | \ No newline at end of file diff --git a/docs/models/openresponsesreasoningtype.md b/docs/models/openresponsesreasoningtype.md new file mode 100644 index 0000000..7536398 --- /dev/null +++ b/docs/models/openresponsesreasoningtype.md @@ -0,0 +1,8 @@ +# OpenResponsesReasoningType + + +## Values + +| Name | Value | +| ----------- | ----------- | +| `REASONING` | reasoning | \ No newline at end of file diff --git a/docs/models/openresponsesrequest.md b/docs/models/openresponsesrequest.md new file mode 100644 index 0000000..2f76d85 --- /dev/null +++ b/docs/models/openresponsesrequest.md @@ -0,0 +1,36 @@ +# OpenResponsesRequest + +Request schema for Responses endpoint + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `input` | [Optional[models.OpenResponsesInput]](../models/openresponsesinput.md) | :heavy_minus_sign: | Input for a response request - can be a string or array of items | [
{
"role": "user",
"content": "What is the weather today?"
}
] | +| `instructions` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | | +| `metadata` | Dict[str, *str*] | :heavy_minus_sign: | Metadata key-value pairs for the request. Keys must be ≤64 characters and cannot contain brackets. Values must be ≤512 characters. Maximum 16 pairs allowed. | {
"user_id": "123",
"session_id": "abc-def-ghi"
} | +| `tools` | List[[models.OpenResponsesRequestToolUnion](../models/openresponsesrequesttoolunion.md)] | :heavy_minus_sign: | N/A | | +| `tool_choice` | [Optional[models.OpenAIResponsesToolChoiceUnion]](../models/openairesponsestoolchoiceunion.md) | :heavy_minus_sign: | N/A | | +| `parallel_tool_calls` | *OptionalNullable[bool]* | :heavy_minus_sign: | N/A | | +| `model` | *Optional[str]* | :heavy_minus_sign: | N/A | | +| `models` | List[*str*] | :heavy_minus_sign: | N/A | | +| `text` | [Optional[models.OpenResponsesResponseText]](../models/openresponsesresponsetext.md) | :heavy_minus_sign: | Text output configuration including format and verbosity | {
"format": {
"type": "text"
},
"verbosity": "medium"
} | +| `reasoning` | [OptionalNullable[models.OpenResponsesReasoningConfig]](../models/openresponsesreasoningconfig.md) | :heavy_minus_sign: | Configuration for reasoning mode in the response | {
"summary": "auto",
"enabled": true
} | +| `max_output_tokens` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | | +| `temperature` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | | +| `top_p` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | | +| `top_k` | *Optional[float]* | :heavy_minus_sign: | N/A | | +| `prompt_cache_key` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | | +| `previous_response_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | | +| `prompt` | [OptionalNullable[models.OpenAIResponsesPrompt]](../models/openairesponsesprompt.md) | :heavy_minus_sign: | N/A | | +| `include` | List[[models.OpenAIResponsesIncludable](../models/openairesponsesincludable.md)] | :heavy_minus_sign: | N/A | | +| `background` | *OptionalNullable[bool]* | :heavy_minus_sign: | N/A | | +| `safety_identifier` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | | +| `store` | *OptionalNullable[bool]* | :heavy_minus_sign: | N/A | | +| `service_tier` | [OptionalNullable[models.ServiceTier]](../models/servicetier.md) | :heavy_minus_sign: | N/A | auto | +| `truncation` | [OptionalNullable[models.Truncation]](../models/truncation.md) | :heavy_minus_sign: | N/A | auto | +| `stream` | *Optional[bool]* | :heavy_minus_sign: | N/A | | +| `provider` | [OptionalNullable[models.Provider]](../models/provider.md) | :heavy_minus_sign: | When multiple model providers are available, optionally indicate your routing preference. | | +| `plugins` | List[[models.Plugin](../models/plugin.md)] | :heavy_minus_sign: | Plugins you want to enable for this request, including their settings. | | +| `user` | *Optional[str]* | :heavy_minus_sign: | A unique identifier representing your end-user, which helps distinguish between different users of your app. This allows your app to identify specific users in case of abuse reports, preventing your entire app from being affected by the actions of individual users. Maximum of 128 characters. | | \ No newline at end of file diff --git a/docs/models/openresponsesrequesttoolfunction.md b/docs/models/openresponsesrequesttoolfunction.md new file mode 100644 index 0000000..76408ac --- /dev/null +++ b/docs/models/openresponsesrequesttoolfunction.md @@ -0,0 +1,14 @@ +# OpenResponsesRequestToolFunction + +Function tool definition + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | +| `type` | [models.OpenResponsesRequestType](../models/openresponsesrequesttype.md) | :heavy_check_mark: | N/A | +| `name` | *str* | :heavy_check_mark: | N/A | +| `description` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | +| `strict` | *OptionalNullable[bool]* | :heavy_minus_sign: | N/A | +| `parameters` | Dict[str, *Nullable[Any]*] | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/openresponsesrequesttoolunion.md b/docs/models/openresponsesrequesttoolunion.md new file mode 100644 index 0000000..63e0d7f --- /dev/null +++ b/docs/models/openresponsesrequesttoolunion.md @@ -0,0 +1,35 @@ +# OpenResponsesRequestToolUnion + + +## Supported Types + +### `models.OpenResponsesRequestToolFunction` + +```python +value: models.OpenResponsesRequestToolFunction = /* values here */ +``` + +### `models.OpenResponsesWebSearchPreviewTool` + +```python +value: models.OpenResponsesWebSearchPreviewTool = /* values here */ +``` + +### `models.OpenResponsesWebSearchPreview20250311Tool` + +```python +value: models.OpenResponsesWebSearchPreview20250311Tool = /* values here */ +``` + +### `models.OpenResponsesWebSearchTool` + +```python +value: models.OpenResponsesWebSearchTool = /* values here */ +``` + +### `models.OpenResponsesWebSearch20250826Tool` + +```python +value: models.OpenResponsesWebSearch20250826Tool = /* values here */ +``` + diff --git a/docs/models/openresponsesrequesttype.md b/docs/models/openresponsesrequesttype.md new file mode 100644 index 0000000..629615d --- /dev/null +++ b/docs/models/openresponsesrequesttype.md @@ -0,0 +1,8 @@ +# OpenResponsesRequestType + + +## Values + +| Name | Value | +| ---------- | ---------- | +| `FUNCTION` | function | \ No newline at end of file diff --git a/docs/models/openresponsesresponsetext.md b/docs/models/openresponsesresponsetext.md new file mode 100644 index 0000000..91355d7 --- /dev/null +++ b/docs/models/openresponsesresponsetext.md @@ -0,0 +1,11 @@ +# OpenResponsesResponseText + +Text output configuration including format and verbosity + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | +| `format_` | [Optional[models.ResponseFormatTextConfig]](../models/responseformattextconfig.md) | :heavy_minus_sign: | Text response format configuration | {
"type": "text"
} | +| `verbosity` | [OptionalNullable[models.OpenResponsesResponseTextVerbosity]](../models/openresponsesresponsetextverbosity.md) | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/docs/models/openresponsesresponsetextverbosity.md b/docs/models/openresponsesresponsetextverbosity.md new file mode 100644 index 0000000..d7622e2 --- /dev/null +++ b/docs/models/openresponsesresponsetextverbosity.md @@ -0,0 +1,10 @@ +# OpenResponsesResponseTextVerbosity + + +## Values + +| Name | Value | +| -------- | -------- | +| `HIGH` | high | +| `LOW` | low | +| `MEDIUM` | medium | \ No newline at end of file diff --git a/docs/models/openresponsesstreamevent.md b/docs/models/openresponsesstreamevent.md new file mode 100644 index 0000000..26b26a5 --- /dev/null +++ b/docs/models/openresponsesstreamevent.md @@ -0,0 +1,169 @@ +# OpenResponsesStreamEvent + +Union of all possible event types emitted during response streaming + + +## Supported Types + +### `models.OpenResponsesStreamEventResponseCreated` + +```python +value: models.OpenResponsesStreamEventResponseCreated = /* values here */ +``` + +### `models.OpenResponsesStreamEventResponseInProgress` + +```python +value: models.OpenResponsesStreamEventResponseInProgress = /* values here */ +``` + +### `models.OpenResponsesStreamEventResponseCompleted` + +```python +value: models.OpenResponsesStreamEventResponseCompleted = /* values here */ +``` + +### `models.OpenResponsesStreamEventResponseIncomplete` + +```python +value: models.OpenResponsesStreamEventResponseIncomplete = /* values here */ +``` + +### `models.OpenResponsesStreamEventResponseFailed` + +```python +value: models.OpenResponsesStreamEventResponseFailed = /* values here */ +``` + +### `models.OpenResponsesErrorEvent` + +```python +value: models.OpenResponsesErrorEvent = /* values here */ +``` + +### `models.OpenResponsesStreamEventResponseOutputItemAdded` + +```python +value: models.OpenResponsesStreamEventResponseOutputItemAdded = /* values here */ +``` + +### `models.OpenResponsesStreamEventResponseOutputItemDone` + +```python +value: models.OpenResponsesStreamEventResponseOutputItemDone = /* values here */ +``` + +### `models.OpenResponsesStreamEventResponseContentPartAdded` + +```python +value: models.OpenResponsesStreamEventResponseContentPartAdded = /* values here */ +``` + +### `models.OpenResponsesStreamEventResponseContentPartDone` + +```python +value: models.OpenResponsesStreamEventResponseContentPartDone = /* values here */ +``` + +### `models.OpenResponsesStreamEventResponseOutputTextDelta` + +```python +value: models.OpenResponsesStreamEventResponseOutputTextDelta = /* values here */ +``` + +### `models.OpenResponsesStreamEventResponseOutputTextDone` + +```python +value: models.OpenResponsesStreamEventResponseOutputTextDone = /* values here */ +``` + +### `models.OpenResponsesStreamEventResponseRefusalDelta` + +```python +value: models.OpenResponsesStreamEventResponseRefusalDelta = /* values here */ +``` + +### `models.OpenResponsesStreamEventResponseRefusalDone` + +```python +value: models.OpenResponsesStreamEventResponseRefusalDone = /* values here */ +``` + +### `models.OpenResponsesStreamEventResponseOutputTextAnnotationAdded` + +```python +value: models.OpenResponsesStreamEventResponseOutputTextAnnotationAdded = /* values here */ +``` + +### `models.OpenResponsesStreamEventResponseFunctionCallArgumentsDelta` + +```python +value: models.OpenResponsesStreamEventResponseFunctionCallArgumentsDelta = /* values here */ +``` + +### `models.OpenResponsesStreamEventResponseFunctionCallArgumentsDone` + +```python +value: models.OpenResponsesStreamEventResponseFunctionCallArgumentsDone = /* values here */ +``` + +### `models.OpenResponsesReasoningDeltaEvent` + +```python +value: models.OpenResponsesReasoningDeltaEvent = /* values here */ +``` + +### `models.OpenResponsesReasoningDoneEvent` + +```python +value: models.OpenResponsesReasoningDoneEvent = /* values here */ +``` + +### `models.OpenResponsesReasoningSummaryPartAddedEvent` + +```python +value: models.OpenResponsesReasoningSummaryPartAddedEvent = /* values here */ +``` + +### `models.OpenResponsesStreamEventResponseReasoningSummaryPartDone` + +```python +value: models.OpenResponsesStreamEventResponseReasoningSummaryPartDone = /* values here */ +``` + +### `models.OpenResponsesReasoningSummaryTextDeltaEvent` + +```python +value: models.OpenResponsesReasoningSummaryTextDeltaEvent = /* values here */ +``` + +### `models.OpenResponsesReasoningSummaryTextDoneEvent` + +```python +value: models.OpenResponsesReasoningSummaryTextDoneEvent = /* values here */ +``` + +### `models.OpenResponsesImageGenCallInProgress` + +```python +value: models.OpenResponsesImageGenCallInProgress = /* values here */ +``` + +### `models.OpenResponsesImageGenCallGenerating` + +```python +value: models.OpenResponsesImageGenCallGenerating = /* values here */ +``` + +### `models.OpenResponsesImageGenCallPartialImage` + +```python +value: models.OpenResponsesImageGenCallPartialImage = /* values here */ +``` + +### `models.OpenResponsesImageGenCallCompleted` + +```python +value: models.OpenResponsesImageGenCallCompleted = /* values here */ +``` + diff --git a/docs/models/openresponsesstreameventresponsecompleted.md b/docs/models/openresponsesstreameventresponsecompleted.md new file mode 100644 index 0000000..adf262d --- /dev/null +++ b/docs/models/openresponsesstreameventresponsecompleted.md @@ -0,0 +1,12 @@ +# OpenResponsesStreamEventResponseCompleted + +Event emitted when a response has completed successfully + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `type` | [models.TypeResponseCompleted](../models/typeresponsecompleted.md) | :heavy_check_mark: | N/A | | +| `response` | [models.OpenResponsesNonStreamingResponse](../models/openresponsesnonstreamingresponse.md) | :heavy_check_mark: | Complete non-streaming response from the Responses API | {
"id": "resp-abc123",
"object": "response",
"created_at": 1704067200,
"model": "gpt-4",
"status": "completed",
"output": [
{
"type": "message",
"id": "msg-abc123",
"status": "completed",
"role": "assistant",
"content": [
{
"type": "output_text",
"text": "Hello! How can I help you today?",
"annotations": []
}
]
}
],
"usage": {
"input_tokens": 10,
"output_tokens": 25,
"total_tokens": 35,
"input_tokens_details": {
"cached_tokens": 0
},
"output_tokens_details": {
"reasoning_tokens": 0
}
},
"tools": [],
"tool_choice": "auto",
"parallel_tool_calls": true,
"error": null,
"incomplete_details": null,
"temperature": null,
"top_p": null,
"max_output_tokens": null,
"metadata": null,
"instructions": null
} | +| `sequence_number` | *float* | :heavy_check_mark: | N/A | | \ No newline at end of file diff --git a/docs/models/openresponsesstreameventresponsecontentpartadded.md b/docs/models/openresponsesstreameventresponsecontentpartadded.md new file mode 100644 index 0000000..adf5300 --- /dev/null +++ b/docs/models/openresponsesstreameventresponsecontentpartadded.md @@ -0,0 +1,15 @@ +# OpenResponsesStreamEventResponseContentPartAdded + +Event emitted when a new content part is added to an output item + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | +| `type` | [models.TypeResponseContentPartAdded](../models/typeresponsecontentpartadded.md) | :heavy_check_mark: | N/A | +| `output_index` | *float* | :heavy_check_mark: | N/A | +| `item_id` | *str* | :heavy_check_mark: | N/A | +| `content_index` | *float* | :heavy_check_mark: | N/A | +| `part` | [models.Part1](../models/part1.md) | :heavy_check_mark: | N/A | +| `sequence_number` | *float* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/openresponsesstreameventresponsecontentpartdone.md b/docs/models/openresponsesstreameventresponsecontentpartdone.md new file mode 100644 index 0000000..f137df7 --- /dev/null +++ b/docs/models/openresponsesstreameventresponsecontentpartdone.md @@ -0,0 +1,15 @@ +# OpenResponsesStreamEventResponseContentPartDone + +Event emitted when a content part is complete + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | +| `type` | [models.TypeResponseContentPartDone](../models/typeresponsecontentpartdone.md) | :heavy_check_mark: | N/A | +| `output_index` | *float* | :heavy_check_mark: | N/A | +| `item_id` | *str* | :heavy_check_mark: | N/A | +| `content_index` | *float* | :heavy_check_mark: | N/A | +| `part` | [models.Part2](../models/part2.md) | :heavy_check_mark: | N/A | +| `sequence_number` | *float* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/openresponsesstreameventresponsecreated.md b/docs/models/openresponsesstreameventresponsecreated.md new file mode 100644 index 0000000..c8d1983 --- /dev/null +++ b/docs/models/openresponsesstreameventresponsecreated.md @@ -0,0 +1,12 @@ +# OpenResponsesStreamEventResponseCreated + +Event emitted when a response is created + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `type` | [models.TypeResponseCreated](../models/typeresponsecreated.md) | :heavy_check_mark: | N/A | | +| `response` | [models.OpenResponsesNonStreamingResponse](../models/openresponsesnonstreamingresponse.md) | :heavy_check_mark: | Complete non-streaming response from the Responses API | {
"id": "resp-abc123",
"object": "response",
"created_at": 1704067200,
"model": "gpt-4",
"status": "completed",
"output": [
{
"type": "message",
"id": "msg-abc123",
"status": "completed",
"role": "assistant",
"content": [
{
"type": "output_text",
"text": "Hello! How can I help you today?",
"annotations": []
}
]
}
],
"usage": {
"input_tokens": 10,
"output_tokens": 25,
"total_tokens": 35,
"input_tokens_details": {
"cached_tokens": 0
},
"output_tokens_details": {
"reasoning_tokens": 0
}
},
"tools": [],
"tool_choice": "auto",
"parallel_tool_calls": true,
"error": null,
"incomplete_details": null,
"temperature": null,
"top_p": null,
"max_output_tokens": null,
"metadata": null,
"instructions": null
} | +| `sequence_number` | *float* | :heavy_check_mark: | N/A | | \ No newline at end of file diff --git a/docs/models/openresponsesstreameventresponsefailed.md b/docs/models/openresponsesstreameventresponsefailed.md new file mode 100644 index 0000000..d9ffe02 --- /dev/null +++ b/docs/models/openresponsesstreameventresponsefailed.md @@ -0,0 +1,12 @@ +# OpenResponsesStreamEventResponseFailed + +Event emitted when a response has failed + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `type` | [models.TypeResponseFailed](../models/typeresponsefailed.md) | :heavy_check_mark: | N/A | | +| `response` | [models.OpenResponsesNonStreamingResponse](../models/openresponsesnonstreamingresponse.md) | :heavy_check_mark: | Complete non-streaming response from the Responses API | {
"id": "resp-abc123",
"object": "response",
"created_at": 1704067200,
"model": "gpt-4",
"status": "completed",
"output": [
{
"type": "message",
"id": "msg-abc123",
"status": "completed",
"role": "assistant",
"content": [
{
"type": "output_text",
"text": "Hello! How can I help you today?",
"annotations": []
}
]
}
],
"usage": {
"input_tokens": 10,
"output_tokens": 25,
"total_tokens": 35,
"input_tokens_details": {
"cached_tokens": 0
},
"output_tokens_details": {
"reasoning_tokens": 0
}
},
"tools": [],
"tool_choice": "auto",
"parallel_tool_calls": true,
"error": null,
"incomplete_details": null,
"temperature": null,
"top_p": null,
"max_output_tokens": null,
"metadata": null,
"instructions": null
} | +| `sequence_number` | *float* | :heavy_check_mark: | N/A | | \ No newline at end of file diff --git a/docs/models/openresponsesstreameventresponsefunctioncallargumentsdelta.md b/docs/models/openresponsesstreameventresponsefunctioncallargumentsdelta.md new file mode 100644 index 0000000..ac24207 --- /dev/null +++ b/docs/models/openresponsesstreameventresponsefunctioncallargumentsdelta.md @@ -0,0 +1,14 @@ +# OpenResponsesStreamEventResponseFunctionCallArgumentsDelta + +Event emitted when function call arguments are being streamed + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | +| `type` | [models.TypeResponseFunctionCallArgumentsDelta](../models/typeresponsefunctioncallargumentsdelta.md) | :heavy_check_mark: | N/A | +| `item_id` | *str* | :heavy_check_mark: | N/A | +| `output_index` | *float* | :heavy_check_mark: | N/A | +| `delta` | *str* | :heavy_check_mark: | N/A | +| `sequence_number` | *float* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/openresponsesstreameventresponsefunctioncallargumentsdone.md b/docs/models/openresponsesstreameventresponsefunctioncallargumentsdone.md new file mode 100644 index 0000000..bbdd489 --- /dev/null +++ b/docs/models/openresponsesstreameventresponsefunctioncallargumentsdone.md @@ -0,0 +1,15 @@ +# OpenResponsesStreamEventResponseFunctionCallArgumentsDone + +Event emitted when function call arguments streaming is complete + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | +| `type` | [models.TypeResponseFunctionCallArgumentsDone](../models/typeresponsefunctioncallargumentsdone.md) | :heavy_check_mark: | N/A | +| `item_id` | *str* | :heavy_check_mark: | N/A | +| `output_index` | *float* | :heavy_check_mark: | N/A | +| `name` | *str* | :heavy_check_mark: | N/A | +| `arguments` | *str* | :heavy_check_mark: | N/A | +| `sequence_number` | *float* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/openresponsesstreameventresponseincomplete.md b/docs/models/openresponsesstreameventresponseincomplete.md new file mode 100644 index 0000000..b90b2bc --- /dev/null +++ b/docs/models/openresponsesstreameventresponseincomplete.md @@ -0,0 +1,12 @@ +# OpenResponsesStreamEventResponseIncomplete + +Event emitted when a response is incomplete + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `type` | [models.TypeResponseIncomplete](../models/typeresponseincomplete.md) | :heavy_check_mark: | N/A | | +| `response` | [models.OpenResponsesNonStreamingResponse](../models/openresponsesnonstreamingresponse.md) | :heavy_check_mark: | Complete non-streaming response from the Responses API | {
"id": "resp-abc123",
"object": "response",
"created_at": 1704067200,
"model": "gpt-4",
"status": "completed",
"output": [
{
"type": "message",
"id": "msg-abc123",
"status": "completed",
"role": "assistant",
"content": [
{
"type": "output_text",
"text": "Hello! How can I help you today?",
"annotations": []
}
]
}
],
"usage": {
"input_tokens": 10,
"output_tokens": 25,
"total_tokens": 35,
"input_tokens_details": {
"cached_tokens": 0
},
"output_tokens_details": {
"reasoning_tokens": 0
}
},
"tools": [],
"tool_choice": "auto",
"parallel_tool_calls": true,
"error": null,
"incomplete_details": null,
"temperature": null,
"top_p": null,
"max_output_tokens": null,
"metadata": null,
"instructions": null
} | +| `sequence_number` | *float* | :heavy_check_mark: | N/A | | \ No newline at end of file diff --git a/docs/models/openresponsesstreameventresponseinprogress.md b/docs/models/openresponsesstreameventresponseinprogress.md new file mode 100644 index 0000000..ecc2a76 --- /dev/null +++ b/docs/models/openresponsesstreameventresponseinprogress.md @@ -0,0 +1,12 @@ +# OpenResponsesStreamEventResponseInProgress + +Event emitted when a response is in progress + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `type` | [models.TypeResponseInProgress](../models/typeresponseinprogress.md) | :heavy_check_mark: | N/A | | +| `response` | [models.OpenResponsesNonStreamingResponse](../models/openresponsesnonstreamingresponse.md) | :heavy_check_mark: | Complete non-streaming response from the Responses API | {
"id": "resp-abc123",
"object": "response",
"created_at": 1704067200,
"model": "gpt-4",
"status": "completed",
"output": [
{
"type": "message",
"id": "msg-abc123",
"status": "completed",
"role": "assistant",
"content": [
{
"type": "output_text",
"text": "Hello! How can I help you today?",
"annotations": []
}
]
}
],
"usage": {
"input_tokens": 10,
"output_tokens": 25,
"total_tokens": 35,
"input_tokens_details": {
"cached_tokens": 0
},
"output_tokens_details": {
"reasoning_tokens": 0
}
},
"tools": [],
"tool_choice": "auto",
"parallel_tool_calls": true,
"error": null,
"incomplete_details": null,
"temperature": null,
"top_p": null,
"max_output_tokens": null,
"metadata": null,
"instructions": null
} | +| `sequence_number` | *float* | :heavy_check_mark: | N/A | | \ No newline at end of file diff --git a/docs/models/openresponsesstreameventresponseoutputitemadded.md b/docs/models/openresponsesstreameventresponseoutputitemadded.md new file mode 100644 index 0000000..3b1c7df --- /dev/null +++ b/docs/models/openresponsesstreameventresponseoutputitemadded.md @@ -0,0 +1,13 @@ +# OpenResponsesStreamEventResponseOutputItemAdded + +Event emitted when a new output item is added to the response + + +## Fields + +| Field | Type | Required | Description | Example | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `type` | [models.TypeResponseOutputItemAdded](../models/typeresponseoutputitemadded.md) | :heavy_check_mark: | N/A | | +| `output_index` | *float* | :heavy_check_mark: | N/A | | +| `item` | [models.ResponsesOutputItem](../models/responsesoutputitem.md) | :heavy_check_mark: | An output item from the response | {
"id": "msg-abc123",
"role": "assistant",
"type": "message",
"status": "completed",
"content": [
{
"type": "output_text",
"text": "Hello! How can I help you today?"
}
]
} | +| `sequence_number` | *float* | :heavy_check_mark: | N/A | | \ No newline at end of file diff --git a/docs/models/openresponsesstreameventresponseoutputitemdone.md b/docs/models/openresponsesstreameventresponseoutputitemdone.md new file mode 100644 index 0000000..e878780 --- /dev/null +++ b/docs/models/openresponsesstreameventresponseoutputitemdone.md @@ -0,0 +1,13 @@ +# OpenResponsesStreamEventResponseOutputItemDone + +Event emitted when an output item is complete + + +## Fields + +| Field | Type | Required | Description | Example | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `type` | [models.TypeResponseOutputItemDone](../models/typeresponseoutputitemdone.md) | :heavy_check_mark: | N/A | | +| `output_index` | *float* | :heavy_check_mark: | N/A | | +| `item` | [models.ResponsesOutputItem](../models/responsesoutputitem.md) | :heavy_check_mark: | An output item from the response | {
"id": "msg-abc123",
"role": "assistant",
"type": "message",
"status": "completed",
"content": [
{
"type": "output_text",
"text": "Hello! How can I help you today?"
}
]
} | +| `sequence_number` | *float* | :heavy_check_mark: | N/A | | \ No newline at end of file diff --git a/docs/models/openresponsesstreameventresponseoutputtextannotationadded.md b/docs/models/openresponsesstreameventresponseoutputtextannotationadded.md new file mode 100644 index 0000000..8c6c0b4 --- /dev/null +++ b/docs/models/openresponsesstreameventresponseoutputtextannotationadded.md @@ -0,0 +1,16 @@ +# OpenResponsesStreamEventResponseOutputTextAnnotationAdded + +Event emitted when a text annotation is added to output + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | +| `type` | [models.TypeResponseOutputTextAnnotationAdded](../models/typeresponseoutputtextannotationadded.md) | :heavy_check_mark: | N/A | +| `output_index` | *float* | :heavy_check_mark: | N/A | +| `item_id` | *str* | :heavy_check_mark: | N/A | +| `content_index` | *float* | :heavy_check_mark: | N/A | +| `sequence_number` | *float* | :heavy_check_mark: | N/A | +| `annotation_index` | *float* | :heavy_check_mark: | N/A | +| `annotation` | [models.OpenAIResponsesAnnotation](../models/openairesponsesannotation.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/openresponsesstreameventresponseoutputtextdelta.md b/docs/models/openresponsesstreameventresponseoutputtextdelta.md new file mode 100644 index 0000000..8da1789 --- /dev/null +++ b/docs/models/openresponsesstreameventresponseoutputtextdelta.md @@ -0,0 +1,16 @@ +# OpenResponsesStreamEventResponseOutputTextDelta + +Event emitted when a text delta is streamed + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | +| `type` | [models.TypeResponseOutputTextDelta](../models/typeresponseoutputtextdelta.md) | :heavy_check_mark: | N/A | +| `logprobs` | List[[models.OpenResponsesLogProbs](../models/openresponseslogprobs.md)] | :heavy_check_mark: | N/A | +| `output_index` | *float* | :heavy_check_mark: | N/A | +| `item_id` | *str* | :heavy_check_mark: | N/A | +| `content_index` | *float* | :heavy_check_mark: | N/A | +| `delta` | *str* | :heavy_check_mark: | N/A | +| `sequence_number` | *float* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/openresponsesstreameventresponseoutputtextdone.md b/docs/models/openresponsesstreameventresponseoutputtextdone.md new file mode 100644 index 0000000..72783ff --- /dev/null +++ b/docs/models/openresponsesstreameventresponseoutputtextdone.md @@ -0,0 +1,16 @@ +# OpenResponsesStreamEventResponseOutputTextDone + +Event emitted when text streaming is complete + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | +| `type` | [models.TypeResponseOutputTextDone](../models/typeresponseoutputtextdone.md) | :heavy_check_mark: | N/A | +| `output_index` | *float* | :heavy_check_mark: | N/A | +| `item_id` | *str* | :heavy_check_mark: | N/A | +| `content_index` | *float* | :heavy_check_mark: | N/A | +| `text` | *str* | :heavy_check_mark: | N/A | +| `sequence_number` | *float* | :heavy_check_mark: | N/A | +| `logprobs` | List[[models.OpenResponsesLogProbs](../models/openresponseslogprobs.md)] | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/openresponsesstreameventresponsereasoningsummarypartdone.md b/docs/models/openresponsesstreameventresponsereasoningsummarypartdone.md new file mode 100644 index 0000000..8cc0856 --- /dev/null +++ b/docs/models/openresponsesstreameventresponsereasoningsummarypartdone.md @@ -0,0 +1,15 @@ +# OpenResponsesStreamEventResponseReasoningSummaryPartDone + +Event emitted when a reasoning summary part is complete + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | +| `type` | [models.TypeResponseReasoningSummaryPartDone](../models/typeresponsereasoningsummarypartdone.md) | :heavy_check_mark: | N/A | | +| `output_index` | *float* | :heavy_check_mark: | N/A | | +| `item_id` | *str* | :heavy_check_mark: | N/A | | +| `summary_index` | *float* | :heavy_check_mark: | N/A | | +| `part` | [models.ReasoningSummaryText](../models/reasoningsummarytext.md) | :heavy_check_mark: | N/A | {
"type": "summary_text",
"text": "Analyzed the problem using first principles"
} | +| `sequence_number` | *float* | :heavy_check_mark: | N/A | | \ No newline at end of file diff --git a/docs/models/openresponsesstreameventresponserefusaldelta.md b/docs/models/openresponsesstreameventresponserefusaldelta.md new file mode 100644 index 0000000..1162cc2 --- /dev/null +++ b/docs/models/openresponsesstreameventresponserefusaldelta.md @@ -0,0 +1,15 @@ +# OpenResponsesStreamEventResponseRefusalDelta + +Event emitted when a refusal delta is streamed + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | +| `type` | [models.TypeResponseRefusalDelta](../models/typeresponserefusaldelta.md) | :heavy_check_mark: | N/A | +| `output_index` | *float* | :heavy_check_mark: | N/A | +| `item_id` | *str* | :heavy_check_mark: | N/A | +| `content_index` | *float* | :heavy_check_mark: | N/A | +| `delta` | *str* | :heavy_check_mark: | N/A | +| `sequence_number` | *float* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/openresponsesstreameventresponserefusaldone.md b/docs/models/openresponsesstreameventresponserefusaldone.md new file mode 100644 index 0000000..adef6db --- /dev/null +++ b/docs/models/openresponsesstreameventresponserefusaldone.md @@ -0,0 +1,15 @@ +# OpenResponsesStreamEventResponseRefusalDone + +Event emitted when refusal streaming is complete + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | +| `type` | [models.TypeResponseRefusalDone](../models/typeresponserefusaldone.md) | :heavy_check_mark: | N/A | +| `output_index` | *float* | :heavy_check_mark: | N/A | +| `item_id` | *str* | :heavy_check_mark: | N/A | +| `content_index` | *float* | :heavy_check_mark: | N/A | +| `refusal` | *str* | :heavy_check_mark: | N/A | +| `sequence_number` | *float* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/openresponsestoplogprobs.md b/docs/models/openresponsestoplogprobs.md new file mode 100644 index 0000000..aa7d39b --- /dev/null +++ b/docs/models/openresponsestoplogprobs.md @@ -0,0 +1,11 @@ +# OpenResponsesTopLogprobs + +Alternative token with its log probability + + +## Fields + +| Field | Type | Required | Description | +| ------------------ | ------------------ | ------------------ | ------------------ | +| `token` | *Optional[str]* | :heavy_minus_sign: | N/A | +| `logprob` | *Optional[float]* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/openresponsesusage.md b/docs/models/openresponsesusage.md new file mode 100644 index 0000000..922b01e --- /dev/null +++ b/docs/models/openresponsesusage.md @@ -0,0 +1,17 @@ +# OpenResponsesUsage + +Token usage information for the response + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | +| `input_tokens` | *float* | :heavy_check_mark: | N/A | +| `input_tokens_details` | [models.InputTokensDetails](../models/inputtokensdetails.md) | :heavy_check_mark: | N/A | +| `output_tokens` | *float* | :heavy_check_mark: | N/A | +| `output_tokens_details` | [models.OutputTokensDetails](../models/outputtokensdetails.md) | :heavy_check_mark: | N/A | +| `total_tokens` | *float* | :heavy_check_mark: | N/A | +| `cost` | *OptionalNullable[float]* | :heavy_minus_sign: | Cost of the completion | +| `is_byok` | *Optional[bool]* | :heavy_minus_sign: | Whether a request was made using a Bring Your Own Key configuration | +| `cost_details` | [Optional[models.CostDetails]](../models/costdetails.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/openresponseswebsearch20250826tool.md b/docs/models/openresponseswebsearch20250826tool.md new file mode 100644 index 0000000..0539e8d --- /dev/null +++ b/docs/models/openresponseswebsearch20250826tool.md @@ -0,0 +1,13 @@ +# OpenResponsesWebSearch20250826Tool + +Web search tool configuration (2025-08-26 version) + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | +| `type` | [models.OpenResponsesWebSearch20250826ToolType](../models/openresponseswebsearch20250826tooltype.md) | :heavy_check_mark: | N/A | | +| `filters` | [OptionalNullable[models.OpenResponsesWebSearch20250826ToolFilters]](../models/openresponseswebsearch20250826toolfilters.md) | :heavy_minus_sign: | N/A | | +| `search_context_size` | [Optional[models.ResponsesSearchContextSize]](../models/responsessearchcontextsize.md) | :heavy_minus_sign: | Size of the search context for web search tools | medium | +| `user_location` | [OptionalNullable[models.ResponsesWebSearchUserLocation]](../models/responseswebsearchuserlocation.md) | :heavy_minus_sign: | User location information for web search | {
"type": "approximate",
"city": "San Francisco",
"country": "USA",
"region": "California",
"timezone": "America/Los_Angeles"
} | \ No newline at end of file diff --git a/docs/models/openresponseswebsearch20250826toolfilters.md b/docs/models/openresponseswebsearch20250826toolfilters.md new file mode 100644 index 0000000..58c6a3b --- /dev/null +++ b/docs/models/openresponseswebsearch20250826toolfilters.md @@ -0,0 +1,8 @@ +# OpenResponsesWebSearch20250826ToolFilters + + +## Fields + +| Field | Type | Required | Description | +| ------------------ | ------------------ | ------------------ | ------------------ | +| `allowed_domains` | List[*str*] | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/openresponseswebsearch20250826tooltype.md b/docs/models/openresponseswebsearch20250826tooltype.md new file mode 100644 index 0000000..e454c71 --- /dev/null +++ b/docs/models/openresponseswebsearch20250826tooltype.md @@ -0,0 +1,8 @@ +# OpenResponsesWebSearch20250826ToolType + + +## Values + +| Name | Value | +| ----------------------- | ----------------------- | +| `WEB_SEARCH_2025_08_26` | web_search_2025_08_26 | \ No newline at end of file diff --git a/docs/models/openresponseswebsearchpreview20250311tool.md b/docs/models/openresponseswebsearchpreview20250311tool.md new file mode 100644 index 0000000..5a53cdd --- /dev/null +++ b/docs/models/openresponseswebsearchpreview20250311tool.md @@ -0,0 +1,12 @@ +# OpenResponsesWebSearchPreview20250311Tool + +Web search preview tool configuration (2025-03-11 version) + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | +| `type` | [models.OpenResponsesWebSearchPreview20250311ToolType](../models/openresponseswebsearchpreview20250311tooltype.md) | :heavy_check_mark: | N/A | | +| `search_context_size` | [Optional[models.ResponsesSearchContextSize]](../models/responsessearchcontextsize.md) | :heavy_minus_sign: | Size of the search context for web search tools | medium | +| `user_location` | [OptionalNullable[models.WebSearchPreviewToolUserLocation]](../models/websearchpreviewtooluserlocation.md) | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/docs/models/openresponseswebsearchpreview20250311tooltype.md b/docs/models/openresponseswebsearchpreview20250311tooltype.md new file mode 100644 index 0000000..25fec31 --- /dev/null +++ b/docs/models/openresponseswebsearchpreview20250311tooltype.md @@ -0,0 +1,8 @@ +# OpenResponsesWebSearchPreview20250311ToolType + + +## Values + +| Name | Value | +| ------------------------------- | ------------------------------- | +| `WEB_SEARCH_PREVIEW_2025_03_11` | web_search_preview_2025_03_11 | \ No newline at end of file diff --git a/docs/models/openresponseswebsearchpreviewtool.md b/docs/models/openresponseswebsearchpreviewtool.md new file mode 100644 index 0000000..bdeff67 --- /dev/null +++ b/docs/models/openresponseswebsearchpreviewtool.md @@ -0,0 +1,12 @@ +# OpenResponsesWebSearchPreviewTool + +Web search preview tool configuration + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | +| `type` | [models.OpenResponsesWebSearchPreviewToolType](../models/openresponseswebsearchpreviewtooltype.md) | :heavy_check_mark: | N/A | | +| `search_context_size` | [Optional[models.ResponsesSearchContextSize]](../models/responsessearchcontextsize.md) | :heavy_minus_sign: | Size of the search context for web search tools | medium | +| `user_location` | [OptionalNullable[models.WebSearchPreviewToolUserLocation]](../models/websearchpreviewtooluserlocation.md) | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/docs/models/openresponseswebsearchpreviewtooltype.md b/docs/models/openresponseswebsearchpreviewtooltype.md new file mode 100644 index 0000000..e4df867 --- /dev/null +++ b/docs/models/openresponseswebsearchpreviewtooltype.md @@ -0,0 +1,8 @@ +# OpenResponsesWebSearchPreviewToolType + + +## Values + +| Name | Value | +| -------------------- | -------------------- | +| `WEB_SEARCH_PREVIEW` | web_search_preview | \ No newline at end of file diff --git a/docs/models/openresponseswebsearchtool.md b/docs/models/openresponseswebsearchtool.md new file mode 100644 index 0000000..1854f49 --- /dev/null +++ b/docs/models/openresponseswebsearchtool.md @@ -0,0 +1,13 @@ +# OpenResponsesWebSearchTool + +Web search tool configuration + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | +| `type` | [models.OpenResponsesWebSearchToolType](../models/openresponseswebsearchtooltype.md) | :heavy_check_mark: | N/A | | +| `filters` | [OptionalNullable[models.OpenResponsesWebSearchToolFilters]](../models/openresponseswebsearchtoolfilters.md) | :heavy_minus_sign: | N/A | | +| `search_context_size` | [Optional[models.ResponsesSearchContextSize]](../models/responsessearchcontextsize.md) | :heavy_minus_sign: | Size of the search context for web search tools | medium | +| `user_location` | [OptionalNullable[models.ResponsesWebSearchUserLocation]](../models/responseswebsearchuserlocation.md) | :heavy_minus_sign: | User location information for web search | {
"type": "approximate",
"city": "San Francisco",
"country": "USA",
"region": "California",
"timezone": "America/Los_Angeles"
} | \ No newline at end of file diff --git a/docs/models/openresponseswebsearchtoolfilters.md b/docs/models/openresponseswebsearchtoolfilters.md new file mode 100644 index 0000000..2528409 --- /dev/null +++ b/docs/models/openresponseswebsearchtoolfilters.md @@ -0,0 +1,8 @@ +# OpenResponsesWebSearchToolFilters + + +## Fields + +| Field | Type | Required | Description | +| ------------------ | ------------------ | ------------------ | ------------------ | +| `allowed_domains` | List[*str*] | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/openresponseswebsearchtooltype.md b/docs/models/openresponseswebsearchtooltype.md new file mode 100644 index 0000000..d107d41 --- /dev/null +++ b/docs/models/openresponseswebsearchtooltype.md @@ -0,0 +1,8 @@ +# OpenResponsesWebSearchToolType + + +## Values + +| Name | Value | +| ------------ | ------------ | +| `WEB_SEARCH` | web_search | \ No newline at end of file diff --git a/docs/models/order.md b/docs/models/order.md new file mode 100644 index 0000000..cdd0388 --- /dev/null +++ b/docs/models/order.md @@ -0,0 +1,17 @@ +# Order + + +## Supported Types + +### `models.ProviderName` + +```python +value: models.ProviderName = /* values here */ +``` + +### `str` + +```python +value: str = /* values here */ +``` + diff --git a/docs/models/outputitemimagegenerationcall.md b/docs/models/outputitemimagegenerationcall.md new file mode 100644 index 0000000..7834984 --- /dev/null +++ b/docs/models/outputitemimagegenerationcall.md @@ -0,0 +1,11 @@ +# OutputItemImageGenerationCall + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | +| `type` | [models.OutputItemImageGenerationCallType](../models/outputitemimagegenerationcalltype.md) | :heavy_check_mark: | N/A | | +| `id` | *str* | :heavy_check_mark: | N/A | | +| `result` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | | +| `status` | [models.ImageGenerationStatus](../models/imagegenerationstatus.md) | :heavy_check_mark: | N/A | completed | \ No newline at end of file diff --git a/docs/models/outputitemimagegenerationcalltype.md b/docs/models/outputitemimagegenerationcalltype.md new file mode 100644 index 0000000..d9e663f --- /dev/null +++ b/docs/models/outputitemimagegenerationcalltype.md @@ -0,0 +1,8 @@ +# OutputItemImageGenerationCallType + + +## Values + +| Name | Value | +| ----------------------- | ----------------------- | +| `IMAGE_GENERATION_CALL` | image_generation_call | \ No newline at end of file diff --git a/docs/models/outputmessage.md b/docs/models/outputmessage.md new file mode 100644 index 0000000..7165f2c --- /dev/null +++ b/docs/models/outputmessage.md @@ -0,0 +1,12 @@ +# OutputMessage + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | +| `id` | *str* | :heavy_check_mark: | N/A | +| `role` | [models.OutputMessageRole](../models/outputmessagerole.md) | :heavy_check_mark: | N/A | +| `type` | [models.OutputMessageType](../models/outputmessagetype.md) | :heavy_check_mark: | N/A | +| `status` | [Optional[models.OutputMessageStatusUnion]](../models/outputmessagestatusunion.md) | :heavy_minus_sign: | N/A | +| `content` | List[[models.OutputMessageContent](../models/outputmessagecontent.md)] | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/outputmessagecontent.md b/docs/models/outputmessagecontent.md new file mode 100644 index 0000000..8e21e48 --- /dev/null +++ b/docs/models/outputmessagecontent.md @@ -0,0 +1,17 @@ +# OutputMessageContent + + +## Supported Types + +### `models.ResponseOutputText` + +```python +value: models.ResponseOutputText = /* values here */ +``` + +### `models.OpenAIResponsesRefusalContent` + +```python +value: models.OpenAIResponsesRefusalContent = /* values here */ +``` + diff --git a/docs/models/outputmessagerole.md b/docs/models/outputmessagerole.md new file mode 100644 index 0000000..21b1616 --- /dev/null +++ b/docs/models/outputmessagerole.md @@ -0,0 +1,8 @@ +# OutputMessageRole + + +## Values + +| Name | Value | +| ----------- | ----------- | +| `ASSISTANT` | assistant | \ No newline at end of file diff --git a/docs/models/outputmessagestatuscompleted.md b/docs/models/outputmessagestatuscompleted.md new file mode 100644 index 0000000..2b0254b --- /dev/null +++ b/docs/models/outputmessagestatuscompleted.md @@ -0,0 +1,8 @@ +# OutputMessageStatusCompleted + + +## Values + +| Name | Value | +| ----------- | ----------- | +| `COMPLETED` | completed | \ No newline at end of file diff --git a/docs/models/outputmessagestatusincomplete.md b/docs/models/outputmessagestatusincomplete.md new file mode 100644 index 0000000..3146b10 --- /dev/null +++ b/docs/models/outputmessagestatusincomplete.md @@ -0,0 +1,8 @@ +# OutputMessageStatusIncomplete + + +## Values + +| Name | Value | +| ------------ | ------------ | +| `INCOMPLETE` | incomplete | \ No newline at end of file diff --git a/docs/models/outputmessagestatusinprogress.md b/docs/models/outputmessagestatusinprogress.md new file mode 100644 index 0000000..eb31df4 --- /dev/null +++ b/docs/models/outputmessagestatusinprogress.md @@ -0,0 +1,8 @@ +# OutputMessageStatusInProgress + + +## Values + +| Name | Value | +| ------------- | ------------- | +| `IN_PROGRESS` | in_progress | \ No newline at end of file diff --git a/docs/models/outputmessagestatusunion.md b/docs/models/outputmessagestatusunion.md new file mode 100644 index 0000000..791e637 --- /dev/null +++ b/docs/models/outputmessagestatusunion.md @@ -0,0 +1,23 @@ +# OutputMessageStatusUnion + + +## Supported Types + +### `models.OutputMessageStatusCompleted` + +```python +value: models.OutputMessageStatusCompleted = /* values here */ +``` + +### `models.OutputMessageStatusIncomplete` + +```python +value: models.OutputMessageStatusIncomplete = /* values here */ +``` + +### `models.OutputMessageStatusInProgress` + +```python +value: models.OutputMessageStatusInProgress = /* values here */ +``` + diff --git a/docs/models/outputmessagetype.md b/docs/models/outputmessagetype.md new file mode 100644 index 0000000..acbedfe --- /dev/null +++ b/docs/models/outputmessagetype.md @@ -0,0 +1,8 @@ +# OutputMessageType + + +## Values + +| Name | Value | +| --------- | --------- | +| `MESSAGE` | message | \ No newline at end of file diff --git a/docs/models/outputmodality.md b/docs/models/outputmodality.md new file mode 100644 index 0000000..97c0497 --- /dev/null +++ b/docs/models/outputmodality.md @@ -0,0 +1,10 @@ +# OutputModality + + +## Values + +| Name | Value | +| ------------ | ------------ | +| `TEXT` | text | +| `IMAGE` | image | +| `EMBEDDINGS` | embeddings | \ No newline at end of file diff --git a/docs/models/outputtokensdetails.md b/docs/models/outputtokensdetails.md new file mode 100644 index 0000000..430d40b --- /dev/null +++ b/docs/models/outputtokensdetails.md @@ -0,0 +1,8 @@ +# OutputTokensDetails + + +## Fields + +| Field | Type | Required | Description | +| ------------------ | ------------------ | ------------------ | ------------------ | +| `reasoning_tokens` | *float* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/parameter.md b/docs/models/parameter.md new file mode 100644 index 0000000..3640dfa --- /dev/null +++ b/docs/models/parameter.md @@ -0,0 +1,30 @@ +# Parameter + + +## Values + +| Name | Value | +| --------------------- | --------------------- | +| `TEMPERATURE` | temperature | +| `TOP_P` | top_p | +| `TOP_K` | top_k | +| `MIN_P` | min_p | +| `TOP_A` | top_a | +| `FREQUENCY_PENALTY` | frequency_penalty | +| `PRESENCE_PENALTY` | presence_penalty | +| `REPETITION_PENALTY` | repetition_penalty | +| `MAX_TOKENS` | max_tokens | +| `LOGIT_BIAS` | logit_bias | +| `LOGPROBS` | logprobs | +| `TOP_LOGPROBS` | top_logprobs | +| `SEED` | seed | +| `RESPONSE_FORMAT` | response_format | +| `STRUCTURED_OUTPUTS` | structured_outputs | +| `STOP` | stop | +| `TOOLS` | tools | +| `TOOL_CHOICE` | tool_choice | +| `PARALLEL_TOOL_CALLS` | parallel_tool_calls | +| `INCLUDE_REASONING` | include_reasoning | +| `REASONING` | reasoning | +| `WEB_SEARCH_OPTIONS` | web_search_options | +| `VERBOSITY` | verbosity | \ No newline at end of file diff --git a/docs/models/part1.md b/docs/models/part1.md new file mode 100644 index 0000000..616ad1c --- /dev/null +++ b/docs/models/part1.md @@ -0,0 +1,23 @@ +# Part1 + + +## Supported Types + +### `models.ResponseOutputText` + +```python +value: models.ResponseOutputText = /* values here */ +``` + +### `models.ReasoningTextContent` + +```python +value: models.ReasoningTextContent = /* values here */ +``` + +### `models.OpenAIResponsesRefusalContent` + +```python +value: models.OpenAIResponsesRefusalContent = /* values here */ +``` + diff --git a/docs/models/part2.md b/docs/models/part2.md new file mode 100644 index 0000000..837b1c4 --- /dev/null +++ b/docs/models/part2.md @@ -0,0 +1,23 @@ +# Part2 + + +## Supported Types + +### `models.ResponseOutputText` + +```python +value: models.ResponseOutputText = /* values here */ +``` + +### `models.ReasoningTextContent` + +```python +value: models.ReasoningTextContent = /* values here */ +``` + +### `models.OpenAIResponsesRefusalContent` + +```python +value: models.OpenAIResponsesRefusalContent = /* values here */ +``` + diff --git a/docs/models/payloadtoolargeresponseerrordata.md b/docs/models/payloadtoolargeresponseerrordata.md new file mode 100644 index 0000000..197ba50 --- /dev/null +++ b/docs/models/payloadtoolargeresponseerrordata.md @@ -0,0 +1,12 @@ +# PayloadTooLargeResponseErrorData + +Error data for PayloadTooLargeResponse + + +## Fields + +| Field | Type | Required | Description | +| -------------------------- | -------------------------- | -------------------------- | -------------------------- | +| `code` | *int* | :heavy_check_mark: | N/A | +| `message` | *str* | :heavy_check_mark: | N/A | +| `metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/paymentrequiredresponseerrordata.md b/docs/models/paymentrequiredresponseerrordata.md new file mode 100644 index 0000000..e083b1f --- /dev/null +++ b/docs/models/paymentrequiredresponseerrordata.md @@ -0,0 +1,12 @@ +# PaymentRequiredResponseErrorData + +Error data for PaymentRequiredResponse + + +## Fields + +| Field | Type | Required | Description | +| -------------------------- | -------------------------- | -------------------------- | -------------------------- | +| `code` | *int* | :heavy_check_mark: | N/A | +| `message` | *str* | :heavy_check_mark: | N/A | +| `metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/pdf.md b/docs/models/pdf.md new file mode 100644 index 0000000..aa1a388 --- /dev/null +++ b/docs/models/pdf.md @@ -0,0 +1,8 @@ +# Pdf + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------- | ---------------------------------------------------- | ---------------------------------------------------- | ---------------------------------------------------- | +| `engine` | [Optional[models.PdfEngine]](../models/pdfengine.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/pdfengine.md b/docs/models/pdfengine.md new file mode 100644 index 0000000..55bca5e --- /dev/null +++ b/docs/models/pdfengine.md @@ -0,0 +1,10 @@ +# PdfEngine + + +## Values + +| Name | Value | +| ------------- | ------------- | +| `MISTRAL_OCR` | mistral-ocr | +| `PDF_TEXT` | pdf-text | +| `NATIVE` | native | \ No newline at end of file diff --git a/docs/models/perrequestlimits.md b/docs/models/perrequestlimits.md new file mode 100644 index 0000000..607ebc6 --- /dev/null +++ b/docs/models/perrequestlimits.md @@ -0,0 +1,11 @@ +# PerRequestLimits + +Per-request token limits + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------- | ------------------------------------- | ------------------------------------- | ------------------------------------- | ------------------------------------- | +| `prompt_tokens` | *float* | :heavy_check_mark: | Maximum prompt tokens per request | 1000 | +| `completion_tokens` | *float* | :heavy_check_mark: | Maximum completion tokens per request | 1000 | \ No newline at end of file diff --git a/docs/models/plugin.md b/docs/models/plugin.md new file mode 100644 index 0000000..722ad28 --- /dev/null +++ b/docs/models/plugin.md @@ -0,0 +1,23 @@ +# Plugin + + +## Supported Types + +### `models.PluginModeration` + +```python +value: models.PluginModeration = /* values here */ +``` + +### `models.PluginWeb` + +```python +value: models.PluginWeb = /* values here */ +``` + +### `models.PluginFileParser` + +```python +value: models.PluginFileParser = /* values here */ +``` + diff --git a/docs/models/pluginfileparser.md b/docs/models/pluginfileparser.md new file mode 100644 index 0000000..c49e7aa --- /dev/null +++ b/docs/models/pluginfileparser.md @@ -0,0 +1,10 @@ +# PluginFileParser + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------ | ------------------------------------------------ | ------------------------------------------------ | ------------------------------------------------ | +| `id` | [models.IDFileParser](../models/idfileparser.md) | :heavy_check_mark: | N/A | +| `max_files` | *Optional[float]* | :heavy_minus_sign: | N/A | +| `pdf` | [Optional[models.Pdf]](../models/pdf.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/pluginmoderation.md b/docs/models/pluginmoderation.md new file mode 100644 index 0000000..0e58d2f --- /dev/null +++ b/docs/models/pluginmoderation.md @@ -0,0 +1,8 @@ +# PluginModeration + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------ | ------------------------------------------------ | ------------------------------------------------ | ------------------------------------------------ | +| `id` | [models.IDModeration](../models/idmoderation.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/pluginweb.md b/docs/models/pluginweb.md new file mode 100644 index 0000000..50e2c17 --- /dev/null +++ b/docs/models/pluginweb.md @@ -0,0 +1,11 @@ +# PluginWeb + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------- | ---------------------------------------------- | ---------------------------------------------- | ---------------------------------------------- | +| `id` | [models.IDWeb](../models/idweb.md) | :heavy_check_mark: | N/A | +| `max_results` | *Optional[float]* | :heavy_minus_sign: | N/A | +| `search_prompt` | *Optional[str]* | :heavy_minus_sign: | N/A | +| `engine` | [Optional[models.Engine]](../models/engine.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/pricing.md b/docs/models/pricing.md new file mode 100644 index 0000000..1a44ac7 --- /dev/null +++ b/docs/models/pricing.md @@ -0,0 +1,19 @@ +# Pricing + + +## Fields + +| Field | Type | Required | Description | +| --------------------------------------------------------- | --------------------------------------------------------- | --------------------------------------------------------- | --------------------------------------------------------- | +| `prompt` | *Any* | :heavy_check_mark: | A value in string or number format that is a large number | +| `completion` | *Any* | :heavy_check_mark: | A value in string or number format that is a large number | +| `request` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number | +| `image` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number | +| `image_output` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number | +| `audio` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number | +| `input_audio_cache` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number | +| `web_search` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number | +| `internal_reasoning` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number | +| `input_cache_read` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number | +| `input_cache_write` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number | +| `discount` | *Optional[float]* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/prompt.md b/docs/models/prompt.md new file mode 100644 index 0000000..c700709 --- /dev/null +++ b/docs/models/prompt.md @@ -0,0 +1,29 @@ +# Prompt + + +## Supported Types + +### `str` + +```python +value: str = /* values here */ +``` + +### `List[str]` + +```python +value: List[str] = /* values here */ +``` + +### `List[float]` + +```python +value: List[float] = /* values here */ +``` + +### `List[List[float]]` + +```python +value: List[List[float]] = /* values here */ +``` + diff --git a/docs/models/prompttokensdetails.md b/docs/models/prompttokensdetails.md new file mode 100644 index 0000000..a7248a0 --- /dev/null +++ b/docs/models/prompttokensdetails.md @@ -0,0 +1,10 @@ +# PromptTokensDetails + + +## Fields + +| Field | Type | Required | Description | +| ------------------ | ------------------ | ------------------ | ------------------ | +| `cached_tokens` | *Optional[float]* | :heavy_minus_sign: | N/A | +| `audio_tokens` | *Optional[float]* | :heavy_minus_sign: | N/A | +| `video_tokens` | *Optional[float]* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/provider.md b/docs/models/provider.md new file mode 100644 index 0000000..068f99d --- /dev/null +++ b/docs/models/provider.md @@ -0,0 +1,20 @@ +# Provider + +When multiple model providers are available, optionally indicate your routing preference. + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `allow_fallbacks` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to allow backup providers to serve requests
- true: (default) when the primary provider (or your custom providers in "order") is unavailable, use the next best provider.
- false: use only the primary/custom provider, and return the upstream error if it's unavailable.
| | +| `require_parameters` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to filter providers to only those that support the parameters you've provided. If this setting is omitted or set to false, then providers will receive only the parameters they support, and ignore the rest. | | +| `data_collection` | [OptionalNullable[models.DataCollection]](../models/datacollection.md) | :heavy_minus_sign: | Data collection setting. If no available model provider meets the requirement, your request will return an error.
- allow: (default) allow providers which store user data non-transiently and may train on it
- deny: use only providers which do not collect user data.
| deny | +| `zdr` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to restrict routing to only ZDR (Zero Data Retention) endpoints. When true, only endpoints that do not retain prompts will be used. | true | +| `enforce_distillable_text` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to restrict routing to only models that allow text distillation. When true, only models where the author has allowed distillation will be used. | true | +| `order` | List[[models.Order](../models/order.md)] | :heavy_minus_sign: | An ordered list of provider slugs. The router will attempt to use the first provider in the subset of this list that supports your requested model, and fall back to the next if it is unavailable. If no providers are available, the request will fail with an error message. | | +| `only` | List[[models.Only](../models/only.md)] | :heavy_minus_sign: | List of provider slugs to allow. If provided, this list is merged with your account-wide allowed provider settings for this request. | | +| `ignore` | List[[models.Ignore](../models/ignore.md)] | :heavy_minus_sign: | List of provider slugs to ignore. If provided, this list is merged with your account-wide ignored provider settings for this request. | | +| `quantizations` | List[[models.Quantization](../models/quantization.md)] | :heavy_minus_sign: | A list of quantization levels to filter the provider by. | | +| `sort` | [OptionalNullable[models.Sort]](../models/sort.md) | :heavy_minus_sign: | The sorting strategy to use for this request, if "order" is not specified. When set, no load balancing is performed. | price | +| `max_price` | [Optional[models.MaxPrice]](../models/maxprice.md) | :heavy_minus_sign: | The object specifying the maximum price you want to pay for this request. USD price per million tokens, for prompt and completion. | | \ No newline at end of file diff --git a/docs/models/providername.md b/docs/models/providername.md new file mode 100644 index 0000000..f29b89d --- /dev/null +++ b/docs/models/providername.md @@ -0,0 +1,93 @@ +# ProviderName + + +## Values + +| Name | Value | +| ------------------ | ------------------ | +| `ANY_SCALE` | AnyScale | +| `CENT_ML` | Cent-ML | +| `HUGGING_FACE` | HuggingFace | +| `HYPERBOLIC_2` | Hyperbolic 2 | +| `LEPTON` | Lepton | +| `LYNN_2` | Lynn 2 | +| `LYNN` | Lynn | +| `MANCER` | Mancer | +| `MODAL` | Modal | +| `OCTO_AI` | OctoAI | +| `RECURSAL` | Recursal | +| `REFLECTION` | Reflection | +| `REPLICATE` | Replicate | +| `SAMBA_NOVA_2` | SambaNova 2 | +| `SF_COMPUTE` | SF Compute | +| `TOGETHER_2` | Together 2 | +| `ONE_DOT_AI` | 01.AI | +| `AI21` | AI21 | +| `AION_LABS` | AionLabs | +| `ALIBABA` | Alibaba | +| `AMAZON_BEDROCK` | Amazon Bedrock | +| `ANTHROPIC` | Anthropic | +| `ATLAS_CLOUD` | AtlasCloud | +| `ATOMA` | Atoma | +| `AVIAN` | Avian | +| `AZURE` | Azure | +| `BASE_TEN` | BaseTen | +| `CEREBRAS` | Cerebras | +| `CHUTES` | Chutes | +| `CIRRASCALE` | Cirrascale | +| `CLARIFAI` | Clarifai | +| `CLOUDFLARE` | Cloudflare | +| `COHERE` | Cohere | +| `CROF_AI` | CrofAI | +| `CRUSOE` | Crusoe | +| `DEEP_INFRA` | DeepInfra | +| `DEEP_SEEK` | DeepSeek | +| `ENFER` | Enfer | +| `FEATHERLESS` | Featherless | +| `FIREWORKS` | Fireworks | +| `FRIENDLI` | Friendli | +| `GMI_CLOUD` | GMICloud | +| `GOOGLE` | Google | +| `GOOGLE_AI_STUDIO` | Google AI Studio | +| `GROQ` | Groq | +| `HYPERBOLIC` | Hyperbolic | +| `INCEPTION` | Inception | +| `INFERENCE_NET` | InferenceNet | +| `INFERMATIC` | Infermatic | +| `INFLECTION` | Inflection | +| `INO_CLOUD` | InoCloud | +| `KLUSTER` | Kluster | +| `LAMBDA` | Lambda | +| `LIQUID` | Liquid | +| `MANCER_2` | Mancer 2 | +| `META` | Meta | +| `MINIMAX` | Minimax | +| `MODEL_RUN` | ModelRun | +| `MISTRAL` | Mistral | +| `MODULAR` | Modular | +| `MOONSHOT_AI` | Moonshot AI | +| `MORPH` | Morph | +| `N_COMPASS` | NCompass | +| `NEBIUS` | Nebius | +| `NEXT_BIT` | NextBit | +| `NINETEEN` | Nineteen | +| `NOVITA` | Novita | +| `NVIDIA` | Nvidia | +| `OPEN_AI` | OpenAI | +| `OPEN_INFERENCE` | OpenInference | +| `PARASAIL` | Parasail | +| `PERPLEXITY` | Perplexity | +| `PHALA` | Phala | +| `RELACE` | Relace | +| `SAMBA_NOVA` | SambaNova | +| `SILICON_FLOW` | SiliconFlow | +| `STEALTH` | Stealth | +| `SWITCHPOINT` | Switchpoint | +| `TARGON` | Targon | +| `TOGETHER` | Together | +| `UBICLOUD` | Ubicloud | +| `VENICE` | Venice | +| `WAND_B` | WandB | +| `X_AI` | xAI | +| `Z_AI` | Z.AI | +| `FAKE_PROVIDER` | FakeProvider | \ No newline at end of file diff --git a/docs/models/provideroverloadedresponseerrordata.md b/docs/models/provideroverloadedresponseerrordata.md new file mode 100644 index 0000000..afebc30 --- /dev/null +++ b/docs/models/provideroverloadedresponseerrordata.md @@ -0,0 +1,12 @@ +# ProviderOverloadedResponseErrorData + +Error data for ProviderOverloadedResponse + + +## Fields + +| Field | Type | Required | Description | +| -------------------------- | -------------------------- | -------------------------- | -------------------------- | +| `code` | *int* | :heavy_check_mark: | N/A | +| `message` | *str* | :heavy_check_mark: | N/A | +| `metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/publicendpoint.md b/docs/models/publicendpoint.md new file mode 100644 index 0000000..429351f --- /dev/null +++ b/docs/models/publicendpoint.md @@ -0,0 +1,22 @@ +# PublicEndpoint + +Information about a specific model endpoint + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | +| `name` | *str* | :heavy_check_mark: | N/A | | +| `model_name` | *str* | :heavy_check_mark: | N/A | | +| `context_length` | *float* | :heavy_check_mark: | N/A | | +| `pricing` | [models.Pricing](../models/pricing.md) | :heavy_check_mark: | N/A | | +| `provider_name` | [models.ProviderName](../models/providername.md) | :heavy_check_mark: | N/A | OpenAI | +| `tag` | *str* | :heavy_check_mark: | N/A | | +| `quantization` | [Nullable[models.PublicEndpointQuantization]](../models/publicendpointquantization.md) | :heavy_check_mark: | N/A | fp16 | +| `max_completion_tokens` | *Nullable[float]* | :heavy_check_mark: | N/A | | +| `max_prompt_tokens` | *Nullable[float]* | :heavy_check_mark: | N/A | | +| `supported_parameters` | List[[models.Parameter](../models/parameter.md)] | :heavy_check_mark: | N/A | | +| `status` | [Optional[models.EndpointStatus]](../models/endpointstatus.md) | :heavy_minus_sign: | N/A | 0 | +| `uptime_last_30m` | *Nullable[float]* | :heavy_check_mark: | N/A | | +| `supports_implicit_caching` | *bool* | :heavy_check_mark: | N/A | | \ No newline at end of file diff --git a/docs/models/publicendpointquantization.md b/docs/models/publicendpointquantization.md new file mode 100644 index 0000000..7d0edd2 --- /dev/null +++ b/docs/models/publicendpointquantization.md @@ -0,0 +1,16 @@ +# PublicEndpointQuantization + + +## Values + +| Name | Value | +| --------- | --------- | +| `INT4` | int4 | +| `INT8` | int8 | +| `FP4` | fp4 | +| `FP6` | fp6 | +| `FP8` | fp8 | +| `FP16` | fp16 | +| `BF16` | bf16 | +| `FP32` | fp32 | +| `UNKNOWN` | unknown | \ No newline at end of file diff --git a/docs/models/publicpricing.md b/docs/models/publicpricing.md new file mode 100644 index 0000000..5d92c94 --- /dev/null +++ b/docs/models/publicpricing.md @@ -0,0 +1,21 @@ +# PublicPricing + +Pricing information for the model + + +## Fields + +| Field | Type | Required | Description | +| --------------------------------------------------------- | --------------------------------------------------------- | --------------------------------------------------------- | --------------------------------------------------------- | +| `prompt` | *Any* | :heavy_check_mark: | A value in string or number format that is a large number | +| `completion` | *Any* | :heavy_check_mark: | A value in string or number format that is a large number | +| `request` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number | +| `image` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number | +| `image_output` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number | +| `audio` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number | +| `input_audio_cache` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number | +| `web_search` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number | +| `internal_reasoning` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number | +| `input_cache_read` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number | +| `input_cache_write` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number | +| `discount` | *Optional[float]* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/quantization.md b/docs/models/quantization.md new file mode 100644 index 0000000..7a0574a --- /dev/null +++ b/docs/models/quantization.md @@ -0,0 +1,16 @@ +# Quantization + + +## Values + +| Name | Value | +| --------- | --------- | +| `INT4` | int4 | +| `INT8` | int8 | +| `FP4` | fp4 | +| `FP6` | fp6 | +| `FP8` | fp8 | +| `FP16` | fp16 | +| `BF16` | bf16 | +| `FP32` | fp32 | +| `UNKNOWN` | unknown | \ No newline at end of file diff --git a/docs/models/ratelimit.md b/docs/models/ratelimit.md new file mode 100644 index 0000000..635db2a --- /dev/null +++ b/docs/models/ratelimit.md @@ -0,0 +1,14 @@ +# ~~RateLimit~~ + +Legacy rate limit information about a key. Will always return -1. + +> :warning: **DEPRECATED**: This will be removed in a future release, please migrate away from it as soon as possible. + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------------- | -------------------------------------------- | -------------------------------------------- | -------------------------------------------- | -------------------------------------------- | +| `requests` | *float* | :heavy_check_mark: | Number of requests allowed per interval | 1000 | +| `interval` | *str* | :heavy_check_mark: | Rate limit interval | 1h | +| `note` | *str* | :heavy_check_mark: | Note about the rate limit | This field is deprecated and safe to ignore. | \ No newline at end of file diff --git a/docs/models/reason.md b/docs/models/reason.md new file mode 100644 index 0000000..1c21d04 --- /dev/null +++ b/docs/models/reason.md @@ -0,0 +1,9 @@ +# Reason + + +## Values + +| Name | Value | +| ------------------- | ------------------- | +| `MAX_OUTPUT_TOKENS` | max_output_tokens | +| `CONTENT_FILTER` | content_filter | \ No newline at end of file diff --git a/docs/models/reasoning.md b/docs/models/reasoning.md new file mode 100644 index 0000000..efb211b --- /dev/null +++ b/docs/models/reasoning.md @@ -0,0 +1,9 @@ +# Reasoning + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | +| `effort` | [OptionalNullable[models.Effort]](../models/effort.md) | :heavy_minus_sign: | N/A | +| `summary` | [OptionalNullable[models.ReasoningSummaryVerbosity]](../models/reasoningsummaryverbosity.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/reasoningsummarytext.md b/docs/models/reasoningsummarytext.md new file mode 100644 index 0000000..3b30934 --- /dev/null +++ b/docs/models/reasoningsummarytext.md @@ -0,0 +1,9 @@ +# ReasoningSummaryText + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | +| `type` | [models.ReasoningSummaryTextType](../models/reasoningsummarytexttype.md) | :heavy_check_mark: | N/A | +| `text` | *str* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/reasoningsummarytexttype.md b/docs/models/reasoningsummarytexttype.md new file mode 100644 index 0000000..af36e33 --- /dev/null +++ b/docs/models/reasoningsummarytexttype.md @@ -0,0 +1,8 @@ +# ReasoningSummaryTextType + + +## Values + +| Name | Value | +| -------------- | -------------- | +| `SUMMARY_TEXT` | summary_text | \ No newline at end of file diff --git a/docs/models/reasoningsummaryverbosity.md b/docs/models/reasoningsummaryverbosity.md new file mode 100644 index 0000000..cc36f39 --- /dev/null +++ b/docs/models/reasoningsummaryverbosity.md @@ -0,0 +1,10 @@ +# ReasoningSummaryVerbosity + + +## Values + +| Name | Value | +| ---------- | ---------- | +| `AUTO` | auto | +| `CONCISE` | concise | +| `DETAILED` | detailed | \ No newline at end of file diff --git a/docs/models/reasoningtextcontent.md b/docs/models/reasoningtextcontent.md new file mode 100644 index 0000000..686344f --- /dev/null +++ b/docs/models/reasoningtextcontent.md @@ -0,0 +1,9 @@ +# ReasoningTextContent + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | +| `type` | [models.ReasoningTextContentType](../models/reasoningtextcontenttype.md) | :heavy_check_mark: | N/A | +| `text` | *str* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/reasoningtextcontenttype.md b/docs/models/reasoningtextcontenttype.md new file mode 100644 index 0000000..f3646d4 --- /dev/null +++ b/docs/models/reasoningtextcontenttype.md @@ -0,0 +1,8 @@ +# ReasoningTextContentType + + +## Values + +| Name | Value | +| ---------------- | ---------------- | +| `REASONING_TEXT` | reasoning_text | \ No newline at end of file diff --git a/docs/models/requesttimeoutresponseerrordata.md b/docs/models/requesttimeoutresponseerrordata.md new file mode 100644 index 0000000..2e062ef --- /dev/null +++ b/docs/models/requesttimeoutresponseerrordata.md @@ -0,0 +1,12 @@ +# RequestTimeoutResponseErrorData + +Error data for RequestTimeoutResponse + + +## Fields + +| Field | Type | Required | Description | +| -------------------------- | -------------------------- | -------------------------- | -------------------------- | +| `code` | *int* | :heavy_check_mark: | N/A | +| `message` | *str* | :heavy_check_mark: | N/A | +| `metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/responseformatjsonschema.md b/docs/models/responseformatjsonschema.md new file mode 100644 index 0000000..df70191 --- /dev/null +++ b/docs/models/responseformatjsonschema.md @@ -0,0 +1,9 @@ +# ResponseFormatJSONSchema + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------- | -------------------------------------------------------- | -------------------------------------------------------- | -------------------------------------------------------- | +| `type` | *Literal["json_schema"]* | :heavy_check_mark: | N/A | +| `json_schema` | [models.JSONSchemaConfig](../models/jsonschemaconfig.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/responseformattextconfig.md b/docs/models/responseformattextconfig.md new file mode 100644 index 0000000..0d91504 --- /dev/null +++ b/docs/models/responseformattextconfig.md @@ -0,0 +1,25 @@ +# ResponseFormatTextConfig + +Text response format configuration + + +## Supported Types + +### `models.ResponsesFormatText` + +```python +value: models.ResponsesFormatText = /* values here */ +``` + +### `models.ResponsesFormatJSONObject` + +```python +value: models.ResponsesFormatJSONObject = /* values here */ +``` + +### `models.ResponsesFormatTextJSONSchemaConfig` + +```python +value: models.ResponsesFormatTextJSONSchemaConfig = /* values here */ +``` + diff --git a/docs/models/responseformattextgrammar.md b/docs/models/responseformattextgrammar.md new file mode 100644 index 0000000..f0590f3 --- /dev/null +++ b/docs/models/responseformattextgrammar.md @@ -0,0 +1,9 @@ +# ResponseFormatTextGrammar + + +## Fields + +| Field | Type | Required | Description | +| -------------------- | -------------------- | -------------------- | -------------------- | +| `type` | *Literal["grammar"]* | :heavy_check_mark: | N/A | +| `grammar` | *str* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/responseinputaudio.md b/docs/models/responseinputaudio.md new file mode 100644 index 0000000..bccbe0d --- /dev/null +++ b/docs/models/responseinputaudio.md @@ -0,0 +1,11 @@ +# ResponseInputAudio + +Audio input content item + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | +| `type` | [models.ResponseInputAudioType](../models/responseinputaudiotype.md) | :heavy_check_mark: | N/A | +| `input_audio` | [models.ResponseInputAudioInputAudio](../models/responseinputaudioinputaudio.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/responseinputaudioformat.md b/docs/models/responseinputaudioformat.md new file mode 100644 index 0000000..524d473 --- /dev/null +++ b/docs/models/responseinputaudioformat.md @@ -0,0 +1,9 @@ +# ResponseInputAudioFormat + + +## Values + +| Name | Value | +| ----- | ----- | +| `MP3` | mp3 | +| `WAV` | wav | \ No newline at end of file diff --git a/docs/models/responseinputaudioinputaudio.md b/docs/models/responseinputaudioinputaudio.md new file mode 100644 index 0000000..7b573e1 --- /dev/null +++ b/docs/models/responseinputaudioinputaudio.md @@ -0,0 +1,9 @@ +# ResponseInputAudioInputAudio + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | +| `data` | *str* | :heavy_check_mark: | N/A | +| `format_` | [models.ResponseInputAudioFormat](../models/responseinputaudioformat.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/responseinputaudiotype.md b/docs/models/responseinputaudiotype.md new file mode 100644 index 0000000..77245e2 --- /dev/null +++ b/docs/models/responseinputaudiotype.md @@ -0,0 +1,8 @@ +# ResponseInputAudioType + + +## Values + +| Name | Value | +| ------------- | ------------- | +| `INPUT_AUDIO` | input_audio | \ No newline at end of file diff --git a/docs/models/responseinputfile.md b/docs/models/responseinputfile.md new file mode 100644 index 0000000..0a41cd5 --- /dev/null +++ b/docs/models/responseinputfile.md @@ -0,0 +1,14 @@ +# ResponseInputFile + +File input content item + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | +| `type` | [models.ResponseInputFileType](../models/responseinputfiletype.md) | :heavy_check_mark: | N/A | +| `file_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | +| `file_data` | *Optional[str]* | :heavy_minus_sign: | N/A | +| `filename` | *Optional[str]* | :heavy_minus_sign: | N/A | +| `file_url` | *Optional[str]* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/responseinputfiletype.md b/docs/models/responseinputfiletype.md new file mode 100644 index 0000000..4528713 --- /dev/null +++ b/docs/models/responseinputfiletype.md @@ -0,0 +1,8 @@ +# ResponseInputFileType + + +## Values + +| Name | Value | +| ------------ | ------------ | +| `INPUT_FILE` | input_file | \ No newline at end of file diff --git a/docs/models/responseinputimage.md b/docs/models/responseinputimage.md new file mode 100644 index 0000000..19a3c73 --- /dev/null +++ b/docs/models/responseinputimage.md @@ -0,0 +1,12 @@ +# ResponseInputImage + +Image input content item + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | +| `type` | [models.ResponseInputImageType](../models/responseinputimagetype.md) | :heavy_check_mark: | N/A | +| `detail` | [models.ResponseInputImageDetail](../models/responseinputimagedetail.md) | :heavy_check_mark: | N/A | +| `image_url` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/responseinputimagedetail.md b/docs/models/responseinputimagedetail.md new file mode 100644 index 0000000..0e31c6e --- /dev/null +++ b/docs/models/responseinputimagedetail.md @@ -0,0 +1,10 @@ +# ResponseInputImageDetail + + +## Values + +| Name | Value | +| ------ | ------ | +| `AUTO` | auto | +| `HIGH` | high | +| `LOW` | low | \ No newline at end of file diff --git a/docs/models/responseinputimagetype.md b/docs/models/responseinputimagetype.md new file mode 100644 index 0000000..1754be9 --- /dev/null +++ b/docs/models/responseinputimagetype.md @@ -0,0 +1,8 @@ +# ResponseInputImageType + + +## Values + +| Name | Value | +| ------------- | ------------- | +| `INPUT_IMAGE` | input_image | \ No newline at end of file diff --git a/docs/models/responseinputtext.md b/docs/models/responseinputtext.md new file mode 100644 index 0000000..b82824b --- /dev/null +++ b/docs/models/responseinputtext.md @@ -0,0 +1,11 @@ +# ResponseInputText + +Text input content item + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | +| `type` | [models.ResponseInputTextType](../models/responseinputtexttype.md) | :heavy_check_mark: | N/A | +| `text` | *str* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/responseinputtexttype.md b/docs/models/responseinputtexttype.md new file mode 100644 index 0000000..896f063 --- /dev/null +++ b/docs/models/responseinputtexttype.md @@ -0,0 +1,8 @@ +# ResponseInputTextType + + +## Values + +| Name | Value | +| ------------ | ------------ | +| `INPUT_TEXT` | input_text | \ No newline at end of file diff --git a/docs/models/responseoutputtext.md b/docs/models/responseoutputtext.md new file mode 100644 index 0000000..737d392 --- /dev/null +++ b/docs/models/responseoutputtext.md @@ -0,0 +1,10 @@ +# ResponseOutputText + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | +| `type` | [models.ResponseOutputTextType](../models/responseoutputtexttype.md) | :heavy_check_mark: | N/A | +| `text` | *str* | :heavy_check_mark: | N/A | +| `annotations` | List[[models.OpenAIResponsesAnnotation](../models/openairesponsesannotation.md)] | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/responseoutputtexttype.md b/docs/models/responseoutputtexttype.md new file mode 100644 index 0000000..8c8a3d7 --- /dev/null +++ b/docs/models/responseoutputtexttype.md @@ -0,0 +1,8 @@ +# ResponseOutputTextType + + +## Values + +| Name | Value | +| ------------- | ------------- | +| `OUTPUT_TEXT` | output_text | \ No newline at end of file diff --git a/docs/models/responseserrorfield.md b/docs/models/responseserrorfield.md new file mode 100644 index 0000000..92e368d --- /dev/null +++ b/docs/models/responseserrorfield.md @@ -0,0 +1,11 @@ +# ResponsesErrorField + +Error information returned from the API + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | +| `code` | [models.CodeEnum](../models/codeenum.md) | :heavy_check_mark: | N/A | +| `message` | *str* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/responsesformatjsonobject.md b/docs/models/responsesformatjsonobject.md new file mode 100644 index 0000000..4e0f35c --- /dev/null +++ b/docs/models/responsesformatjsonobject.md @@ -0,0 +1,10 @@ +# ResponsesFormatJSONObject + +JSON object response format + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | +| `type` | [models.ResponsesFormatJSONObjectType](../models/responsesformatjsonobjecttype.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/responsesformatjsonobjecttype.md b/docs/models/responsesformatjsonobjecttype.md new file mode 100644 index 0000000..93a2472 --- /dev/null +++ b/docs/models/responsesformatjsonobjecttype.md @@ -0,0 +1,8 @@ +# ResponsesFormatJSONObjectType + + +## Values + +| Name | Value | +| ------------- | ------------- | +| `JSON_OBJECT` | json_object | \ No newline at end of file diff --git a/docs/models/responsesformattext.md b/docs/models/responsesformattext.md new file mode 100644 index 0000000..f47ccfc --- /dev/null +++ b/docs/models/responsesformattext.md @@ -0,0 +1,10 @@ +# ResponsesFormatText + +Plain text response format + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | +| `type` | [models.ResponsesFormatTextType](../models/responsesformattexttype.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/responsesformattextjsonschemaconfig.md b/docs/models/responsesformattextjsonschemaconfig.md new file mode 100644 index 0000000..13b20b9 --- /dev/null +++ b/docs/models/responsesformattextjsonschemaconfig.md @@ -0,0 +1,14 @@ +# ResponsesFormatTextJSONSchemaConfig + +JSON schema constrained response format + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | +| `type` | [models.ResponsesFormatTextJSONSchemaConfigType](../models/responsesformattextjsonschemaconfigtype.md) | :heavy_check_mark: | N/A | +| `name` | *str* | :heavy_check_mark: | N/A | +| `description` | *Optional[str]* | :heavy_minus_sign: | N/A | +| `strict` | *OptionalNullable[bool]* | :heavy_minus_sign: | N/A | +| `schema_` | Dict[str, *Nullable[Any]*] | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/responsesformattextjsonschemaconfigtype.md b/docs/models/responsesformattextjsonschemaconfigtype.md new file mode 100644 index 0000000..60eb553 --- /dev/null +++ b/docs/models/responsesformattextjsonschemaconfigtype.md @@ -0,0 +1,8 @@ +# ResponsesFormatTextJSONSchemaConfigType + + +## Values + +| Name | Value | +| ------------- | ------------- | +| `JSON_SCHEMA` | json_schema | \ No newline at end of file diff --git a/docs/models/responsesformattexttype.md b/docs/models/responsesformattexttype.md new file mode 100644 index 0000000..2e8fd48 --- /dev/null +++ b/docs/models/responsesformattexttype.md @@ -0,0 +1,8 @@ +# ResponsesFormatTextType + + +## Values + +| Name | Value | +| ------ | ------ | +| `TEXT` | text | \ No newline at end of file diff --git a/docs/models/responsesimagegenerationcall.md b/docs/models/responsesimagegenerationcall.md new file mode 100644 index 0000000..f095958 --- /dev/null +++ b/docs/models/responsesimagegenerationcall.md @@ -0,0 +1,11 @@ +# ResponsesImageGenerationCall + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | +| `type` | [models.ResponsesImageGenerationCallType](../models/responsesimagegenerationcalltype.md) | :heavy_check_mark: | N/A | | +| `id` | *str* | :heavy_check_mark: | N/A | | +| `result` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | | +| `status` | [models.ImageGenerationStatus](../models/imagegenerationstatus.md) | :heavy_check_mark: | N/A | completed | \ No newline at end of file diff --git a/docs/models/responsesimagegenerationcalltype.md b/docs/models/responsesimagegenerationcalltype.md new file mode 100644 index 0000000..6eb99c3 --- /dev/null +++ b/docs/models/responsesimagegenerationcalltype.md @@ -0,0 +1,8 @@ +# ResponsesImageGenerationCallType + + +## Values + +| Name | Value | +| ----------------------- | ----------------------- | +| `IMAGE_GENERATION_CALL` | image_generation_call | \ No newline at end of file diff --git a/docs/models/responsesoutputitem.md b/docs/models/responsesoutputitem.md new file mode 100644 index 0000000..eedde5f --- /dev/null +++ b/docs/models/responsesoutputitem.md @@ -0,0 +1,43 @@ +# ResponsesOutputItem + +An output item from the response + + +## Supported Types + +### `models.ResponsesOutputMessage` + +```python +value: models.ResponsesOutputMessage = /* values here */ +``` + +### `models.ResponsesOutputItemReasoning` + +```python +value: models.ResponsesOutputItemReasoning = /* values here */ +``` + +### `models.ResponsesOutputItemFunctionCall` + +```python +value: models.ResponsesOutputItemFunctionCall = /* values here */ +``` + +### `models.ResponsesWebSearchCallOutput` + +```python +value: models.ResponsesWebSearchCallOutput = /* values here */ +``` + +### `models.ResponsesOutputItemFileSearchCall` + +```python +value: models.ResponsesOutputItemFileSearchCall = /* values here */ +``` + +### `models.ResponsesImageGenerationCall` + +```python +value: models.ResponsesImageGenerationCall = /* values here */ +``` + diff --git a/docs/models/responsesoutputitemfilesearchcall.md b/docs/models/responsesoutputitemfilesearchcall.md new file mode 100644 index 0000000..01877d4 --- /dev/null +++ b/docs/models/responsesoutputitemfilesearchcall.md @@ -0,0 +1,11 @@ +# ResponsesOutputItemFileSearchCall + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | +| `type` | [models.ResponsesOutputItemFileSearchCallType](../models/responsesoutputitemfilesearchcalltype.md) | :heavy_check_mark: | N/A | | +| `id` | *str* | :heavy_check_mark: | N/A | | +| `queries` | List[*str*] | :heavy_check_mark: | N/A | | +| `status` | [models.WebSearchStatus](../models/websearchstatus.md) | :heavy_check_mark: | N/A | completed | \ No newline at end of file diff --git a/docs/models/responsesoutputitemfilesearchcalltype.md b/docs/models/responsesoutputitemfilesearchcalltype.md new file mode 100644 index 0000000..2b4d6ea --- /dev/null +++ b/docs/models/responsesoutputitemfilesearchcalltype.md @@ -0,0 +1,8 @@ +# ResponsesOutputItemFileSearchCallType + + +## Values + +| Name | Value | +| ------------------ | ------------------ | +| `FILE_SEARCH_CALL` | file_search_call | \ No newline at end of file diff --git a/docs/models/responsesoutputitemfunctioncall.md b/docs/models/responsesoutputitemfunctioncall.md new file mode 100644 index 0000000..34bede6 --- /dev/null +++ b/docs/models/responsesoutputitemfunctioncall.md @@ -0,0 +1,13 @@ +# ResponsesOutputItemFunctionCall + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | +| `type` | [models.ResponsesOutputItemFunctionCallType](../models/responsesoutputitemfunctioncalltype.md) | :heavy_check_mark: | N/A | +| `id` | *Optional[str]* | :heavy_minus_sign: | N/A | +| `name` | *str* | :heavy_check_mark: | N/A | +| `arguments` | *str* | :heavy_check_mark: | N/A | +| `call_id` | *str* | :heavy_check_mark: | N/A | +| `status` | [Optional[models.ResponsesOutputItemFunctionCallStatusUnion]](../models/responsesoutputitemfunctioncallstatusunion.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/responsesoutputitemfunctioncallstatuscompleted.md b/docs/models/responsesoutputitemfunctioncallstatuscompleted.md new file mode 100644 index 0000000..f8d1ae0 --- /dev/null +++ b/docs/models/responsesoutputitemfunctioncallstatuscompleted.md @@ -0,0 +1,8 @@ +# ResponsesOutputItemFunctionCallStatusCompleted + + +## Values + +| Name | Value | +| ----------- | ----------- | +| `COMPLETED` | completed | \ No newline at end of file diff --git a/docs/models/responsesoutputitemfunctioncallstatusincomplete.md b/docs/models/responsesoutputitemfunctioncallstatusincomplete.md new file mode 100644 index 0000000..63df291 --- /dev/null +++ b/docs/models/responsesoutputitemfunctioncallstatusincomplete.md @@ -0,0 +1,8 @@ +# ResponsesOutputItemFunctionCallStatusIncomplete + + +## Values + +| Name | Value | +| ------------ | ------------ | +| `INCOMPLETE` | incomplete | \ No newline at end of file diff --git a/docs/models/responsesoutputitemfunctioncallstatusinprogress.md b/docs/models/responsesoutputitemfunctioncallstatusinprogress.md new file mode 100644 index 0000000..74e3945 --- /dev/null +++ b/docs/models/responsesoutputitemfunctioncallstatusinprogress.md @@ -0,0 +1,8 @@ +# ResponsesOutputItemFunctionCallStatusInProgress + + +## Values + +| Name | Value | +| ------------- | ------------- | +| `IN_PROGRESS` | in_progress | \ No newline at end of file diff --git a/docs/models/responsesoutputitemfunctioncallstatusunion.md b/docs/models/responsesoutputitemfunctioncallstatusunion.md new file mode 100644 index 0000000..1aca085 --- /dev/null +++ b/docs/models/responsesoutputitemfunctioncallstatusunion.md @@ -0,0 +1,23 @@ +# ResponsesOutputItemFunctionCallStatusUnion + + +## Supported Types + +### `models.ResponsesOutputItemFunctionCallStatusCompleted` + +```python +value: models.ResponsesOutputItemFunctionCallStatusCompleted = /* values here */ +``` + +### `models.ResponsesOutputItemFunctionCallStatusIncomplete` + +```python +value: models.ResponsesOutputItemFunctionCallStatusIncomplete = /* values here */ +``` + +### `models.ResponsesOutputItemFunctionCallStatusInProgress` + +```python +value: models.ResponsesOutputItemFunctionCallStatusInProgress = /* values here */ +``` + diff --git a/docs/models/responsesoutputitemfunctioncalltype.md b/docs/models/responsesoutputitemfunctioncalltype.md new file mode 100644 index 0000000..d1e5d65 --- /dev/null +++ b/docs/models/responsesoutputitemfunctioncalltype.md @@ -0,0 +1,8 @@ +# ResponsesOutputItemFunctionCallType + + +## Values + +| Name | Value | +| --------------- | --------------- | +| `FUNCTION_CALL` | function_call | \ No newline at end of file diff --git a/docs/models/responsesoutputitemreasoning.md b/docs/models/responsesoutputitemreasoning.md new file mode 100644 index 0000000..6d9afa9 --- /dev/null +++ b/docs/models/responsesoutputitemreasoning.md @@ -0,0 +1,15 @@ +# ResponsesOutputItemReasoning + +An output item containing reasoning + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | +| `type` | [models.ResponsesOutputItemReasoningType](../models/responsesoutputitemreasoningtype.md) | :heavy_check_mark: | N/A | +| `id` | *str* | :heavy_check_mark: | N/A | +| `content` | List[[models.ReasoningTextContent](../models/reasoningtextcontent.md)] | :heavy_minus_sign: | N/A | +| `summary` | List[[models.ReasoningSummaryText](../models/reasoningsummarytext.md)] | :heavy_check_mark: | N/A | +| `encrypted_content` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | +| `status` | [Optional[models.ResponsesOutputItemReasoningStatusUnion]](../models/responsesoutputitemreasoningstatusunion.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/responsesoutputitemreasoningstatuscompleted.md b/docs/models/responsesoutputitemreasoningstatuscompleted.md new file mode 100644 index 0000000..592e740 --- /dev/null +++ b/docs/models/responsesoutputitemreasoningstatuscompleted.md @@ -0,0 +1,8 @@ +# ResponsesOutputItemReasoningStatusCompleted + + +## Values + +| Name | Value | +| ----------- | ----------- | +| `COMPLETED` | completed | \ No newline at end of file diff --git a/docs/models/responsesoutputitemreasoningstatusincomplete.md b/docs/models/responsesoutputitemreasoningstatusincomplete.md new file mode 100644 index 0000000..55081b2 --- /dev/null +++ b/docs/models/responsesoutputitemreasoningstatusincomplete.md @@ -0,0 +1,8 @@ +# ResponsesOutputItemReasoningStatusIncomplete + + +## Values + +| Name | Value | +| ------------ | ------------ | +| `INCOMPLETE` | incomplete | \ No newline at end of file diff --git a/docs/models/responsesoutputitemreasoningstatusinprogress.md b/docs/models/responsesoutputitemreasoningstatusinprogress.md new file mode 100644 index 0000000..05ca983 --- /dev/null +++ b/docs/models/responsesoutputitemreasoningstatusinprogress.md @@ -0,0 +1,8 @@ +# ResponsesOutputItemReasoningStatusInProgress + + +## Values + +| Name | Value | +| ------------- | ------------- | +| `IN_PROGRESS` | in_progress | \ No newline at end of file diff --git a/docs/models/responsesoutputitemreasoningstatusunion.md b/docs/models/responsesoutputitemreasoningstatusunion.md new file mode 100644 index 0000000..960864d --- /dev/null +++ b/docs/models/responsesoutputitemreasoningstatusunion.md @@ -0,0 +1,23 @@ +# ResponsesOutputItemReasoningStatusUnion + + +## Supported Types + +### `models.ResponsesOutputItemReasoningStatusCompleted` + +```python +value: models.ResponsesOutputItemReasoningStatusCompleted = /* values here */ +``` + +### `models.ResponsesOutputItemReasoningStatusIncomplete` + +```python +value: models.ResponsesOutputItemReasoningStatusIncomplete = /* values here */ +``` + +### `models.ResponsesOutputItemReasoningStatusInProgress` + +```python +value: models.ResponsesOutputItemReasoningStatusInProgress = /* values here */ +``` + diff --git a/docs/models/responsesoutputitemreasoningtype.md b/docs/models/responsesoutputitemreasoningtype.md new file mode 100644 index 0000000..1b223b6 --- /dev/null +++ b/docs/models/responsesoutputitemreasoningtype.md @@ -0,0 +1,8 @@ +# ResponsesOutputItemReasoningType + + +## Values + +| Name | Value | +| ----------- | ----------- | +| `REASONING` | reasoning | \ No newline at end of file diff --git a/docs/models/responsesoutputmessage.md b/docs/models/responsesoutputmessage.md new file mode 100644 index 0000000..1722795 --- /dev/null +++ b/docs/models/responsesoutputmessage.md @@ -0,0 +1,14 @@ +# ResponsesOutputMessage + +An output message item + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | +| `id` | *str* | :heavy_check_mark: | N/A | +| `role` | [models.ResponsesOutputMessageRole](../models/responsesoutputmessagerole.md) | :heavy_check_mark: | N/A | +| `type` | [models.ResponsesOutputMessageType](../models/responsesoutputmessagetype.md) | :heavy_check_mark: | N/A | +| `status` | [Optional[models.ResponsesOutputMessageStatusUnion]](../models/responsesoutputmessagestatusunion.md) | :heavy_minus_sign: | N/A | +| `content` | List[[models.ResponsesOutputMessageContent](../models/responsesoutputmessagecontent.md)] | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/responsesoutputmessagecontent.md b/docs/models/responsesoutputmessagecontent.md new file mode 100644 index 0000000..a02f684 --- /dev/null +++ b/docs/models/responsesoutputmessagecontent.md @@ -0,0 +1,17 @@ +# ResponsesOutputMessageContent + + +## Supported Types + +### `models.ResponseOutputText` + +```python +value: models.ResponseOutputText = /* values here */ +``` + +### `models.OpenAIResponsesRefusalContent` + +```python +value: models.OpenAIResponsesRefusalContent = /* values here */ +``` + diff --git a/docs/models/responsesoutputmessagerole.md b/docs/models/responsesoutputmessagerole.md new file mode 100644 index 0000000..3eb534f --- /dev/null +++ b/docs/models/responsesoutputmessagerole.md @@ -0,0 +1,8 @@ +# ResponsesOutputMessageRole + + +## Values + +| Name | Value | +| ----------- | ----------- | +| `ASSISTANT` | assistant | \ No newline at end of file diff --git a/docs/models/responsesoutputmessagestatuscompleted.md b/docs/models/responsesoutputmessagestatuscompleted.md new file mode 100644 index 0000000..250c917 --- /dev/null +++ b/docs/models/responsesoutputmessagestatuscompleted.md @@ -0,0 +1,8 @@ +# ResponsesOutputMessageStatusCompleted + + +## Values + +| Name | Value | +| ----------- | ----------- | +| `COMPLETED` | completed | \ No newline at end of file diff --git a/docs/models/responsesoutputmessagestatusincomplete.md b/docs/models/responsesoutputmessagestatusincomplete.md new file mode 100644 index 0000000..bae111f --- /dev/null +++ b/docs/models/responsesoutputmessagestatusincomplete.md @@ -0,0 +1,8 @@ +# ResponsesOutputMessageStatusIncomplete + + +## Values + +| Name | Value | +| ------------ | ------------ | +| `INCOMPLETE` | incomplete | \ No newline at end of file diff --git a/docs/models/responsesoutputmessagestatusinprogress.md b/docs/models/responsesoutputmessagestatusinprogress.md new file mode 100644 index 0000000..03fbb24 --- /dev/null +++ b/docs/models/responsesoutputmessagestatusinprogress.md @@ -0,0 +1,8 @@ +# ResponsesOutputMessageStatusInProgress + + +## Values + +| Name | Value | +| ------------- | ------------- | +| `IN_PROGRESS` | in_progress | \ No newline at end of file diff --git a/docs/models/responsesoutputmessagestatusunion.md b/docs/models/responsesoutputmessagestatusunion.md new file mode 100644 index 0000000..44f0690 --- /dev/null +++ b/docs/models/responsesoutputmessagestatusunion.md @@ -0,0 +1,23 @@ +# ResponsesOutputMessageStatusUnion + + +## Supported Types + +### `models.ResponsesOutputMessageStatusCompleted` + +```python +value: models.ResponsesOutputMessageStatusCompleted = /* values here */ +``` + +### `models.ResponsesOutputMessageStatusIncomplete` + +```python +value: models.ResponsesOutputMessageStatusIncomplete = /* values here */ +``` + +### `models.ResponsesOutputMessageStatusInProgress` + +```python +value: models.ResponsesOutputMessageStatusInProgress = /* values here */ +``` + diff --git a/docs/models/responsesoutputmessagetype.md b/docs/models/responsesoutputmessagetype.md new file mode 100644 index 0000000..8648193 --- /dev/null +++ b/docs/models/responsesoutputmessagetype.md @@ -0,0 +1,8 @@ +# ResponsesOutputMessageType + + +## Values + +| Name | Value | +| --------- | --------- | +| `MESSAGE` | message | \ No newline at end of file diff --git a/docs/models/responsessearchcontextsize.md b/docs/models/responsessearchcontextsize.md new file mode 100644 index 0000000..4f0bc02 --- /dev/null +++ b/docs/models/responsessearchcontextsize.md @@ -0,0 +1,12 @@ +# ResponsesSearchContextSize + +Size of the search context for web search tools + + +## Values + +| Name | Value | +| -------- | -------- | +| `LOW` | low | +| `MEDIUM` | medium | +| `HIGH` | high | \ No newline at end of file diff --git a/docs/models/responseswebsearchcalloutput.md b/docs/models/responseswebsearchcalloutput.md new file mode 100644 index 0000000..31b7fad --- /dev/null +++ b/docs/models/responseswebsearchcalloutput.md @@ -0,0 +1,10 @@ +# ResponsesWebSearchCallOutput + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | +| `type` | [models.ResponsesWebSearchCallOutputType](../models/responseswebsearchcalloutputtype.md) | :heavy_check_mark: | N/A | | +| `id` | *str* | :heavy_check_mark: | N/A | | +| `status` | [models.WebSearchStatus](../models/websearchstatus.md) | :heavy_check_mark: | N/A | completed | \ No newline at end of file diff --git a/docs/models/responseswebsearchcalloutputtype.md b/docs/models/responseswebsearchcalloutputtype.md new file mode 100644 index 0000000..faaec22 --- /dev/null +++ b/docs/models/responseswebsearchcalloutputtype.md @@ -0,0 +1,8 @@ +# ResponsesWebSearchCallOutputType + + +## Values + +| Name | Value | +| ----------------- | ----------------- | +| `WEB_SEARCH_CALL` | web_search_call | \ No newline at end of file diff --git a/docs/models/responseswebsearchuserlocation.md b/docs/models/responseswebsearchuserlocation.md new file mode 100644 index 0000000..f0915c5 --- /dev/null +++ b/docs/models/responseswebsearchuserlocation.md @@ -0,0 +1,14 @@ +# ResponsesWebSearchUserLocation + +User location information for web search + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | +| `type` | [Optional[models.ResponsesWebSearchUserLocationType]](../models/responseswebsearchuserlocationtype.md) | :heavy_minus_sign: | N/A | +| `city` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | +| `country` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | +| `region` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | +| `timezone` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/responseswebsearchuserlocationtype.md b/docs/models/responseswebsearchuserlocationtype.md new file mode 100644 index 0000000..cb35c6a --- /dev/null +++ b/docs/models/responseswebsearchuserlocationtype.md @@ -0,0 +1,8 @@ +# ResponsesWebSearchUserLocationType + + +## Values + +| Name | Value | +| ------------- | ------------- | +| `APPROXIMATE` | approximate | \ No newline at end of file diff --git a/docs/models/responsetextconfig.md b/docs/models/responsetextconfig.md new file mode 100644 index 0000000..3150dde --- /dev/null +++ b/docs/models/responsetextconfig.md @@ -0,0 +1,11 @@ +# ResponseTextConfig + +Text output configuration including format and verbosity + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | +| `format_` | [Optional[models.ResponseFormatTextConfig]](../models/responseformattextconfig.md) | :heavy_minus_sign: | Text response format configuration | {
"type": "text"
} | +| `verbosity` | [OptionalNullable[models.ResponseTextConfigVerbosity]](../models/responsetextconfigverbosity.md) | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/docs/models/responsetextconfigverbosity.md b/docs/models/responsetextconfigverbosity.md new file mode 100644 index 0000000..073cb07 --- /dev/null +++ b/docs/models/responsetextconfigverbosity.md @@ -0,0 +1,10 @@ +# ResponseTextConfigVerbosity + + +## Values + +| Name | Value | +| -------- | -------- | +| `HIGH` | high | +| `LOW` | low | +| `MEDIUM` | medium | \ No newline at end of file diff --git a/docs/models/security.md b/docs/models/security.md new file mode 100644 index 0000000..2e0839d --- /dev/null +++ b/docs/models/security.md @@ -0,0 +1,8 @@ +# Security + + +## Fields + +| Field | Type | Required | Description | +| ------------------ | ------------------ | ------------------ | ------------------ | +| `api_key` | *Optional[str]* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/sendchatcompletionrequestresponse.md b/docs/models/sendchatcompletionrequestresponse.md new file mode 100644 index 0000000..03af74a --- /dev/null +++ b/docs/models/sendchatcompletionrequestresponse.md @@ -0,0 +1,17 @@ +# SendChatCompletionRequestResponse + + +## Supported Types + +### `models.ChatResponse` + +```python +value: models.ChatResponse = /* values here */ +``` + +### `Union[eventstreaming.EventStream[models.ChatStreamingResponseChunk], eventstreaming.EventStreamAsync[models.ChatStreamingResponseChunk]]` + +```python +value: Union[eventstreaming.EventStream[models.ChatStreamingResponseChunk], eventstreaming.EventStreamAsync[models.ChatStreamingResponseChunk]] = /* values here */ +``` + diff --git a/docs/models/servicetier.md b/docs/models/servicetier.md new file mode 100644 index 0000000..3a7a020 --- /dev/null +++ b/docs/models/servicetier.md @@ -0,0 +1,12 @@ +# ServiceTier + + +## Values + +| Name | Value | +| ---------- | ---------- | +| `AUTO` | auto | +| `DEFAULT` | default | +| `FLEX` | flex | +| `PRIORITY` | priority | +| `SCALE` | scale | \ No newline at end of file diff --git a/docs/models/serviceunavailableresponseerrordata.md b/docs/models/serviceunavailableresponseerrordata.md new file mode 100644 index 0000000..797c831 --- /dev/null +++ b/docs/models/serviceunavailableresponseerrordata.md @@ -0,0 +1,12 @@ +# ServiceUnavailableResponseErrorData + +Error data for ServiceUnavailableResponse + + +## Fields + +| Field | Type | Required | Description | +| -------------------------- | -------------------------- | -------------------------- | -------------------------- | +| `code` | *int* | :heavy_check_mark: | N/A | +| `message` | *str* | :heavy_check_mark: | N/A | +| `metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/sort.md b/docs/models/sort.md new file mode 100644 index 0000000..65b6edb --- /dev/null +++ b/docs/models/sort.md @@ -0,0 +1,12 @@ +# Sort + +The sorting strategy to use for this request, if "order" is not specified. When set, no load balancing is performed. + + +## Values + +| Name | Value | +| ------------ | ------------ | +| `PRICE` | price | +| `THROUGHPUT` | throughput | +| `LATENCY` | latency | \ No newline at end of file diff --git a/docs/models/streamoptions.md b/docs/models/streamoptions.md new file mode 100644 index 0000000..a2e5702 --- /dev/null +++ b/docs/models/streamoptions.md @@ -0,0 +1,8 @@ +# StreamOptions + + +## Fields + +| Field | Type | Required | Description | +| ------------------------ | ------------------------ | ------------------------ | ------------------------ | +| `include_usage` | *OptionalNullable[bool]* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/supportedparameter.md b/docs/models/supportedparameter.md new file mode 100644 index 0000000..4d18fd1 --- /dev/null +++ b/docs/models/supportedparameter.md @@ -0,0 +1,30 @@ +# SupportedParameter + + +## Values + +| Name | Value | +| --------------------- | --------------------- | +| `TEMPERATURE` | temperature | +| `TOP_P` | top_p | +| `TOP_K` | top_k | +| `MIN_P` | min_p | +| `TOP_A` | top_a | +| `FREQUENCY_PENALTY` | frequency_penalty | +| `PRESENCE_PENALTY` | presence_penalty | +| `REPETITION_PENALTY` | repetition_penalty | +| `MAX_TOKENS` | max_tokens | +| `LOGIT_BIAS` | logit_bias | +| `LOGPROBS` | logprobs | +| `TOP_LOGPROBS` | top_logprobs | +| `SEED` | seed | +| `RESPONSE_FORMAT` | response_format | +| `STRUCTURED_OUTPUTS` | structured_outputs | +| `STOP` | stop | +| `TOOLS` | tools | +| `TOOL_CHOICE` | tool_choice | +| `PARALLEL_TOOL_CALLS` | parallel_tool_calls | +| `INCLUDE_REASONING` | include_reasoning | +| `REASONING` | reasoning | +| `WEB_SEARCH_OPTIONS` | web_search_options | +| `VERBOSITY` | verbosity | \ No newline at end of file diff --git a/docs/models/systemmessage.md b/docs/models/systemmessage.md new file mode 100644 index 0000000..3458a7a --- /dev/null +++ b/docs/models/systemmessage.md @@ -0,0 +1,10 @@ +# SystemMessage + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------- | +| `role` | *Literal["system"]* | :heavy_check_mark: | N/A | +| `content` | [models.SystemMessageContent](../models/systemmessagecontent.md) | :heavy_check_mark: | N/A | +| `name` | *Optional[str]* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/systemmessagecontent.md b/docs/models/systemmessagecontent.md new file mode 100644 index 0000000..8993660 --- /dev/null +++ b/docs/models/systemmessagecontent.md @@ -0,0 +1,17 @@ +# SystemMessageContent + + +## Supported Types + +### `str` + +```python +value: str = /* values here */ +``` + +### `List[models.ChatMessageContentItemText]` + +```python +value: List[models.ChatMessageContentItemText] = /* values here */ +``` + diff --git a/docs/models/tokenizer.md b/docs/models/tokenizer.md new file mode 100644 index 0000000..375af17 --- /dev/null +++ b/docs/models/tokenizer.md @@ -0,0 +1,28 @@ +# Tokenizer + +Tokenizer type used by the model + + +## Values + +| Name | Value | +| ----------- | ----------- | +| `ROUTER` | Router | +| `MEDIA` | Media | +| `OTHER` | Other | +| `GPT` | GPT | +| `CLAUDE` | Claude | +| `GEMINI` | Gemini | +| `GROK` | Grok | +| `COHERE` | Cohere | +| `NOVA` | Nova | +| `QWEN` | Qwen | +| `YI` | Yi | +| `DEEP_SEEK` | DeepSeek | +| `MISTRAL` | Mistral | +| `LLAMA2` | Llama2 | +| `LLAMA3` | Llama3 | +| `LLAMA4` | Llama4 | +| `PA_LM` | PaLM | +| `RWKV` | RWKV | +| `QWEN3` | Qwen3 | \ No newline at end of file diff --git a/docs/models/toolcallstatus.md b/docs/models/toolcallstatus.md new file mode 100644 index 0000000..e3aadb1 --- /dev/null +++ b/docs/models/toolcallstatus.md @@ -0,0 +1,10 @@ +# ToolCallStatus + + +## Values + +| Name | Value | +| ------------- | ------------- | +| `IN_PROGRESS` | in_progress | +| `COMPLETED` | completed | +| `INCOMPLETE` | incomplete | \ No newline at end of file diff --git a/docs/models/tooldefinitionjson.md b/docs/models/tooldefinitionjson.md new file mode 100644 index 0000000..efa9fd0 --- /dev/null +++ b/docs/models/tooldefinitionjson.md @@ -0,0 +1,9 @@ +# ToolDefinitionJSON + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | +| `type` | *Literal["function"]* | :heavy_check_mark: | N/A | +| `function` | [models.ToolDefinitionJSONFunction](../models/tooldefinitionjsonfunction.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/tooldefinitionjsonfunction.md b/docs/models/tooldefinitionjsonfunction.md new file mode 100644 index 0000000..4ae1dcc --- /dev/null +++ b/docs/models/tooldefinitionjsonfunction.md @@ -0,0 +1,11 @@ +# ToolDefinitionJSONFunction + + +## Fields + +| Field | Type | Required | Description | +| ------------------------ | ------------------------ | ------------------------ | ------------------------ | +| `name` | *str* | :heavy_check_mark: | N/A | +| `description` | *Optional[str]* | :heavy_minus_sign: | N/A | +| `parameters` | Dict[str, *Any*] | :heavy_minus_sign: | N/A | +| `strict` | *OptionalNullable[bool]* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/toolresponsemessage.md b/docs/models/toolresponsemessage.md new file mode 100644 index 0000000..9ff5454 --- /dev/null +++ b/docs/models/toolresponsemessage.md @@ -0,0 +1,10 @@ +# ToolResponseMessage + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | +| `role` | *Literal["tool"]* | :heavy_check_mark: | N/A | +| `content` | [models.ToolResponseMessageContent](../models/toolresponsemessagecontent.md) | :heavy_check_mark: | N/A | +| `tool_call_id` | *str* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/toolresponsemessagecontent.md b/docs/models/toolresponsemessagecontent.md new file mode 100644 index 0000000..a542003 --- /dev/null +++ b/docs/models/toolresponsemessagecontent.md @@ -0,0 +1,17 @@ +# ToolResponseMessageContent + + +## Supported Types + +### `str` + +```python +value: str = /* values here */ +``` + +### `List[models.ChatMessageContentItem]` + +```python +value: List[models.ChatMessageContentItem] = /* values here */ +``` + diff --git a/docs/models/toomanyrequestsresponseerrordata.md b/docs/models/toomanyrequestsresponseerrordata.md new file mode 100644 index 0000000..a957677 --- /dev/null +++ b/docs/models/toomanyrequestsresponseerrordata.md @@ -0,0 +1,12 @@ +# TooManyRequestsResponseErrorData + +Error data for TooManyRequestsResponse + + +## Fields + +| Field | Type | Required | Description | +| -------------------------- | -------------------------- | -------------------------- | -------------------------- | +| `code` | *int* | :heavy_check_mark: | N/A | +| `message` | *str* | :heavy_check_mark: | N/A | +| `metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/toplogprob.md b/docs/models/toplogprob.md new file mode 100644 index 0000000..a3eddcf --- /dev/null +++ b/docs/models/toplogprob.md @@ -0,0 +1,10 @@ +# TopLogprob + + +## Fields + +| Field | Type | Required | Description | +| ------------------ | ------------------ | ------------------ | ------------------ | +| `token` | *str* | :heavy_check_mark: | N/A | +| `logprob` | *float* | :heavy_check_mark: | N/A | +| `bytes_` | List[*float*] | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/topproviderinfo.md b/docs/models/topproviderinfo.md new file mode 100644 index 0000000..1353919 --- /dev/null +++ b/docs/models/topproviderinfo.md @@ -0,0 +1,12 @@ +# TopProviderInfo + +Information about the top provider for this model + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------- | ----------------------------------------------- | ----------------------------------------------- | ----------------------------------------------- | ----------------------------------------------- | +| `context_length` | *OptionalNullable[float]* | :heavy_minus_sign: | Context length from the top provider | 8192 | +| `max_completion_tokens` | *OptionalNullable[float]* | :heavy_minus_sign: | Maximum completion tokens from the top provider | 4096 | +| `is_moderated` | *bool* | :heavy_check_mark: | Whether the top provider moderates content | true | \ No newline at end of file diff --git a/docs/models/transferintent.md b/docs/models/transferintent.md new file mode 100644 index 0000000..c86f0f6 --- /dev/null +++ b/docs/models/transferintent.md @@ -0,0 +1,9 @@ +# TransferIntent + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | +| `call_data` | [models.CallData](../models/calldata.md) | :heavy_check_mark: | N/A | +| `metadata` | [models.Metadata](../models/metadata.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/truncation.md b/docs/models/truncation.md new file mode 100644 index 0000000..5a04bd9 --- /dev/null +++ b/docs/models/truncation.md @@ -0,0 +1,9 @@ +# Truncation + + +## Values + +| Name | Value | +| ---------- | ---------- | +| `AUTO` | auto | +| `DISABLED` | disabled | \ No newline at end of file diff --git a/docs/models/type.md b/docs/models/type.md new file mode 100644 index 0000000..a4acdd9 --- /dev/null +++ b/docs/models/type.md @@ -0,0 +1,17 @@ +# Type + + +## Supported Types + +### `models.OpenAIResponsesToolChoiceTypeWebSearchPreview20250311` + +```python +value: models.OpenAIResponsesToolChoiceTypeWebSearchPreview20250311 = /* values here */ +``` + +### `models.OpenAIResponsesToolChoiceTypeWebSearchPreview` + +```python +value: models.OpenAIResponsesToolChoiceTypeWebSearchPreview = /* values here */ +``` + diff --git a/docs/models/typeresponsecompleted.md b/docs/models/typeresponsecompleted.md new file mode 100644 index 0000000..77875c6 --- /dev/null +++ b/docs/models/typeresponsecompleted.md @@ -0,0 +1,8 @@ +# TypeResponseCompleted + + +## Values + +| Name | Value | +| -------------------- | -------------------- | +| `RESPONSE_COMPLETED` | response.completed | \ No newline at end of file diff --git a/docs/models/typeresponsecontentpartadded.md b/docs/models/typeresponsecontentpartadded.md new file mode 100644 index 0000000..c31cd18 --- /dev/null +++ b/docs/models/typeresponsecontentpartadded.md @@ -0,0 +1,8 @@ +# TypeResponseContentPartAdded + + +## Values + +| Name | Value | +| ----------------------------- | ----------------------------- | +| `RESPONSE_CONTENT_PART_ADDED` | response.content_part.added | \ No newline at end of file diff --git a/docs/models/typeresponsecontentpartdone.md b/docs/models/typeresponsecontentpartdone.md new file mode 100644 index 0000000..0f98a39 --- /dev/null +++ b/docs/models/typeresponsecontentpartdone.md @@ -0,0 +1,8 @@ +# TypeResponseContentPartDone + + +## Values + +| Name | Value | +| ---------------------------- | ---------------------------- | +| `RESPONSE_CONTENT_PART_DONE` | response.content_part.done | \ No newline at end of file diff --git a/docs/models/typeresponsecreated.md b/docs/models/typeresponsecreated.md new file mode 100644 index 0000000..364b68b --- /dev/null +++ b/docs/models/typeresponsecreated.md @@ -0,0 +1,8 @@ +# TypeResponseCreated + + +## Values + +| Name | Value | +| ------------------ | ------------------ | +| `RESPONSE_CREATED` | response.created | \ No newline at end of file diff --git a/docs/models/typeresponsefailed.md b/docs/models/typeresponsefailed.md new file mode 100644 index 0000000..6ce2836 --- /dev/null +++ b/docs/models/typeresponsefailed.md @@ -0,0 +1,8 @@ +# TypeResponseFailed + + +## Values + +| Name | Value | +| ----------------- | ----------------- | +| `RESPONSE_FAILED` | response.failed | \ No newline at end of file diff --git a/docs/models/typeresponsefunctioncallargumentsdelta.md b/docs/models/typeresponsefunctioncallargumentsdelta.md new file mode 100644 index 0000000..c9708cc --- /dev/null +++ b/docs/models/typeresponsefunctioncallargumentsdelta.md @@ -0,0 +1,8 @@ +# TypeResponseFunctionCallArgumentsDelta + + +## Values + +| Name | Value | +| ---------------------------------------- | ---------------------------------------- | +| `RESPONSE_FUNCTION_CALL_ARGUMENTS_DELTA` | response.function_call_arguments.delta | \ No newline at end of file diff --git a/docs/models/typeresponsefunctioncallargumentsdone.md b/docs/models/typeresponsefunctioncallargumentsdone.md new file mode 100644 index 0000000..efb0b73 --- /dev/null +++ b/docs/models/typeresponsefunctioncallargumentsdone.md @@ -0,0 +1,8 @@ +# TypeResponseFunctionCallArgumentsDone + + +## Values + +| Name | Value | +| --------------------------------------- | --------------------------------------- | +| `RESPONSE_FUNCTION_CALL_ARGUMENTS_DONE` | response.function_call_arguments.done | \ No newline at end of file diff --git a/docs/models/typeresponseincomplete.md b/docs/models/typeresponseincomplete.md new file mode 100644 index 0000000..3fea878 --- /dev/null +++ b/docs/models/typeresponseincomplete.md @@ -0,0 +1,8 @@ +# TypeResponseIncomplete + + +## Values + +| Name | Value | +| --------------------- | --------------------- | +| `RESPONSE_INCOMPLETE` | response.incomplete | \ No newline at end of file diff --git a/docs/models/typeresponseinprogress.md b/docs/models/typeresponseinprogress.md new file mode 100644 index 0000000..6f2328e --- /dev/null +++ b/docs/models/typeresponseinprogress.md @@ -0,0 +1,8 @@ +# TypeResponseInProgress + + +## Values + +| Name | Value | +| ---------------------- | ---------------------- | +| `RESPONSE_IN_PROGRESS` | response.in_progress | \ No newline at end of file diff --git a/docs/models/typeresponseoutputitemadded.md b/docs/models/typeresponseoutputitemadded.md new file mode 100644 index 0000000..b29c71e --- /dev/null +++ b/docs/models/typeresponseoutputitemadded.md @@ -0,0 +1,8 @@ +# TypeResponseOutputItemAdded + + +## Values + +| Name | Value | +| ---------------------------- | ---------------------------- | +| `RESPONSE_OUTPUT_ITEM_ADDED` | response.output_item.added | \ No newline at end of file diff --git a/docs/models/typeresponseoutputitemdone.md b/docs/models/typeresponseoutputitemdone.md new file mode 100644 index 0000000..4c6f4a6 --- /dev/null +++ b/docs/models/typeresponseoutputitemdone.md @@ -0,0 +1,8 @@ +# TypeResponseOutputItemDone + + +## Values + +| Name | Value | +| --------------------------- | --------------------------- | +| `RESPONSE_OUTPUT_ITEM_DONE` | response.output_item.done | \ No newline at end of file diff --git a/docs/models/typeresponseoutputtextannotationadded.md b/docs/models/typeresponseoutputtextannotationadded.md new file mode 100644 index 0000000..d2319a5 --- /dev/null +++ b/docs/models/typeresponseoutputtextannotationadded.md @@ -0,0 +1,8 @@ +# TypeResponseOutputTextAnnotationAdded + + +## Values + +| Name | Value | +| --------------------------------------- | --------------------------------------- | +| `RESPONSE_OUTPUT_TEXT_ANNOTATION_ADDED` | response.output_text.annotation.added | \ No newline at end of file diff --git a/docs/models/typeresponseoutputtextdelta.md b/docs/models/typeresponseoutputtextdelta.md new file mode 100644 index 0000000..e6381fd --- /dev/null +++ b/docs/models/typeresponseoutputtextdelta.md @@ -0,0 +1,8 @@ +# TypeResponseOutputTextDelta + + +## Values + +| Name | Value | +| ---------------------------- | ---------------------------- | +| `RESPONSE_OUTPUT_TEXT_DELTA` | response.output_text.delta | \ No newline at end of file diff --git a/docs/models/typeresponseoutputtextdone.md b/docs/models/typeresponseoutputtextdone.md new file mode 100644 index 0000000..2ccc4b5 --- /dev/null +++ b/docs/models/typeresponseoutputtextdone.md @@ -0,0 +1,8 @@ +# TypeResponseOutputTextDone + + +## Values + +| Name | Value | +| --------------------------- | --------------------------- | +| `RESPONSE_OUTPUT_TEXT_DONE` | response.output_text.done | \ No newline at end of file diff --git a/docs/models/typeresponsereasoningsummarypartdone.md b/docs/models/typeresponsereasoningsummarypartdone.md new file mode 100644 index 0000000..8951706 --- /dev/null +++ b/docs/models/typeresponsereasoningsummarypartdone.md @@ -0,0 +1,8 @@ +# TypeResponseReasoningSummaryPartDone + + +## Values + +| Name | Value | +| -------------------------------------- | -------------------------------------- | +| `RESPONSE_REASONING_SUMMARY_PART_DONE` | response.reasoning_summary_part.done | \ No newline at end of file diff --git a/docs/models/typeresponserefusaldelta.md b/docs/models/typeresponserefusaldelta.md new file mode 100644 index 0000000..9e5dadc --- /dev/null +++ b/docs/models/typeresponserefusaldelta.md @@ -0,0 +1,8 @@ +# TypeResponseRefusalDelta + + +## Values + +| Name | Value | +| ------------------------ | ------------------------ | +| `RESPONSE_REFUSAL_DELTA` | response.refusal.delta | \ No newline at end of file diff --git a/docs/models/typeresponserefusaldone.md b/docs/models/typeresponserefusaldone.md new file mode 100644 index 0000000..0124586 --- /dev/null +++ b/docs/models/typeresponserefusaldone.md @@ -0,0 +1,8 @@ +# TypeResponseRefusalDone + + +## Values + +| Name | Value | +| ----------------------- | ----------------------- | +| `RESPONSE_REFUSAL_DONE` | response.refusal.done | \ No newline at end of file diff --git a/docs/models/unauthorizedresponseerrordata.md b/docs/models/unauthorizedresponseerrordata.md new file mode 100644 index 0000000..1db2a3a --- /dev/null +++ b/docs/models/unauthorizedresponseerrordata.md @@ -0,0 +1,12 @@ +# UnauthorizedResponseErrorData + +Error data for UnauthorizedResponse + + +## Fields + +| Field | Type | Required | Description | +| -------------------------- | -------------------------- | -------------------------- | -------------------------- | +| `code` | *int* | :heavy_check_mark: | N/A | +| `message` | *str* | :heavy_check_mark: | N/A | +| `metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/unprocessableentityresponseerrordata.md b/docs/models/unprocessableentityresponseerrordata.md new file mode 100644 index 0000000..9ccd3c0 --- /dev/null +++ b/docs/models/unprocessableentityresponseerrordata.md @@ -0,0 +1,12 @@ +# UnprocessableEntityResponseErrorData + +Error data for UnprocessableEntityResponse + + +## Fields + +| Field | Type | Required | Description | +| -------------------------- | -------------------------- | -------------------------- | -------------------------- | +| `code` | *int* | :heavy_check_mark: | N/A | +| `message` | *str* | :heavy_check_mark: | N/A | +| `metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/updatekeysdata.md b/docs/models/updatekeysdata.md new file mode 100644 index 0000000..90fd068 --- /dev/null +++ b/docs/models/updatekeysdata.md @@ -0,0 +1,28 @@ +# UpdateKeysData + +The updated API key information + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | +| `hash` | *str* | :heavy_check_mark: | Unique hash identifier for the API key | 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 | +| `name` | *str* | :heavy_check_mark: | Name of the API key | My Production Key | +| `label` | *str* | :heavy_check_mark: | Human-readable label for the API key | Production API Key | +| `disabled` | *bool* | :heavy_check_mark: | Whether the API key is disabled | false | +| `limit` | *Nullable[float]* | :heavy_check_mark: | Spending limit for the API key in USD | 100 | +| `limit_remaining` | *Nullable[float]* | :heavy_check_mark: | Remaining spending limit in USD | 74.5 | +| `limit_reset` | *Nullable[str]* | :heavy_check_mark: | Type of limit reset for the API key | monthly | +| `include_byok_in_limit` | *bool* | :heavy_check_mark: | Whether to include external BYOK usage in the credit limit | false | +| `usage` | *float* | :heavy_check_mark: | Total OpenRouter credit usage (in USD) for the API key | 25.5 | +| `usage_daily` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC day | 25.5 | +| `usage_weekly` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday) | 25.5 | +| `usage_monthly` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC month | 25.5 | +| `byok_usage` | *float* | :heavy_check_mark: | Total external BYOK usage (in USD) for the API key | 17.38 | +| `byok_usage_daily` | *float* | :heavy_check_mark: | External BYOK usage (in USD) for the current UTC day | 17.38 | +| `byok_usage_weekly` | *float* | :heavy_check_mark: | External BYOK usage (in USD) for the current UTC week (Monday-Sunday) | 17.38 | +| `byok_usage_monthly` | *float* | :heavy_check_mark: | External BYOK usage (in USD) for current UTC month | 17.38 | +| `created_at` | *str* | :heavy_check_mark: | ISO 8601 timestamp of when the API key was created | 2025-08-24T10:30:00Z | +| `updated_at` | *Nullable[str]* | :heavy_check_mark: | ISO 8601 timestamp of when the API key was last updated | 2025-08-24T15:45:00Z | +| `expires_at` | [date](https://docs.python.org/3/library/datetime.html#date-objects) | :heavy_minus_sign: | ISO 8601 UTC timestamp when the API key expires, or null if no expiration | 2027-12-31T23:59:59Z | \ No newline at end of file diff --git a/docs/models/updatekeyslimitreset.md b/docs/models/updatekeyslimitreset.md new file mode 100644 index 0000000..7a91c14 --- /dev/null +++ b/docs/models/updatekeyslimitreset.md @@ -0,0 +1,12 @@ +# UpdateKeysLimitReset + +New limit reset type for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday. + + +## Values + +| Name | Value | +| --------- | --------- | +| `DAILY` | daily | +| `WEEKLY` | weekly | +| `MONTHLY` | monthly | \ No newline at end of file diff --git a/docs/models/updatekeysrequest.md b/docs/models/updatekeysrequest.md new file mode 100644 index 0000000..f5a70ce --- /dev/null +++ b/docs/models/updatekeysrequest.md @@ -0,0 +1,9 @@ +# UpdateKeysRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | +| `hash` | *str* | :heavy_check_mark: | The hash identifier of the API key to update | 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 | +| `body` | [models.UpdateKeysRequestBody](../models/updatekeysrequestbody.md) | :heavy_check_mark: | N/A | {
"name": "Updated API Key Name",
"disabled": false,
"limit": 75,
"limit_reset": "daily",
"include_byok_in_limit": true
} | \ No newline at end of file diff --git a/docs/models/updatekeysrequestbody.md b/docs/models/updatekeysrequestbody.md new file mode 100644 index 0000000..f9c96f3 --- /dev/null +++ b/docs/models/updatekeysrequestbody.md @@ -0,0 +1,12 @@ +# UpdateKeysRequestBody + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `name` | *Optional[str]* | :heavy_minus_sign: | New name for the API key | Updated API Key Name | +| `disabled` | *Optional[bool]* | :heavy_minus_sign: | Whether to disable the API key | false | +| `limit` | *OptionalNullable[float]* | :heavy_minus_sign: | New spending limit for the API key in USD | 75 | +| `limit_reset` | [OptionalNullable[models.UpdateKeysLimitReset]](../models/updatekeyslimitreset.md) | :heavy_minus_sign: | New limit reset type for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday. | daily | +| `include_byok_in_limit` | *Optional[bool]* | :heavy_minus_sign: | Whether to include BYOK usage in the limit | true | \ No newline at end of file diff --git a/docs/models/updatekeysresponse.md b/docs/models/updatekeysresponse.md new file mode 100644 index 0000000..6f2432f --- /dev/null +++ b/docs/models/updatekeysresponse.md @@ -0,0 +1,10 @@ +# UpdateKeysResponse + +API key updated successfully + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `data` | [models.UpdateKeysData](../models/updatekeysdata.md) | :heavy_check_mark: | The updated API key information | {
"hash": "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",
"name": "My Production Key",
"label": "Production API Key",
"disabled": false,
"limit": 100,
"limit_remaining": 74.5,
"limit_reset": "monthly",
"include_byok_in_limit": false,
"usage": 25.5,
"usage_daily": 25.5,
"usage_weekly": 25.5,
"usage_monthly": 25.5,
"byok_usage": 17.38,
"byok_usage_daily": 17.38,
"byok_usage_weekly": 17.38,
"byok_usage_monthly": 17.38,
"created_at": "2025-08-24T10:30:00Z",
"updated_at": "2025-08-24T15:45:00Z",
"expires_at": "2027-12-31T23:59:59Z"
} | \ No newline at end of file diff --git a/docs/models/urlcitation.md b/docs/models/urlcitation.md new file mode 100644 index 0000000..59cdcf6 --- /dev/null +++ b/docs/models/urlcitation.md @@ -0,0 +1,12 @@ +# URLCitation + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------ | ------------------------------------------------------ | ------------------------------------------------------ | ------------------------------------------------------ | +| `type` | [models.URLCitationType](../models/urlcitationtype.md) | :heavy_check_mark: | N/A | +| `url` | *str* | :heavy_check_mark: | N/A | +| `title` | *str* | :heavy_check_mark: | N/A | +| `start_index` | *float* | :heavy_check_mark: | N/A | +| `end_index` | *float* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/urlcitationtype.md b/docs/models/urlcitationtype.md new file mode 100644 index 0000000..2b6e38f --- /dev/null +++ b/docs/models/urlcitationtype.md @@ -0,0 +1,8 @@ +# URLCitationType + + +## Values + +| Name | Value | +| -------------- | -------------- | +| `URL_CITATION` | url_citation | \ No newline at end of file diff --git a/docs/models/usage.md b/docs/models/usage.md new file mode 100644 index 0000000..90e9361 --- /dev/null +++ b/docs/models/usage.md @@ -0,0 +1,10 @@ +# Usage + + +## Fields + +| Field | Type | Required | Description | +| ------------------ | ------------------ | ------------------ | ------------------ | +| `prompt_tokens` | *float* | :heavy_check_mark: | N/A | +| `total_tokens` | *float* | :heavy_check_mark: | N/A | +| `cost` | *Optional[float]* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/usermessage.md b/docs/models/usermessage.md new file mode 100644 index 0000000..c2db475 --- /dev/null +++ b/docs/models/usermessage.md @@ -0,0 +1,10 @@ +# UserMessage + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | +| `role` | *Literal["user"]* | :heavy_check_mark: | N/A | +| `content` | [models.UserMessageContent](../models/usermessagecontent.md) | :heavy_check_mark: | N/A | +| `name` | *Optional[str]* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/usermessagecontent.md b/docs/models/usermessagecontent.md new file mode 100644 index 0000000..3542905 --- /dev/null +++ b/docs/models/usermessagecontent.md @@ -0,0 +1,17 @@ +# UserMessageContent + + +## Supported Types + +### `str` + +```python +value: str = /* values here */ +``` + +### `List[models.ChatMessageContentItem]` + +```python +value: List[models.ChatMessageContentItem] = /* values here */ +``` + diff --git a/docs/models/utils/retryconfig.md b/docs/models/utils/retryconfig.md new file mode 100644 index 0000000..69dd549 --- /dev/null +++ b/docs/models/utils/retryconfig.md @@ -0,0 +1,24 @@ +# RetryConfig + +Allows customizing the default retry configuration. Only usable with methods that mention they support retries. + +## Fields + +| Name | Type | Description | Example | +| ------------------------- | ----------------------------------- | --------------------------------------- | --------- | +| `strategy` | `*str*` | The retry strategy to use. | `backoff` | +| `backoff` | [BackoffStrategy](#backoffstrategy) | Configuration for the backoff strategy. | | +| `retry_connection_errors` | `*bool*` | Whether to retry on connection errors. | `true` | + +## BackoffStrategy + +The backoff strategy allows retrying a request with an exponential backoff between each retry. + +### Fields + +| Name | Type | Description | Example | +| ------------------ | --------- | ----------------------------------------- | -------- | +| `initial_interval` | `*int*` | The initial interval in milliseconds. | `500` | +| `max_interval` | `*int*` | The maximum interval in milliseconds. | `60000` | +| `exponent` | `*float*` | The exponent to use for the backoff. | `1.5` | +| `max_elapsed_time` | `*int*` | The maximum elapsed time in milliseconds. | `300000` | \ No newline at end of file diff --git a/docs/models/variables.md b/docs/models/variables.md new file mode 100644 index 0000000..1682dbd --- /dev/null +++ b/docs/models/variables.md @@ -0,0 +1,29 @@ +# Variables + + +## Supported Types + +### `str` + +```python +value: str = /* values here */ +``` + +### `models.ResponseInputText` + +```python +value: models.ResponseInputText = /* values here */ +``` + +### `models.ResponseInputImage` + +```python +value: models.ResponseInputImage = /* values here */ +``` + +### `models.ResponseInputFile` + +```python +value: models.ResponseInputFile = /* values here */ +``` + diff --git a/docs/models/videourl.md b/docs/models/videourl.md new file mode 100644 index 0000000..5bd5dec --- /dev/null +++ b/docs/models/videourl.md @@ -0,0 +1,8 @@ +# VideoURL + + +## Fields + +| Field | Type | Required | Description | +| ------------------ | ------------------ | ------------------ | ------------------ | +| `url` | *str* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/web3data.md b/docs/models/web3data.md new file mode 100644 index 0000000..f74dee3 --- /dev/null +++ b/docs/models/web3data.md @@ -0,0 +1,8 @@ +# Web3Data + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------- | ---------------------------------------------------- | ---------------------------------------------------- | ---------------------------------------------------- | +| `transfer_intent` | [models.TransferIntent](../models/transferintent.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/websearchpreviewtooluserlocation.md b/docs/models/websearchpreviewtooluserlocation.md new file mode 100644 index 0000000..9dc52fd --- /dev/null +++ b/docs/models/websearchpreviewtooluserlocation.md @@ -0,0 +1,12 @@ +# WebSearchPreviewToolUserLocation + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | +| `type` | [models.WebSearchPreviewToolUserLocationType](../models/websearchpreviewtooluserlocationtype.md) | :heavy_check_mark: | N/A | +| `city` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | +| `country` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | +| `region` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | +| `timezone` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/websearchpreviewtooluserlocationtype.md b/docs/models/websearchpreviewtooluserlocationtype.md new file mode 100644 index 0000000..505e5ea --- /dev/null +++ b/docs/models/websearchpreviewtooluserlocationtype.md @@ -0,0 +1,8 @@ +# WebSearchPreviewToolUserLocationType + + +## Values + +| Name | Value | +| ------------- | ------------- | +| `APPROXIMATE` | approximate | \ No newline at end of file diff --git a/docs/models/websearchstatus.md b/docs/models/websearchstatus.md new file mode 100644 index 0000000..53303ec --- /dev/null +++ b/docs/models/websearchstatus.md @@ -0,0 +1,11 @@ +# WebSearchStatus + + +## Values + +| Name | Value | +| ------------- | ------------- | +| `COMPLETED` | completed | +| `SEARCHING` | searching | +| `IN_PROGRESS` | in_progress | +| `FAILED` | failed | \ No newline at end of file diff --git a/docs/sdks/analytics/README.md b/docs/sdks/analytics/README.md new file mode 100644 index 0000000..451a486 --- /dev/null +++ b/docs/sdks/analytics/README.md @@ -0,0 +1,54 @@ +# Analytics +(*analytics*) + +## Overview + +Analytics and usage endpoints + +### Available Operations + +* [get_user_activity](#get_user_activity) - Get user activity grouped by endpoint + +## get_user_activity + +Returns user activity data grouped by endpoint for the last 30 (completed) UTC days + +### Example Usage + + +```python +from openrouter import OpenRouter +import os + + +with OpenRouter( + api_key=os.getenv("OPENROUTER_API_KEY", ""), +) as open_router: + + res = open_router.analytics.get_user_activity(date_="2025-08-24") + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | Example | +| -------------------------------------------------------------------- | -------------------------------------------------------------------- | -------------------------------------------------------------------- | -------------------------------------------------------------------- | -------------------------------------------------------------------- | +| `date_` | *Optional[str]* | :heavy_minus_sign: | Filter by a single UTC date in the last 30 days (YYYY-MM-DD format). | 2025-08-24 | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | | + +### Response + +**[models.GetUserActivityResponse](../../models/getuseractivityresponse.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ---------------------------------- | ---------------------------------- | ---------------------------------- | +| errors.BadRequestResponseError | 400 | application/json | +| errors.UnauthorizedResponseError | 401 | application/json | +| errors.ForbiddenResponseError | 403 | application/json | +| errors.InternalServerResponseError | 500 | application/json | +| errors.OpenRouterDefaultError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/docs/sdks/apikeys/README.md b/docs/sdks/apikeys/README.md new file mode 100644 index 0000000..e860acf --- /dev/null +++ b/docs/sdks/apikeys/README.md @@ -0,0 +1,287 @@ +# APIKeys +(*api_keys*) + +## Overview + +API key management endpoints + +### Available Operations + +* [list](#list) - List API keys +* [create](#create) - Create a new API key +* [update](#update) - Update an API key +* [delete](#delete) - Delete an API key +* [get](#get) - Get a single API key +* [get_current_key_metadata](#get_current_key_metadata) - Get current API key + +## list + +List API keys + +### Example Usage + + +```python +from openrouter import OpenRouter +import os + + +with OpenRouter( + api_key=os.getenv("OPENROUTER_API_KEY", ""), +) as open_router: + + res = open_router.api_keys.list(include_disabled="false", offset="0") + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | Example | +| ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | +| `include_disabled` | *Optional[str]* | :heavy_minus_sign: | Whether to include disabled API keys in the response | false | +| `offset` | *Optional[str]* | :heavy_minus_sign: | Number of API keys to skip for pagination | 0 | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | | + +### Response + +**[models.ListResponse](../../models/listresponse.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------------------- | ----------------------------------- | ----------------------------------- | +| errors.UnauthorizedResponseError | 401 | application/json | +| errors.TooManyRequestsResponseError | 429 | application/json | +| errors.InternalServerResponseError | 500 | application/json | +| errors.OpenRouterDefaultError | 4XX, 5XX | \*/\* | + +## create + +Create a new API key + +### Example Usage + + +```python +from openrouter import OpenRouter +from openrouter.utils import parse_datetime +import os + + +with OpenRouter( + api_key=os.getenv("OPENROUTER_API_KEY", ""), +) as open_router: + + res = open_router.api_keys.create(name="My New API Key", limit=50, limit_reset="monthly", include_byok_in_limit=True, expires_at=parse_datetime("2027-12-31T23:59:59Z")) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | Example | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `name` | *str* | :heavy_check_mark: | Name for the new API key | My New API Key | +| `limit` | *OptionalNullable[float]* | :heavy_minus_sign: | Optional spending limit for the API key in USD | 50 | +| `limit_reset` | [OptionalNullable[models.CreateKeysLimitReset]](../../models/createkeyslimitreset.md) | :heavy_minus_sign: | Type of limit reset for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday. | monthly | +| `include_byok_in_limit` | *Optional[bool]* | :heavy_minus_sign: | Whether to include BYOK usage in the limit | true | +| `expires_at` | [date](https://docs.python.org/3/library/datetime.html#date-objects) | :heavy_minus_sign: | Optional ISO 8601 UTC timestamp when the API key should expire. Must be UTC, other timezones will be rejected | 2027-12-31T23:59:59Z | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | | + +### Response + +**[models.CreateKeysResponse](../../models/createkeysresponse.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------------------- | ----------------------------------- | ----------------------------------- | +| errors.BadRequestResponseError | 400 | application/json | +| errors.UnauthorizedResponseError | 401 | application/json | +| errors.TooManyRequestsResponseError | 429 | application/json | +| errors.InternalServerResponseError | 500 | application/json | +| errors.OpenRouterDefaultError | 4XX, 5XX | \*/\* | + +## update + +Update an API key + +### Example Usage + + +```python +from openrouter import OpenRouter +import os + + +with OpenRouter( + api_key=os.getenv("OPENROUTER_API_KEY", ""), +) as open_router: + + res = open_router.api_keys.update(hash="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", name="Updated API Key Name", disabled=False, limit=75, limit_reset="daily", include_byok_in_limit=True) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | Example | +| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `hash` | *str* | :heavy_check_mark: | The hash identifier of the API key to update | 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 | +| `name` | *Optional[str]* | :heavy_minus_sign: | New name for the API key | Updated API Key Name | +| `disabled` | *Optional[bool]* | :heavy_minus_sign: | Whether to disable the API key | false | +| `limit` | *OptionalNullable[float]* | :heavy_minus_sign: | New spending limit for the API key in USD | 75 | +| `limit_reset` | [OptionalNullable[models.UpdateKeysLimitReset]](../../models/updatekeyslimitreset.md) | :heavy_minus_sign: | New limit reset type for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday. | daily | +| `include_byok_in_limit` | *Optional[bool]* | :heavy_minus_sign: | Whether to include BYOK usage in the limit | true | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | | + +### Response + +**[models.UpdateKeysResponse](../../models/updatekeysresponse.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------------------- | ----------------------------------- | ----------------------------------- | +| errors.BadRequestResponseError | 400 | application/json | +| errors.UnauthorizedResponseError | 401 | application/json | +| errors.NotFoundResponseError | 404 | application/json | +| errors.TooManyRequestsResponseError | 429 | application/json | +| errors.InternalServerResponseError | 500 | application/json | +| errors.OpenRouterDefaultError | 4XX, 5XX | \*/\* | + +## delete + +Delete an API key + +### Example Usage + + +```python +from openrouter import OpenRouter +import os + + +with OpenRouter( + api_key=os.getenv("OPENROUTER_API_KEY", ""), +) as open_router: + + res = open_router.api_keys.delete(hash="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") + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | Example | +| ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | +| `hash` | *str* | :heavy_check_mark: | The hash identifier of the API key to delete | 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 | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | | + +### Response + +**[models.DeleteKeysResponse](../../models/deletekeysresponse.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------------------- | ----------------------------------- | ----------------------------------- | +| errors.UnauthorizedResponseError | 401 | application/json | +| errors.NotFoundResponseError | 404 | application/json | +| errors.TooManyRequestsResponseError | 429 | application/json | +| errors.InternalServerResponseError | 500 | application/json | +| errors.OpenRouterDefaultError | 4XX, 5XX | \*/\* | + +## get + +Get a single API key + +### Example Usage + + +```python +from openrouter import OpenRouter +import os + + +with OpenRouter( + api_key=os.getenv("OPENROUTER_API_KEY", ""), +) as open_router: + + res = open_router.api_keys.get(hash="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") + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | Example | +| ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | +| `hash` | *str* | :heavy_check_mark: | The hash identifier of the API key to retrieve | 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 | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | | + +### Response + +**[models.GetKeyResponse](../../models/getkeyresponse.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------------------- | ----------------------------------- | ----------------------------------- | +| errors.UnauthorizedResponseError | 401 | application/json | +| errors.NotFoundResponseError | 404 | application/json | +| errors.TooManyRequestsResponseError | 429 | application/json | +| errors.InternalServerResponseError | 500 | application/json | +| errors.OpenRouterDefaultError | 4XX, 5XX | \*/\* | + +## get_current_key_metadata + +Get information on the API key associated with the current authentication session + +### Example Usage + + +```python +from openrouter import OpenRouter +import os + + +with OpenRouter( + api_key=os.getenv("OPENROUTER_API_KEY", ""), +) as open_router: + + res = open_router.api_keys.get_current_key_metadata() + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[models.GetCurrentKeyResponse](../../models/getcurrentkeyresponse.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ---------------------------------- | ---------------------------------- | ---------------------------------- | +| errors.UnauthorizedResponseError | 401 | application/json | +| errors.InternalServerResponseError | 500 | application/json | +| errors.OpenRouterDefaultError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/docs/sdks/chat/README.md b/docs/sdks/chat/README.md new file mode 100644 index 0000000..d0cd562 --- /dev/null +++ b/docs/sdks/chat/README.md @@ -0,0 +1,73 @@ +# Chat +(*chat*) + +## Overview + +### Available Operations + +* [send](#send) - Create a chat completion + +## send + +Sends a request for a model response for the given chat conversation. Supports both streaming and non-streaming modes. + +### Example Usage + + +```python +from openrouter import OpenRouter +import os + + +with OpenRouter( + api_key=os.getenv("OPENROUTER_API_KEY", ""), +) as open_router: + + res = open_router.chat.send(messages=[], stream=False) + + with res as event_stream: + for event in event_stream: + # handle event + print(event, flush=True) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | +| `messages` | List[[models.Message](../../models/message.md)] | :heavy_check_mark: | N/A | +| `model` | *Optional[str]* | :heavy_minus_sign: | N/A | +| `models` | List[*str*] | :heavy_minus_sign: | N/A | +| `frequency_penalty` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | +| `logit_bias` | Dict[str, *float*] | :heavy_minus_sign: | N/A | +| `logprobs` | *OptionalNullable[bool]* | :heavy_minus_sign: | N/A | +| `top_logprobs` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | +| `max_completion_tokens` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | +| `max_tokens` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | +| `metadata` | Dict[str, *str*] | :heavy_minus_sign: | N/A | +| `presence_penalty` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | +| `reasoning` | [Optional[models.Reasoning]](../../models/reasoning.md) | :heavy_minus_sign: | N/A | +| `response_format` | [Optional[models.ChatGenerationParamsResponseFormatUnion]](../../models/chatgenerationparamsresponseformatunion.md) | :heavy_minus_sign: | N/A | +| `seed` | *OptionalNullable[int]* | :heavy_minus_sign: | N/A | +| `stop` | [OptionalNullable[models.ChatGenerationParamsStop]](../../models/chatgenerationparamsstop.md) | :heavy_minus_sign: | N/A | +| `stream` | *Optional[bool]* | :heavy_minus_sign: | N/A | +| `stream_options` | [OptionalNullable[models.ChatStreamOptions]](../../models/chatstreamoptions.md) | :heavy_minus_sign: | N/A | +| `temperature` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | +| `tool_choice` | *Optional[Any]* | :heavy_minus_sign: | N/A | +| `tools` | List[[models.ToolDefinitionJSON](../../models/tooldefinitionjson.md)] | :heavy_minus_sign: | N/A | +| `top_p` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | +| `user` | *Optional[str]* | :heavy_minus_sign: | N/A | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[models.SendChatCompletionRequestResponse](../../models/sendchatcompletionrequestresponse.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------------- | ----------------------------- | ----------------------------- | +| errors.ChatError | 400, 401, 429 | application/json | +| errors.ChatError | 500 | application/json | +| errors.OpenRouterDefaultError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/docs/sdks/completions/README.md b/docs/sdks/completions/README.md new file mode 100644 index 0000000..d1b5f3f --- /dev/null +++ b/docs/sdks/completions/README.md @@ -0,0 +1,70 @@ +# Completions +(*completions*) + +## Overview + +### Available Operations + +* [generate](#generate) - Create a completion + +## generate + +Creates a completion for the provided prompt and parameters. Supports both streaming and non-streaming modes. + +### Example Usage + + +```python +from openrouter import OpenRouter +import os + + +with OpenRouter( + api_key=os.getenv("OPENROUTER_API_KEY", ""), +) as open_router: + + res = open_router.completions.generate(prompt=[], stream=False) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | +| `prompt` | [models.Prompt](../../models/prompt.md) | :heavy_check_mark: | N/A | +| `model` | *Optional[str]* | :heavy_minus_sign: | N/A | +| `models` | List[*str*] | :heavy_minus_sign: | N/A | +| `best_of` | *OptionalNullable[int]* | :heavy_minus_sign: | N/A | +| `echo` | *OptionalNullable[bool]* | :heavy_minus_sign: | N/A | +| `frequency_penalty` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | +| `logit_bias` | Dict[str, *float*] | :heavy_minus_sign: | N/A | +| `logprobs` | *OptionalNullable[int]* | :heavy_minus_sign: | N/A | +| `max_tokens` | *OptionalNullable[int]* | :heavy_minus_sign: | N/A | +| `n` | *OptionalNullable[int]* | :heavy_minus_sign: | N/A | +| `presence_penalty` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | +| `seed` | *OptionalNullable[int]* | :heavy_minus_sign: | N/A | +| `stop` | [OptionalNullable[models.CompletionCreateParamsStop]](../../models/completioncreateparamsstop.md) | :heavy_minus_sign: | N/A | +| `stream` | *Optional[bool]* | :heavy_minus_sign: | N/A | +| `stream_options` | [OptionalNullable[models.StreamOptions]](../../models/streamoptions.md) | :heavy_minus_sign: | N/A | +| `suffix` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | +| `temperature` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | +| `top_p` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | +| `user` | *Optional[str]* | :heavy_minus_sign: | N/A | +| `metadata` | Dict[str, *str*] | :heavy_minus_sign: | N/A | +| `response_format` | [OptionalNullable[models.CompletionCreateParamsResponseFormatUnion]](../../models/completioncreateparamsresponseformatunion.md) | :heavy_minus_sign: | N/A | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[models.CompletionResponse](../../models/completionresponse.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------------- | ----------------------------- | ----------------------------- | +| errors.ChatError | 400, 401, 429 | application/json | +| errors.ChatError | 500 | application/json | +| errors.OpenRouterDefaultError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/docs/sdks/credits/README.md b/docs/sdks/credits/README.md new file mode 100644 index 0000000..39d6c23 --- /dev/null +++ b/docs/sdks/credits/README.md @@ -0,0 +1,100 @@ +# Credits +(*credits*) + +## Overview + +Credit management endpoints + +### Available Operations + +* [get_credits](#get_credits) - Get remaining credits +* [create_coinbase_charge](#create_coinbase_charge) - Create a Coinbase charge for crypto payment + +## get_credits + +Get total credits purchased and used for the authenticated user + +### Example Usage + + +```python +from openrouter import OpenRouter +import os + + +with OpenRouter( + api_key=os.getenv("OPENROUTER_API_KEY", ""), +) as open_router: + + res = open_router.credits.get_credits() + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[models.GetCreditsResponse](../../models/getcreditsresponse.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ---------------------------------- | ---------------------------------- | ---------------------------------- | +| errors.UnauthorizedResponseError | 401 | application/json | +| errors.ForbiddenResponseError | 403 | application/json | +| errors.InternalServerResponseError | 500 | application/json | +| errors.OpenRouterDefaultError | 4XX, 5XX | \*/\* | + +## create_coinbase_charge + +Create a Coinbase charge for crypto payment + +### Example Usage + + +```python +from openrouter import OpenRouter, models +import os + + +with OpenRouter() as open_router: + + res = open_router.credits.create_coinbase_charge(security=models.CreateCoinbaseChargeSecurity( + bearer=os.getenv("OPENROUTER_BEARER", ""), + ), amount=100, sender="0x1234567890123456789012345678901234567890", chain_id=1) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ----------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | +| `security` | [models.CreateCoinbaseChargeSecurity](../../models/createcoinbasechargesecurity.md) | :heavy_check_mark: | N/A | +| `amount` | *float* | :heavy_check_mark: | N/A | +| `sender` | *str* | :heavy_check_mark: | N/A | +| `chain_id` | [models.ChainID](../../models/chainid.md) | :heavy_check_mark: | N/A | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[models.CreateCoinbaseChargeResponse](../../models/createcoinbasechargeresponse.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------------------- | ----------------------------------- | ----------------------------------- | +| errors.BadRequestResponseError | 400 | application/json | +| errors.UnauthorizedResponseError | 401 | application/json | +| errors.TooManyRequestsResponseError | 429 | application/json | +| errors.InternalServerResponseError | 500 | application/json | +| errors.OpenRouterDefaultError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/docs/sdks/embeddings/README.md b/docs/sdks/embeddings/README.md new file mode 100644 index 0000000..cad1726 --- /dev/null +++ b/docs/sdks/embeddings/README.md @@ -0,0 +1,123 @@ +# Embeddings +(*embeddings*) + +## Overview + +Text embedding endpoints + +### Available Operations + +* [generate](#generate) - Submit an embedding request +* [list_models](#list_models) - List all embeddings models + +## generate + +Submits an embedding request to the embeddings router + +### Example Usage + + +```python +from openrouter import OpenRouter +import os + + +with OpenRouter( + api_key=os.getenv("OPENROUTER_API_KEY", ""), +) as open_router: + + res = open_router.embeddings.generate(input="", model="Taurus", provider={ + "data_collection": "deny", + "zdr": True, + "enforce_distillable_text": True, + "order": [ + "OpenAI", + ], + "only": [ + "OpenAI", + ], + "ignore": [ + "OpenAI", + ], + "quantizations": [ + "fp16", + ], + "sort": "price", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | +| `input` | [models.Input](../../models/input.md) | :heavy_check_mark: | N/A | +| `model` | *str* | :heavy_check_mark: | N/A | +| `provider` | [Optional[models.CreateEmbeddingsProvider]](../../models/createembeddingsprovider.md) | :heavy_minus_sign: | N/A | +| `encoding_format` | [Optional[models.EncodingFormat]](../../models/encodingformat.md) | :heavy_minus_sign: | N/A | +| `user` | *Optional[str]* | :heavy_minus_sign: | N/A | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[models.CreateEmbeddingsResponse](../../models/createembeddingsresponse.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| -------------------------------------- | -------------------------------------- | -------------------------------------- | +| errors.BadRequestResponseError | 400 | application/json | +| errors.UnauthorizedResponseError | 401 | application/json | +| errors.PaymentRequiredResponseError | 402 | application/json | +| errors.NotFoundResponseError | 404 | application/json | +| errors.TooManyRequestsResponseError | 429 | application/json | +| errors.InternalServerResponseError | 500 | application/json | +| errors.BadGatewayResponseError | 502 | application/json | +| errors.ServiceUnavailableResponseError | 503 | application/json | +| errors.EdgeNetworkTimeoutResponseError | 524 | application/json | +| errors.ProviderOverloadedResponseError | 529 | application/json | +| errors.OpenRouterDefaultError | 4XX, 5XX | \*/\* | + +## list_models + +Returns a list of all available embeddings models and their properties + +### Example Usage + + +```python +from openrouter import OpenRouter +import os + + +with OpenRouter( + api_key=os.getenv("OPENROUTER_API_KEY", ""), +) as open_router: + + res = open_router.embeddings.list_models() + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[models.ModelsListResponse](../../models/modelslistresponse.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ---------------------------------- | ---------------------------------- | ---------------------------------- | +| errors.BadRequestResponseError | 400 | application/json | +| errors.InternalServerResponseError | 500 | application/json | +| errors.OpenRouterDefaultError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/docs/sdks/endpoints/README.md b/docs/sdks/endpoints/README.md new file mode 100644 index 0000000..2cda3e7 --- /dev/null +++ b/docs/sdks/endpoints/README.md @@ -0,0 +1,94 @@ +# Endpoints +(*endpoints*) + +## Overview + +Endpoint information + +### Available Operations + +* [list](#list) - List all endpoints for a model +* [list_zdr_endpoints](#list_zdr_endpoints) - Preview the impact of ZDR on the available endpoints + +## list + +List all endpoints for a model + +### Example Usage + + +```python +from openrouter import OpenRouter +import os + + +with OpenRouter( + api_key=os.getenv("OPENROUTER_API_KEY", ""), +) as open_router: + + res = open_router.endpoints.list(author="", slug="") + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | +| `author` | *str* | :heavy_check_mark: | N/A | +| `slug` | *str* | :heavy_check_mark: | N/A | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[models.EndpointsListEndpointsResponse](../../models/endpointslistendpointsresponse.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ---------------------------------- | ---------------------------------- | ---------------------------------- | +| errors.NotFoundResponseError | 404 | application/json | +| errors.InternalServerResponseError | 500 | application/json | +| errors.OpenRouterDefaultError | 4XX, 5XX | \*/\* | + +## list_zdr_endpoints + +Preview the impact of ZDR on the available endpoints + +### Example Usage + + +```python +from openrouter import OpenRouter +import os + + +with OpenRouter( + api_key=os.getenv("OPENROUTER_API_KEY", ""), +) as open_router: + + res = open_router.endpoints.list_zdr_endpoints() + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[models.ListEndpointsZdrResponse](../../models/listendpointszdrresponse.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ---------------------------------- | ---------------------------------- | ---------------------------------- | +| errors.InternalServerResponseError | 500 | application/json | +| errors.OpenRouterDefaultError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/docs/sdks/generations/README.md b/docs/sdks/generations/README.md new file mode 100644 index 0000000..c7a7e16 --- /dev/null +++ b/docs/sdks/generations/README.md @@ -0,0 +1,58 @@ +# Generations +(*generations*) + +## Overview + +Generation history endpoints + +### Available Operations + +* [get_generation](#get_generation) - Get request & usage metadata for a generation + +## get_generation + +Get request & usage metadata for a generation + +### Example Usage + + +```python +from openrouter import OpenRouter +import os + + +with OpenRouter( + api_key=os.getenv("OPENROUTER_API_KEY", ""), +) as open_router: + + res = open_router.generations.get_generation(id="") + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | +| `id` | *str* | :heavy_check_mark: | N/A | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[models.GetGenerationResponse](../../models/getgenerationresponse.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| -------------------------------------- | -------------------------------------- | -------------------------------------- | +| errors.UnauthorizedResponseError | 401 | application/json | +| errors.PaymentRequiredResponseError | 402 | application/json | +| errors.NotFoundResponseError | 404 | application/json | +| errors.TooManyRequestsResponseError | 429 | application/json | +| errors.InternalServerResponseError | 500 | application/json | +| errors.BadGatewayResponseError | 502 | application/json | +| errors.EdgeNetworkTimeoutResponseError | 524 | application/json | +| errors.ProviderOverloadedResponseError | 529 | application/json | +| errors.OpenRouterDefaultError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/docs/sdks/models/README.md b/docs/sdks/models/README.md new file mode 100644 index 0000000..1e9998a --- /dev/null +++ b/docs/sdks/models/README.md @@ -0,0 +1,137 @@ +# Models +(*models*) + +## Overview + +Model information endpoints + +### Available Operations + +* [count](#count) - Get total count of available models +* [list](#list) - List all models and their properties +* [list_for_user](#list_for_user) - List models filtered by user provider preferences + +## count + +Get total count of available models + +### Example Usage + + +```python +from openrouter import OpenRouter +import os + + +with OpenRouter( + api_key=os.getenv("OPENROUTER_API_KEY", ""), +) as open_router: + + res = open_router.models.count() + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[models.ModelsCountResponse](../../models/modelscountresponse.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ---------------------------------- | ---------------------------------- | ---------------------------------- | +| errors.InternalServerResponseError | 500 | application/json | +| errors.OpenRouterDefaultError | 4XX, 5XX | \*/\* | + +## list + +List all models and their properties + +### Example Usage + + +```python +from openrouter import OpenRouter +import os + + +with OpenRouter( + api_key=os.getenv("OPENROUTER_API_KEY", ""), +) as open_router: + + res = open_router.models.list() + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | +| `category` | *Optional[str]* | :heavy_minus_sign: | N/A | +| `supported_parameters` | *Optional[str]* | :heavy_minus_sign: | N/A | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[models.ModelsListResponse](../../models/modelslistresponse.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ---------------------------------- | ---------------------------------- | ---------------------------------- | +| errors.BadRequestResponseError | 400 | application/json | +| errors.InternalServerResponseError | 500 | application/json | +| errors.OpenRouterDefaultError | 4XX, 5XX | \*/\* | + +## list_for_user + +List models filtered by user provider preferences + +### Example Usage + + +```python +from openrouter import OpenRouter, models +import os + + +with OpenRouter() as open_router: + + res = open_router.models.list_for_user(security=models.ListModelsUserSecurity( + bearer=os.getenv("OPENROUTER_BEARER", ""), + )) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | +| `security` | [models.ListModelsUserSecurity](../../listmodelsusersecurity.md) | :heavy_check_mark: | The security requirements to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[models.ModelsListResponse](../../models/modelslistresponse.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ---------------------------------- | ---------------------------------- | ---------------------------------- | +| errors.UnauthorizedResponseError | 401 | application/json | +| errors.InternalServerResponseError | 500 | application/json | +| errors.OpenRouterDefaultError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/docs/sdks/oauth/README.md b/docs/sdks/oauth/README.md new file mode 100644 index 0000000..d069d54 --- /dev/null +++ b/docs/sdks/oauth/README.md @@ -0,0 +1,103 @@ +# OAuth +(*o_auth*) + +## Overview + +OAuth authentication endpoints + +### Available Operations + +* [exchange_auth_code_for_api_key](#exchange_auth_code_for_api_key) - Exchange authorization code for API key +* [create_auth_code](#create_auth_code) - Create authorization code + +## exchange_auth_code_for_api_key + +Exchange an authorization code from the PKCE flow for a user-controlled API key + +### Example Usage + + +```python +from openrouter import OpenRouter +import os + + +with OpenRouter( + api_key=os.getenv("OPENROUTER_API_KEY", ""), +) as open_router: + + res = open_router.o_auth.exchange_auth_code_for_api_key(code="auth_code_abc123def456", code_verifier="dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk", code_challenge_method="S256") + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | +| `code` | *str* | :heavy_check_mark: | The authorization code received from the OAuth redirect | auth_code_abc123def456 | +| `code_verifier` | *Optional[str]* | :heavy_minus_sign: | The code verifier if code_challenge was used in the authorization request | dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk | +| `code_challenge_method` | [OptionalNullable[models.ExchangeAuthCodeForAPIKeyCodeChallengeMethod]](../../models/exchangeauthcodeforapikeycodechallengemethod.md) | :heavy_minus_sign: | The method used to generate the code challenge | S256 | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | | + +### Response + +**[models.ExchangeAuthCodeForAPIKeyResponse](../../models/exchangeauthcodeforapikeyresponse.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ---------------------------------- | ---------------------------------- | ---------------------------------- | +| errors.BadRequestResponseError | 400 | application/json | +| errors.ForbiddenResponseError | 403 | application/json | +| errors.InternalServerResponseError | 500 | application/json | +| errors.OpenRouterDefaultError | 4XX, 5XX | \*/\* | + +## create_auth_code + +Create an authorization code for the PKCE flow to generate a user-controlled API key + +### Example Usage + + +```python +from openrouter import OpenRouter +import os + + +with OpenRouter( + api_key=os.getenv("OPENROUTER_API_KEY", ""), +) as open_router: + + res = open_router.o_auth.create_auth_code(callback_url="https://myapp.com/auth/callback", code_challenge="E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM", code_challenge_method="S256", limit=100) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | Example | +| --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | +| `callback_url` | *str* | :heavy_check_mark: | The callback URL to redirect to after authorization. Note, only https URLs on ports 443 and 3000 are allowed. | https://myapp.com/auth/callback | +| `code_challenge` | *Optional[str]* | :heavy_minus_sign: | PKCE code challenge for enhanced security | E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM | +| `code_challenge_method` | [Optional[models.CreateAuthKeysCodeCodeChallengeMethod]](../../models/createauthkeyscodecodechallengemethod.md) | :heavy_minus_sign: | The method used to generate the code challenge | S256 | +| `limit` | *Optional[float]* | :heavy_minus_sign: | Credit limit for the API key to be created | 100 | +| `expires_at` | [date](https://docs.python.org/3/library/datetime.html#date-objects) | :heavy_minus_sign: | Optional expiration time for the API key to be created | | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | | + +### Response + +**[models.CreateAuthKeysCodeResponse](../../models/createauthkeyscoderesponse.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ---------------------------------- | ---------------------------------- | ---------------------------------- | +| errors.BadRequestResponseError | 400 | application/json | +| errors.UnauthorizedResponseError | 401 | application/json | +| errors.InternalServerResponseError | 500 | application/json | +| errors.OpenRouterDefaultError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/docs/sdks/parameters/README.md b/docs/sdks/parameters/README.md new file mode 100644 index 0000000..b197a12 --- /dev/null +++ b/docs/sdks/parameters/README.md @@ -0,0 +1,56 @@ +# Parameters +(*parameters*) + +## Overview + +Parameters endpoints + +### Available Operations + +* [get_parameters](#get_parameters) - Get a model's supported parameters and data about which are most popular + +## get_parameters + +Get a model's supported parameters and data about which are most popular + +### Example Usage + + +```python +from openrouter import OpenRouter, models +import os + + +with OpenRouter() as open_router: + + res = open_router.parameters.get_parameters(security=models.GetParametersSecurity( + bearer=os.getenv("OPENROUTER_BEARER", ""), + ), author="", slug="") + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | +| `security` | [models.GetParametersSecurity](../../models/getparameterssecurity.md) | :heavy_check_mark: | N/A | +| `author` | *str* | :heavy_check_mark: | N/A | +| `slug` | *str* | :heavy_check_mark: | N/A | +| `provider` | [Optional[models.GetParametersProvider]](../../models/getparametersprovider.md) | :heavy_minus_sign: | N/A | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[models.GetParametersResponse](../../models/getparametersresponse.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ---------------------------------- | ---------------------------------- | ---------------------------------- | +| errors.UnauthorizedResponseError | 401 | application/json | +| errors.NotFoundResponseError | 404 | application/json | +| errors.InternalServerResponseError | 500 | application/json | +| errors.OpenRouterDefaultError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/docs/sdks/providers/README.md b/docs/sdks/providers/README.md new file mode 100644 index 0000000..755b740 --- /dev/null +++ b/docs/sdks/providers/README.md @@ -0,0 +1,50 @@ +# Providers +(*providers*) + +## Overview + +Provider information endpoints + +### Available Operations + +* [list](#list) - List all providers + +## list + +List all providers + +### Example Usage + + +```python +from openrouter import OpenRouter +import os + + +with OpenRouter( + api_key=os.getenv("OPENROUTER_API_KEY", ""), +) as open_router: + + res = open_router.providers.list() + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[models.ListProvidersResponse](../../models/listprovidersresponse.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ---------------------------------- | ---------------------------------- | ---------------------------------- | +| errors.InternalServerResponseError | 500 | application/json | +| errors.OpenRouterDefaultError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/docs/sdks/responses/README.md b/docs/sdks/responses/README.md new file mode 100644 index 0000000..b4b19aa --- /dev/null +++ b/docs/sdks/responses/README.md @@ -0,0 +1,145 @@ +# Responses +(*beta.responses*) + +## Overview + +beta.responses endpoints + +### Available Operations + +* [send](#send) - Create a response + +## send + +Creates a streaming or non-streaming response using OpenResponses API format + +### Example Usage + + +```python +from openrouter import OpenRouter +import os + + +with OpenRouter( + api_key=os.getenv("OPENROUTER_API_KEY", ""), +) as open_router: + + res = open_router.beta.responses.send(input=[ + { + "type": "message", + "role": "user", + "content": "Hello, how are you?", + }, + ], metadata={ + "user_id": "123", + "session_id": "abc-def-ghi", + }, tools=[ + { + "type": "function", + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + }, + }, + }, + }, + ], model="anthropic/claude-4.5-sonnet-20250929", text={ + "format_": { + "type": "text", + }, + "verbosity": "medium", + }, reasoning={ + "summary": "auto", + "enabled": True, + }, temperature=0.7, top_p=0.9, prompt={ + "id": "", + "variables": { + "key": { + "type": "input_text", + "text": "Hello, how can I help you?", + }, + }, + }, service_tier="auto", truncation="auto", stream=False, provider={ + "data_collection": "deny", + "zdr": True, + "enforce_distillable_text": True, + "order": [ + "OpenAI", + ], + "only": [ + "OpenAI", + ], + "ignore": [ + "OpenAI", + ], + "quantizations": None, + "sort": "price", + }) + + with res as event_stream: + for event in event_stream: + # handle event + print(event, flush=True) + +``` + +### Parameters + +| Parameter | Type | Required | Description | Example | +| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `input` | [Optional[models.OpenResponsesInput]](../../models/openresponsesinput.md) | :heavy_minus_sign: | Input for a response request - can be a string or array of items | [
{
"role": "user",
"content": "What is the weather today?"
}
] | +| `instructions` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | | +| `metadata` | Dict[str, *str*] | :heavy_minus_sign: | Metadata key-value pairs for the request. Keys must be ≤64 characters and cannot contain brackets. Values must be ≤512 characters. Maximum 16 pairs allowed. | {
"user_id": "123",
"session_id": "abc-def-ghi"
} | +| `tools` | List[[models.OpenResponsesRequestToolUnion](../../models/openresponsesrequesttoolunion.md)] | :heavy_minus_sign: | N/A | | +| `tool_choice` | [Optional[models.OpenAIResponsesToolChoiceUnion]](../../models/openairesponsestoolchoiceunion.md) | :heavy_minus_sign: | N/A | | +| `parallel_tool_calls` | *OptionalNullable[bool]* | :heavy_minus_sign: | N/A | | +| `model` | *Optional[str]* | :heavy_minus_sign: | N/A | | +| `models` | List[*str*] | :heavy_minus_sign: | N/A | | +| `text` | [Optional[models.OpenResponsesResponseText]](../../models/openresponsesresponsetext.md) | :heavy_minus_sign: | Text output configuration including format and verbosity | {
"format": {
"type": "text"
},
"verbosity": "medium"
} | +| `reasoning` | [OptionalNullable[models.OpenResponsesReasoningConfig]](../../models/openresponsesreasoningconfig.md) | :heavy_minus_sign: | Configuration for reasoning mode in the response | {
"summary": "auto",
"enabled": true
} | +| `max_output_tokens` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | | +| `temperature` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | | +| `top_p` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | | +| `top_k` | *Optional[float]* | :heavy_minus_sign: | N/A | | +| `prompt_cache_key` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | | +| `previous_response_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | | +| `prompt` | [OptionalNullable[models.OpenAIResponsesPrompt]](../../models/openairesponsesprompt.md) | :heavy_minus_sign: | N/A | | +| `include` | List[[models.OpenAIResponsesIncludable](../../models/openairesponsesincludable.md)] | :heavy_minus_sign: | N/A | | +| `background` | *OptionalNullable[bool]* | :heavy_minus_sign: | N/A | | +| `safety_identifier` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | | +| `store` | *OptionalNullable[bool]* | :heavy_minus_sign: | N/A | | +| `service_tier` | [OptionalNullable[models.ServiceTier]](../../models/servicetier.md) | :heavy_minus_sign: | N/A | auto | +| `truncation` | [OptionalNullable[models.Truncation]](../../models/truncation.md) | :heavy_minus_sign: | N/A | auto | +| `stream` | *Optional[bool]* | :heavy_minus_sign: | N/A | | +| `provider` | [OptionalNullable[models.Provider]](../../models/provider.md) | :heavy_minus_sign: | When multiple model providers are available, optionally indicate your routing preference. | | +| `plugins` | List[[models.Plugin](../../models/plugin.md)] | :heavy_minus_sign: | Plugins you want to enable for this request, including their settings. | | +| `user` | *Optional[str]* | :heavy_minus_sign: | A unique identifier representing your end-user, which helps distinguish between different users of your app. This allows your app to identify specific users in case of abuse reports, preventing your entire app from being affected by the actions of individual users. Maximum of 128 characters. | | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | | + +### Response + +**[models.CreateResponsesResponse](../../models/createresponsesresponse.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| --------------------------------------- | --------------------------------------- | --------------------------------------- | +| errors.BadRequestResponseError | 400 | application/json | +| errors.UnauthorizedResponseError | 401 | application/json | +| errors.PaymentRequiredResponseError | 402 | application/json | +| errors.NotFoundResponseError | 404 | application/json | +| errors.RequestTimeoutResponseError | 408 | application/json | +| errors.PayloadTooLargeResponseError | 413 | application/json | +| errors.UnprocessableEntityResponseError | 422 | application/json | +| errors.TooManyRequestsResponseError | 429 | application/json | +| errors.InternalServerResponseError | 500 | application/json | +| errors.BadGatewayResponseError | 502 | application/json | +| errors.ServiceUnavailableResponseError | 503 | application/json | +| errors.EdgeNetworkTimeoutResponseError | 524 | application/json | +| errors.ProviderOverloadedResponseError | 529 | application/json | +| errors.OpenRouterDefaultError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/py.typed b/py.typed new file mode 100644 index 0000000..3e38f1a --- /dev/null +++ b/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. The package enables type hints. diff --git a/pylintrc b/pylintrc new file mode 100644 index 0000000..193cde3 --- /dev/null +++ b/pylintrc @@ -0,0 +1,663 @@ +[MAIN] + +# Analyse import fallback blocks. This can be used to support both Python 2 and +# 3 compatible code, which means that the block might have code that exists +# only in one or another interpreter, leading to false positives when analysed. +analyse-fallback-blocks=no + +# Clear in-memory caches upon conclusion of linting. Useful if running pylint +# in a server-like mode. +clear-cache-post-run=no + +# Load and enable all available extensions. Use --list-extensions to see a list +# all available extensions. +#enable-all-extensions= + +# In error mode, messages with a category besides ERROR or FATAL are +# suppressed, and no reports are done by default. Error mode is compatible with +# disabling specific errors. +#errors-only= + +# Always return a 0 (non-error) status code, even if lint errors are found. +# This is primarily useful in continuous integration scripts. +#exit-zero= + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code. +extension-pkg-allow-list= + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code. (This is an alternative name to extension-pkg-allow-list +# for backward compatibility.) +extension-pkg-whitelist= + +# Return non-zero exit code if any of these messages/categories are detected, +# even if score is above --fail-under value. Syntax same as enable. Messages +# specified are enabled, while categories only check already-enabled messages. +fail-on= + +# Specify a score threshold under which the program will exit with error. +fail-under=10 + +# Interpret the stdin as a python script, whose filename needs to be passed as +# the module_or_package argument. +#from-stdin= + +# Files or directories to be skipped. They should be base names, not paths. +ignore=CVS + +# Add files or directories matching the regular expressions patterns to the +# ignore-list. The regex matches against paths and can be in Posix or Windows +# format. Because '\\' represents the directory delimiter on Windows systems, +# it can't be used as an escape character. +ignore-paths= + +# Files or directories matching the regular expression patterns are skipped. +# The regex matches against base names, not paths. The default value ignores +# Emacs file locks +ignore-patterns=^\.# + +# List of module names for which member attributes should not be checked and +# will not be imported (useful for modules/projects where namespaces are +# manipulated during runtime and thus existing member attributes cannot be +# deduced by static analysis). It supports qualified module names, as well as +# Unix pattern matching. +ignored-modules= + +# Python code to execute, usually for sys.path manipulation such as +# pygtk.require(). +#init-hook= + +# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the +# number of processors available to use, and will cap the count on Windows to +# avoid hangs. +jobs=1 + +# Control the amount of potential inferred values when inferring a single +# object. This can help the performance when dealing with large functions or +# complex, nested conditions. +limit-inference-results=100 + +# List of plugins (as comma separated values of python module names) to load, +# usually to register additional checkers. +load-plugins= + +# Pickle collected data for later comparisons. +persistent=yes + +# Minimum Python version to use for version dependent checks. Will default to +# the version used to run pylint. +py-version=3.9 + +# Discover python modules and packages in the file system subtree. +recursive=no + +# Add paths to the list of the source roots. Supports globbing patterns. The +# source root is an absolute path or a path relative to the current working +# directory used to determine a package namespace for modules located under the +# source root. +source-roots=src + +# When enabled, pylint would attempt to guess common misconfiguration and emit +# user-friendly hints instead of false-positive error messages. +suggestion-mode=yes + +# Allow loading of arbitrary C extensions. Extensions are imported into the +# active Python interpreter and may run arbitrary code. +unsafe-load-any-extension=no + +# In verbose mode, extra non-checker-related info will be displayed. +#verbose= + + +[BASIC] + +# Naming style matching correct argument names. +argument-naming-style=snake_case + +# Regular expression matching correct argument names. Overrides argument- +# naming-style. If left empty, argument names will be checked with the set +# naming style. +#argument-rgx= + +# Naming style matching correct attribute names. +#attr-naming-style=snake_case + +# Regular expression matching correct attribute names. Overrides attr-naming- +# style. If left empty, attribute names will be checked with the set naming +# style. +attr-rgx=[^\W\d][^\W]*|__.*__$ + +# Bad variable names which should always be refused, separated by a comma. +bad-names= + +# Bad variable names regexes, separated by a comma. If names match any regex, +# they will always be refused +bad-names-rgxs= + +# Naming style matching correct class attribute names. +class-attribute-naming-style=any + +# Regular expression matching correct class attribute names. Overrides class- +# attribute-naming-style. If left empty, class attribute names will be checked +# with the set naming style. +#class-attribute-rgx= + +# Naming style matching correct class constant names. +class-const-naming-style=UPPER_CASE + +# Regular expression matching correct class constant names. Overrides class- +# const-naming-style. If left empty, class constant names will be checked with +# the set naming style. +#class-const-rgx= + +# Naming style matching correct class names. +class-naming-style=PascalCase + +# Regular expression matching correct class names. Overrides class-naming- +# style. If left empty, class names will be checked with the set naming style. +#class-rgx= + +# Naming style matching correct constant names. +const-naming-style=UPPER_CASE + +# Regular expression matching correct constant names. Overrides const-naming- +# style. If left empty, constant names will be checked with the set naming +# style. +#const-rgx= + +# Minimum line length for functions/classes that require docstrings, shorter +# ones are exempt. +docstring-min-length=-1 + +# Naming style matching correct function names. +function-naming-style=snake_case + +# Regular expression matching correct function names. Overrides function- +# naming-style. If left empty, function names will be checked with the set +# naming style. +#function-rgx= + +# Good variable names which should always be accepted, separated by a comma. +good-names=i, + j, + k, + ex, + Run, + _, + e, + id, + n + +# Good variable names regexes, separated by a comma. If names match any regex, +# they will always be accepted +good-names-rgxs= + +# Include a hint for the correct naming format with invalid-name. +include-naming-hint=no + +# Naming style matching correct inline iteration names. +inlinevar-naming-style=any + +# Regular expression matching correct inline iteration names. Overrides +# inlinevar-naming-style. If left empty, inline iteration names will be checked +# with the set naming style. +#inlinevar-rgx= + +# Naming style matching correct method names. +method-naming-style=snake_case + +# Regular expression matching correct method names. Overrides method-naming- +# style. If left empty, method names will be checked with the set naming style. +#method-rgx= + +# Naming style matching correct module names. +module-naming-style=snake_case + +# Regular expression matching correct module names. Overrides module-naming- +# style. If left empty, module names will be checked with the set naming style. +#module-rgx= + +# Colon-delimited sets of names that determine each other's naming style when +# the name regexes allow several styles. +name-group= + +# Regular expression which should only match function or class names that do +# not require a docstring. +no-docstring-rgx=^_ + +# List of decorators that produce properties, such as abc.abstractproperty. Add +# to this list to register other decorators that produce valid properties. +# These decorators are taken in consideration only for invalid-name. +property-classes=abc.abstractproperty + +# Regular expression matching correct type alias names. If left empty, type +# alias names will be checked with the set naming style. +typealias-rgx=.* + +# Regular expression matching correct type variable names. If left empty, type +# variable names will be checked with the set naming style. +#typevar-rgx= + +# Naming style matching correct variable names. +variable-naming-style=snake_case + +# Regular expression matching correct variable names. Overrides variable- +# naming-style. If left empty, variable names will be checked with the set +# naming style. +#variable-rgx= + + +[CLASSES] + +# Warn about protected attribute access inside special methods +check-protected-access-in-special-methods=no + +# List of method names used to declare (i.e. assign) instance attributes. +defining-attr-methods=__init__, + __new__, + setUp, + asyncSetUp, + __post_init__ + +# List of member names, which should be excluded from the protected access +# warning. +exclude-protected=_asdict,_fields,_replace,_source,_make,os._exit + +# List of valid names for the first argument in a class method. +valid-classmethod-first-arg=cls + +# List of valid names for the first argument in a metaclass class method. +valid-metaclass-classmethod-first-arg=mcs + + +[DESIGN] + +# List of regular expressions of class ancestor names to ignore when counting +# public methods (see R0903) +exclude-too-few-public-methods= + +# List of qualified class names to ignore when counting class parents (see +# R0901) +ignored-parents= + +# Maximum number of arguments for function / method. +max-args=5 + +# Maximum number of attributes for a class (see R0902). +max-attributes=7 + +# Maximum number of boolean expressions in an if statement (see R0916). +max-bool-expr=5 + +# Maximum number of branch for function / method body. +max-branches=12 + +# Maximum number of locals for function / method body. +max-locals=15 + +# Maximum number of parents for a class (see R0901). +max-parents=7 + +# Maximum number of public methods for a class (see R0904). +max-public-methods=25 + +# Maximum number of return / yield for function / method body. +max-returns=6 + +# Maximum number of statements in function / method body. +max-statements=50 + +# Minimum number of public methods for a class (see R0903). +min-public-methods=2 + + +[EXCEPTIONS] + +# Exceptions that will emit a warning when caught. +overgeneral-exceptions=builtins.BaseException,builtins.Exception + + +[FORMAT] + +# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. +expected-line-ending-format= + +# Regexp for a line that is allowed to be longer than the limit. +ignore-long-lines=^\s*(# )??$ + +# Number of spaces of indent required inside a hanging or continued line. +indent-after-paren=4 + +# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 +# tab). +indent-string=' ' + +# Maximum number of characters on a single line. +max-line-length=100 + +# Maximum number of lines in a module. +max-module-lines=1000 + +# Allow the body of a class to be on the same line as the declaration if body +# contains single statement. +single-line-class-stmt=no + +# Allow the body of an if to be on the same line as the test if there is no +# else. +single-line-if-stmt=no + + +[IMPORTS] + +# List of modules that can be imported at any level, not just the top level +# one. +allow-any-import-level= + +# Allow explicit reexports by alias from a package __init__. +allow-reexport-from-package=no + +# Allow wildcard imports from modules that define __all__. +allow-wildcard-with-all=no + +# Deprecated modules which should not be used, separated by a comma. +deprecated-modules= + +# Output a graph (.gv or any supported image format) of external dependencies +# to the given file (report RP0402 must not be disabled). +ext-import-graph= + +# Output a graph (.gv or any supported image format) of all (i.e. internal and +# external) dependencies to the given file (report RP0402 must not be +# disabled). +import-graph= + +# Output a graph (.gv or any supported image format) of internal dependencies +# to the given file (report RP0402 must not be disabled). +int-import-graph= + +# Force import order to recognize a module as part of the standard +# compatibility libraries. +known-standard-library= + +# Force import order to recognize a module as part of a third party library. +known-third-party=enchant + +# Couples of modules and preferred modules, separated by a comma. +preferred-modules= + + +[LOGGING] + +# The type of string formatting that logging methods do. `old` means using % +# formatting, `new` is for `{}` formatting. +logging-format-style=old + +# Logging modules to check that the string format arguments are in logging +# function parameter format. +logging-modules=logging + + +[MESSAGES CONTROL] + +# Only show warnings with the listed confidence levels. Leave empty to show +# all. Valid levels: HIGH, CONTROL_FLOW, INFERENCE, INFERENCE_FAILURE, +# UNDEFINED. +confidence=HIGH, + CONTROL_FLOW, + INFERENCE, + INFERENCE_FAILURE, + UNDEFINED + +# Disable the message, report, category or checker with the given id(s). You +# can either give multiple identifiers separated by comma (,) or put this +# option multiple times (only on the command line, not in the configuration +# file where it should appear only once). You can also use "--disable=all" to +# disable everything first and then re-enable specific checks. For example, if +# you want to run only the similarities checker, you can use "--disable=all +# --enable=similarities". If you want to run only the classes checker, but have +# no Warning level messages displayed, use "--disable=all --enable=classes +# --disable=W". +disable=raw-checker-failed, + bad-inline-option, + locally-disabled, + file-ignored, + suppressed-message, + useless-suppression, + deprecated-pragma, + use-implicit-booleaness-not-comparison-to-string, + use-implicit-booleaness-not-comparison-to-zero, + use-symbolic-message-instead, + trailing-whitespace, + line-too-long, + missing-class-docstring, + missing-module-docstring, + missing-function-docstring, + too-many-instance-attributes, + wrong-import-order, + too-many-arguments, + broad-exception-raised, + too-few-public-methods, + too-many-branches, + duplicate-code, + trailing-newlines, + too-many-public-methods, + too-many-locals, + too-many-lines, + using-constant-test, + too-many-statements, + cyclic-import, + too-many-nested-blocks, + too-many-boolean-expressions, + no-else-raise, + bare-except, + broad-exception-caught, + fixme, + relative-beyond-top-level, + consider-using-with, + wildcard-import, + unused-wildcard-import, + too-many-return-statements + +# Enable the message, report, category or checker with the given id(s). You can +# either give multiple identifier separated by comma (,) or put this option +# multiple time (only on the command line, not in the configuration file where +# it should appear only once). See also the "--disable" option for examples. +enable= + + +[METHOD_ARGS] + +# List of qualified names (i.e., library.method) which require a timeout +# parameter e.g. 'requests.api.get,requests.api.post' +timeout-methods=requests.api.delete,requests.api.get,requests.api.head,requests.api.options,requests.api.patch,requests.api.post,requests.api.put,requests.api.request + + +[MISCELLANEOUS] + +# List of note tags to take in consideration, separated by a comma. +notes=FIXME, + XXX, + TODO + +# Regular expression of note tags to take in consideration. +notes-rgx= + + +[REFACTORING] + +# Maximum number of nested blocks for function / method body +max-nested-blocks=5 + +# Complete name of functions that never returns. When checking for +# inconsistent-return-statements if a never returning function is called then +# it will be considered as an explicit return statement and no message will be +# printed. +never-returning-functions=sys.exit,argparse.parse_error + + +[REPORTS] + +# Python expression which should return a score less than or equal to 10. You +# have access to the variables 'fatal', 'error', 'warning', 'refactor', +# 'convention', and 'info' which contain the number of messages in each +# category, as well as 'statement' which is the total number of statements +# analyzed. This score is used by the global evaluation report (RP0004). +evaluation=max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)) + +# Template used to display messages. This is a python new-style format string +# used to format the message information. See doc for all details. +msg-template= + +# Set the output format. Available formats are: text, parseable, colorized, +# json2 (improved json format), json (old json format) and msvs (visual +# studio). You can also give a reporter class, e.g. +# mypackage.mymodule.MyReporterClass. +#output-format= + +# Tells whether to display a full report or only the messages. +reports=no + +# Activate the evaluation score. +score=yes + + +[SIMILARITIES] + +# Comments are removed from the similarity computation +ignore-comments=yes + +# Docstrings are removed from the similarity computation +ignore-docstrings=yes + +# Imports are removed from the similarity computation +ignore-imports=yes + +# Signatures are removed from the similarity computation +ignore-signatures=yes + +# Minimum lines number of a similarity. +min-similarity-lines=4 + + +[SPELLING] + +# Limits count of emitted suggestions for spelling mistakes. +max-spelling-suggestions=4 + +# Spelling dictionary name. No available dictionaries : You need to install +# both the python package and the system dependency for enchant to work. +spelling-dict= + +# List of comma separated words that should be considered directives if they +# appear at the beginning of a comment and should not be checked. +spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy: + +# List of comma separated words that should not be checked. +spelling-ignore-words= + +# A path to a file that contains the private dictionary; one word per line. +spelling-private-dict-file= + +# Tells whether to store unknown words to the private dictionary (see the +# --spelling-private-dict-file option) instead of raising a message. +spelling-store-unknown-words=no + + +[STRING] + +# This flag controls whether inconsistent-quotes generates a warning when the +# character used as a quote delimiter is used inconsistently within a module. +check-quote-consistency=no + +# This flag controls whether the implicit-str-concat should generate a warning +# on implicit string concatenation in sequences defined over several lines. +check-str-concat-over-line-jumps=no + + +[TYPECHECK] + +# List of decorators that produce context managers, such as +# contextlib.contextmanager. Add to this list to register other decorators that +# produce valid context managers. +contextmanager-decorators=contextlib.contextmanager + +# List of members which are set dynamically and missed by pylint inference +# system, and so shouldn't trigger E1101 when accessed. Python regular +# expressions are accepted. +generated-members= + +# Tells whether to warn about missing members when the owner of the attribute +# is inferred to be None. +ignore-none=yes + +# This flag controls whether pylint should warn about no-member and similar +# checks whenever an opaque object is returned when inferring. The inference +# can return multiple potential results while evaluating a Python object, but +# some branches might not be evaluated, which results in partial inference. In +# that case, it might be useful to still emit no-member and other checks for +# the rest of the inferred objects. +ignore-on-opaque-inference=yes + +# List of symbolic message names to ignore for Mixin members. +ignored-checks-for-mixins=no-member, + not-async-context-manager, + not-context-manager, + attribute-defined-outside-init + +# List of class names for which member attributes should not be checked (useful +# for classes with dynamically set attributes). This supports the use of +# qualified names. +ignored-classes=optparse.Values,thread._local,_thread._local,argparse.Namespace + +# Show a hint with possible names when a member name was not found. The aspect +# of finding the hint is based on edit distance. +missing-member-hint=yes + +# The minimum edit distance a name should have in order to be considered a +# similar match for a missing member name. +missing-member-hint-distance=1 + +# The total number of similar names that should be taken in consideration when +# showing a hint for a missing member. +missing-member-max-choices=1 + +# Regex pattern to define which classes are considered mixins. +mixin-class-rgx=.*[Mm]ixin + +# List of decorators that change the signature of a decorated function. +signature-mutators= + + +[VARIABLES] + +# List of additional names supposed to be defined in builtins. Remember that +# you should avoid defining new builtins when possible. +additional-builtins= + +# Tells whether unused global variables should be treated as a violation. +allow-global-unused-variables=yes + +# List of names allowed to shadow builtins +allowed-redefined-builtins=id,object,input + +# List of strings which can identify a callback function by name. A callback +# name must start or end with one of those strings. +callbacks=cb_, + _cb + +# A regular expression matching the name of dummy variables (i.e. expected to +# not be used). +dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ + +# Argument names that match this expression will be ignored. +ignored-argument-names=_.*|^ignored_|^unused_ + +# Tells whether we should check for unused import in __init__ files. +init-import=no + +# List of qualified module names which can have objects that can redefine +# builtins. +redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..7fee20b --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,52 @@ +[project] +name = "openrouter" +version = "0.0.1" +description = "Python Client SDK Generated by Speakeasy." +authors = [{ name = "Speakeasy" },] +readme = "README.md" +requires-python = ">=3.9.2" +dependencies = [ + "httpcore >=1.0.9", + "httpx >=0.28.1", + "pydantic >=2.11.2", +] + +[dependency-groups] +dev = [ + "mypy ==1.15.0", + "pylint ==3.2.3", + "pyright ==1.1.398", +] + +[tool.setuptools.packages.find] +where = ["src"] + +[tool.setuptools.package-data] +"*" = ["py.typed"] + +[build-system] +requires = ["setuptools>=80", "wheel"] +build-backend = "setuptools.build_meta" + +[tool.pytest.ini_options] +asyncio_default_fixture_loop_scope = "function" +pythonpath = ["src"] + +[tool.mypy] +disable_error_code = "misc" +explicit_package_bases = true +mypy_path = "src" + +[[tool.mypy.overrides]] +module = "typing_inspect" +ignore_missing_imports = true + +[[tool.mypy.overrides]] +module = "jsonpath" +ignore_missing_imports = true + +[tool.pyright] +venvPath = "." +venv = ".venv" + + diff --git a/scripts/publish.sh b/scripts/publish.sh new file mode 100644 index 0000000..ef28dc1 --- /dev/null +++ b/scripts/publish.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash + +uv build +uv publish --token $PYPI_TOKEN diff --git a/src/openrouter/__init__.py b/src/openrouter/__init__.py new file mode 100644 index 0000000..833c68c --- /dev/null +++ b/src/openrouter/__init__.py @@ -0,0 +1,17 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from ._version import ( + __title__, + __version__, + __openapi_doc_version__, + __gen_version__, + __user_agent__, +) +from .sdk import * +from .sdkconfiguration import * + + +VERSION: str = __version__ +OPENAPI_DOC_VERSION = __openapi_doc_version__ +SPEAKEASY_GENERATOR_VERSION = __gen_version__ +USER_AGENT = __user_agent__ diff --git a/src/openrouter/_hooks/__init__.py b/src/openrouter/_hooks/__init__.py new file mode 100644 index 0000000..2ee66cd --- /dev/null +++ b/src/openrouter/_hooks/__init__.py @@ -0,0 +1,5 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from .sdkhooks import * +from .types import * +from .registration import * diff --git a/src/openrouter/_hooks/registration.py b/src/openrouter/_hooks/registration.py new file mode 100644 index 0000000..cab4778 --- /dev/null +++ b/src/openrouter/_hooks/registration.py @@ -0,0 +1,13 @@ +from .types import Hooks + + +# This file is only ever generated once on the first generation and then is free to be modified. +# Any hooks you wish to add should be registered in the init_hooks function. Feel free to define them +# in this file or in separate files in the hooks folder. + + +def init_hooks(hooks: Hooks): + # pylint: disable=unused-argument + """Add hooks by calling hooks.register{sdk_init/before_request/after_success/after_error}Hook + with an instance of a hook that implements that specific Hook interface + Hooks are registered per SDK instance, and are valid for the lifetime of the SDK instance""" diff --git a/src/openrouter/_hooks/sdkhooks.py b/src/openrouter/_hooks/sdkhooks.py new file mode 100644 index 0000000..bea18a5 --- /dev/null +++ b/src/openrouter/_hooks/sdkhooks.py @@ -0,0 +1,76 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +import httpx +from .types import ( + SDKInitHook, + BeforeRequestContext, + BeforeRequestHook, + AfterSuccessContext, + AfterSuccessHook, + AfterErrorContext, + AfterErrorHook, + Hooks, +) +from .registration import init_hooks +from typing import List, Optional, Tuple +from openrouter.sdkconfiguration import SDKConfiguration + + +class SDKHooks(Hooks): + def __init__(self) -> None: + self.sdk_init_hooks: List[SDKInitHook] = [] + self.before_request_hooks: List[BeforeRequestHook] = [] + self.after_success_hooks: List[AfterSuccessHook] = [] + self.after_error_hooks: List[AfterErrorHook] = [] + init_hooks(self) + + def register_sdk_init_hook(self, hook: SDKInitHook) -> None: + self.sdk_init_hooks.append(hook) + + def register_before_request_hook(self, hook: BeforeRequestHook) -> None: + self.before_request_hooks.append(hook) + + def register_after_success_hook(self, hook: AfterSuccessHook) -> None: + self.after_success_hooks.append(hook) + + def register_after_error_hook(self, hook: AfterErrorHook) -> None: + self.after_error_hooks.append(hook) + + def sdk_init(self, config: SDKConfiguration) -> SDKConfiguration: + for hook in self.sdk_init_hooks: + config = hook.sdk_init(config) + return config + + def before_request( + self, hook_ctx: BeforeRequestContext, request: httpx.Request + ) -> httpx.Request: + for hook in self.before_request_hooks: + out = hook.before_request(hook_ctx, request) + if isinstance(out, Exception): + raise out + request = out + + return request + + def after_success( + self, hook_ctx: AfterSuccessContext, response: httpx.Response + ) -> httpx.Response: + for hook in self.after_success_hooks: + out = hook.after_success(hook_ctx, response) + if isinstance(out, Exception): + raise out + response = out + return response + + def after_error( + self, + hook_ctx: AfterErrorContext, + response: Optional[httpx.Response], + error: Optional[Exception], + ) -> Tuple[Optional[httpx.Response], Optional[Exception]]: + for hook in self.after_error_hooks: + result = hook.after_error(hook_ctx, response, error) + if isinstance(result, Exception): + raise result + response, error = result + return response, error diff --git a/src/openrouter/_hooks/types.py b/src/openrouter/_hooks/types.py new file mode 100644 index 0000000..07ace03 --- /dev/null +++ b/src/openrouter/_hooks/types.py @@ -0,0 +1,112 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from abc import ABC, abstractmethod +import httpx +from openrouter.sdkconfiguration import SDKConfiguration +from typing import Any, Callable, List, Optional, Tuple, Union + + +class HookContext: + config: SDKConfiguration + base_url: str + operation_id: str + oauth2_scopes: Optional[List[str]] = None + security_source: Optional[Union[Any, Callable[[], Any]]] = None + + def __init__( + self, + config: SDKConfiguration, + base_url: str, + operation_id: str, + oauth2_scopes: Optional[List[str]], + security_source: Optional[Union[Any, Callable[[], Any]]], + ): + self.config = config + self.base_url = base_url + self.operation_id = operation_id + self.oauth2_scopes = oauth2_scopes + self.security_source = security_source + + +class BeforeRequestContext(HookContext): + def __init__(self, hook_ctx: HookContext): + super().__init__( + hook_ctx.config, + hook_ctx.base_url, + hook_ctx.operation_id, + hook_ctx.oauth2_scopes, + hook_ctx.security_source, + ) + + +class AfterSuccessContext(HookContext): + def __init__(self, hook_ctx: HookContext): + super().__init__( + hook_ctx.config, + hook_ctx.base_url, + hook_ctx.operation_id, + hook_ctx.oauth2_scopes, + hook_ctx.security_source, + ) + + +class AfterErrorContext(HookContext): + def __init__(self, hook_ctx: HookContext): + super().__init__( + hook_ctx.config, + hook_ctx.base_url, + hook_ctx.operation_id, + hook_ctx.oauth2_scopes, + hook_ctx.security_source, + ) + + +class SDKInitHook(ABC): + @abstractmethod + def sdk_init(self, config: SDKConfiguration) -> SDKConfiguration: + pass + + +class BeforeRequestHook(ABC): + @abstractmethod + def before_request( + self, hook_ctx: BeforeRequestContext, request: httpx.Request + ) -> Union[httpx.Request, Exception]: + pass + + +class AfterSuccessHook(ABC): + @abstractmethod + def after_success( + self, hook_ctx: AfterSuccessContext, response: httpx.Response + ) -> Union[httpx.Response, Exception]: + pass + + +class AfterErrorHook(ABC): + @abstractmethod + def after_error( + self, + hook_ctx: AfterErrorContext, + response: Optional[httpx.Response], + error: Optional[Exception], + ) -> Union[Tuple[Optional[httpx.Response], Optional[Exception]], Exception]: + pass + + +class Hooks(ABC): + @abstractmethod + def register_sdk_init_hook(self, hook: SDKInitHook): + pass + + @abstractmethod + def register_before_request_hook(self, hook: BeforeRequestHook): + pass + + @abstractmethod + def register_after_success_hook(self, hook: AfterSuccessHook): + pass + + @abstractmethod + def register_after_error_hook(self, hook: AfterErrorHook): + pass diff --git a/src/openrouter/_version.py b/src/openrouter/_version.py new file mode 100644 index 0000000..db53f44 --- /dev/null +++ b/src/openrouter/_version.py @@ -0,0 +1,15 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +import importlib.metadata + +__title__: str = "openrouter" +__version__: str = "0.0.1" +__openapi_doc_version__: str = "1.0.0" +__gen_version__: str = "2.753.6" +__user_agent__: str = "speakeasy-sdk/python 0.0.1 2.753.6 1.0.0 openrouter" + +try: + if __package__ is not None: + __version__ = importlib.metadata.version(__package__) +except importlib.metadata.PackageNotFoundError: + pass diff --git a/src/openrouter/analytics.py b/src/openrouter/analytics.py new file mode 100644 index 0000000..2dc82e9 --- /dev/null +++ b/src/openrouter/analytics.py @@ -0,0 +1,229 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from .basesdk import BaseSDK +from openrouter import errors, models, utils +from openrouter._hooks import HookContext +from openrouter.types import OptionalNullable, UNSET +from openrouter.utils import get_security_from_env +from openrouter.utils.unmarshal_json_response import unmarshal_json_response +from typing import Any, Mapping, Optional + + +class Analytics(BaseSDK): + r"""Analytics and usage endpoints""" + + def get_user_activity( + self, + *, + date_: Optional[str] = None, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.GetUserActivityResponse: + r"""Get user activity grouped by endpoint + + Returns user activity data grouped by endpoint for the last 30 (completed) UTC days + + :param date_: Filter by a single UTC date in the last 30 days (YYYY-MM-DD format). + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + + request = models.GetUserActivityRequest( + date_=date_, + ) + + req = self._build_request( + method="GET", + path="/activity", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = self.do_request( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="getUserActivity", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=["400", "401", "403", "4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response(models.GetUserActivityResponse, http_res) + if utils.match_response(http_res, "400", "application/json"): + response_data = unmarshal_json_response( + errors.BadRequestResponseErrorData, http_res + ) + raise errors.BadRequestResponseError(response_data, http_res) + if utils.match_response(http_res, "401", "application/json"): + response_data = unmarshal_json_response( + errors.UnauthorizedResponseErrorData, http_res + ) + raise errors.UnauthorizedResponseError(response_data, http_res) + if utils.match_response(http_res, "403", "application/json"): + response_data = unmarshal_json_response( + errors.ForbiddenResponseErrorData, http_res + ) + raise errors.ForbiddenResponseError(response_data, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) + + async def get_user_activity_async( + self, + *, + date_: Optional[str] = None, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.GetUserActivityResponse: + r"""Get user activity grouped by endpoint + + Returns user activity data grouped by endpoint for the last 30 (completed) UTC days + + :param date_: Filter by a single UTC date in the last 30 days (YYYY-MM-DD format). + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + + request = models.GetUserActivityRequest( + date_=date_, + ) + + req = self._build_request_async( + method="GET", + path="/activity", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = await self.do_request_async( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="getUserActivity", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=["400", "401", "403", "4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response(models.GetUserActivityResponse, http_res) + if utils.match_response(http_res, "400", "application/json"): + response_data = unmarshal_json_response( + errors.BadRequestResponseErrorData, http_res + ) + raise errors.BadRequestResponseError(response_data, http_res) + if utils.match_response(http_res, "401", "application/json"): + response_data = unmarshal_json_response( + errors.UnauthorizedResponseErrorData, http_res + ) + raise errors.UnauthorizedResponseError(response_data, http_res) + if utils.match_response(http_res, "403", "application/json"): + response_data = unmarshal_json_response( + errors.ForbiddenResponseErrorData, http_res + ) + raise errors.ForbiddenResponseError(response_data, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) diff --git a/src/openrouter/api_keys.py b/src/openrouter/api_keys.py new file mode 100644 index 0000000..bea496e --- /dev/null +++ b/src/openrouter/api_keys.py @@ -0,0 +1,1332 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from .basesdk import BaseSDK +from datetime import datetime +from openrouter import errors, models, utils +from openrouter._hooks import HookContext +from openrouter.types import OptionalNullable, UNSET +from openrouter.utils import get_security_from_env +from openrouter.utils.unmarshal_json_response import unmarshal_json_response +from typing import Any, Mapping, Optional + + +class APIKeys(BaseSDK): + r"""API key management endpoints""" + + def list( + self, + *, + include_disabled: Optional[str] = None, + offset: Optional[str] = None, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.ListResponse: + r"""List API keys + + :param include_disabled: Whether to include disabled API keys in the response + :param offset: Number of API keys to skip for pagination + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + + request = models.ListRequest( + include_disabled=include_disabled, + offset=offset, + ) + + req = self._build_request( + method="GET", + path="/keys", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = self.do_request( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="list", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=["401", "429", "4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response(models.ListResponse, http_res) + if utils.match_response(http_res, "401", "application/json"): + response_data = unmarshal_json_response( + errors.UnauthorizedResponseErrorData, http_res + ) + raise errors.UnauthorizedResponseError(response_data, http_res) + if utils.match_response(http_res, "429", "application/json"): + response_data = unmarshal_json_response( + errors.TooManyRequestsResponseErrorData, http_res + ) + raise errors.TooManyRequestsResponseError(response_data, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) + + async def list_async( + self, + *, + include_disabled: Optional[str] = None, + offset: Optional[str] = None, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.ListResponse: + r"""List API keys + + :param include_disabled: Whether to include disabled API keys in the response + :param offset: Number of API keys to skip for pagination + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + + request = models.ListRequest( + include_disabled=include_disabled, + offset=offset, + ) + + req = self._build_request_async( + method="GET", + path="/keys", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = await self.do_request_async( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="list", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=["401", "429", "4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response(models.ListResponse, http_res) + if utils.match_response(http_res, "401", "application/json"): + response_data = unmarshal_json_response( + errors.UnauthorizedResponseErrorData, http_res + ) + raise errors.UnauthorizedResponseError(response_data, http_res) + if utils.match_response(http_res, "429", "application/json"): + response_data = unmarshal_json_response( + errors.TooManyRequestsResponseErrorData, http_res + ) + raise errors.TooManyRequestsResponseError(response_data, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) + + def create( + self, + *, + name: str, + limit: OptionalNullable[float] = UNSET, + limit_reset: OptionalNullable[models.CreateKeysLimitReset] = UNSET, + include_byok_in_limit: Optional[bool] = None, + expires_at: OptionalNullable[datetime] = UNSET, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.CreateKeysResponse: + r"""Create a new API key + + :param name: Name for the new API key + :param limit: Optional spending limit for the API key in USD + :param limit_reset: Type of limit reset for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday. + :param include_byok_in_limit: Whether to include BYOK usage in the limit + :param expires_at: Optional ISO 8601 UTC timestamp when the API key should expire. Must be UTC, other timezones will be rejected + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + + request = models.CreateKeysRequest( + name=name, + limit=limit, + limit_reset=limit_reset, + include_byok_in_limit=include_byok_in_limit, + expires_at=expires_at, + ) + + req = self._build_request( + method="POST", + path="/keys", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=True, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + get_serialized_body=lambda: utils.serialize_request_body( + request, False, False, "json", models.CreateKeysRequest + ), + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = self.do_request( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="createKeys", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=["400", "401", "429", "4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "201", "application/json"): + return unmarshal_json_response(models.CreateKeysResponse, http_res) + if utils.match_response(http_res, "400", "application/json"): + response_data = unmarshal_json_response( + errors.BadRequestResponseErrorData, http_res + ) + raise errors.BadRequestResponseError(response_data, http_res) + if utils.match_response(http_res, "401", "application/json"): + response_data = unmarshal_json_response( + errors.UnauthorizedResponseErrorData, http_res + ) + raise errors.UnauthorizedResponseError(response_data, http_res) + if utils.match_response(http_res, "429", "application/json"): + response_data = unmarshal_json_response( + errors.TooManyRequestsResponseErrorData, http_res + ) + raise errors.TooManyRequestsResponseError(response_data, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) + + async def create_async( + self, + *, + name: str, + limit: OptionalNullable[float] = UNSET, + limit_reset: OptionalNullable[models.CreateKeysLimitReset] = UNSET, + include_byok_in_limit: Optional[bool] = None, + expires_at: OptionalNullable[datetime] = UNSET, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.CreateKeysResponse: + r"""Create a new API key + + :param name: Name for the new API key + :param limit: Optional spending limit for the API key in USD + :param limit_reset: Type of limit reset for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday. + :param include_byok_in_limit: Whether to include BYOK usage in the limit + :param expires_at: Optional ISO 8601 UTC timestamp when the API key should expire. Must be UTC, other timezones will be rejected + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + + request = models.CreateKeysRequest( + name=name, + limit=limit, + limit_reset=limit_reset, + include_byok_in_limit=include_byok_in_limit, + expires_at=expires_at, + ) + + req = self._build_request_async( + method="POST", + path="/keys", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=True, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + get_serialized_body=lambda: utils.serialize_request_body( + request, False, False, "json", models.CreateKeysRequest + ), + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = await self.do_request_async( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="createKeys", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=["400", "401", "429", "4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "201", "application/json"): + return unmarshal_json_response(models.CreateKeysResponse, http_res) + if utils.match_response(http_res, "400", "application/json"): + response_data = unmarshal_json_response( + errors.BadRequestResponseErrorData, http_res + ) + raise errors.BadRequestResponseError(response_data, http_res) + if utils.match_response(http_res, "401", "application/json"): + response_data = unmarshal_json_response( + errors.UnauthorizedResponseErrorData, http_res + ) + raise errors.UnauthorizedResponseError(response_data, http_res) + if utils.match_response(http_res, "429", "application/json"): + response_data = unmarshal_json_response( + errors.TooManyRequestsResponseErrorData, http_res + ) + raise errors.TooManyRequestsResponseError(response_data, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) + + def update( + self, + *, + hash: str, + name: Optional[str] = None, + disabled: Optional[bool] = None, + limit: OptionalNullable[float] = UNSET, + limit_reset: OptionalNullable[models.UpdateKeysLimitReset] = UNSET, + include_byok_in_limit: Optional[bool] = None, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.UpdateKeysResponse: + r"""Update an API key + + :param hash: The hash identifier of the API key to update + :param name: New name for the API key + :param disabled: Whether to disable the API key + :param limit: New spending limit for the API key in USD + :param limit_reset: New limit reset type for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday. + :param include_byok_in_limit: Whether to include BYOK usage in the limit + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + + request = models.UpdateKeysRequest( + hash=hash, + body=models.UpdateKeysRequestBody( + name=name, + disabled=disabled, + limit=limit, + limit_reset=limit_reset, + include_byok_in_limit=include_byok_in_limit, + ), + ) + + req = self._build_request( + method="PATCH", + path="/keys/{hash}", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=True, + request_has_path_params=True, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + get_serialized_body=lambda: utils.serialize_request_body( + request.body, False, False, "json", models.UpdateKeysRequestBody + ), + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = self.do_request( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="updateKeys", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=["400", "401", "404", "429", "4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response(models.UpdateKeysResponse, http_res) + if utils.match_response(http_res, "400", "application/json"): + response_data = unmarshal_json_response( + errors.BadRequestResponseErrorData, http_res + ) + raise errors.BadRequestResponseError(response_data, http_res) + if utils.match_response(http_res, "401", "application/json"): + response_data = unmarshal_json_response( + errors.UnauthorizedResponseErrorData, http_res + ) + raise errors.UnauthorizedResponseError(response_data, http_res) + if utils.match_response(http_res, "404", "application/json"): + response_data = unmarshal_json_response( + errors.NotFoundResponseErrorData, http_res + ) + raise errors.NotFoundResponseError(response_data, http_res) + if utils.match_response(http_res, "429", "application/json"): + response_data = unmarshal_json_response( + errors.TooManyRequestsResponseErrorData, http_res + ) + raise errors.TooManyRequestsResponseError(response_data, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) + + async def update_async( + self, + *, + hash: str, + name: Optional[str] = None, + disabled: Optional[bool] = None, + limit: OptionalNullable[float] = UNSET, + limit_reset: OptionalNullable[models.UpdateKeysLimitReset] = UNSET, + include_byok_in_limit: Optional[bool] = None, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.UpdateKeysResponse: + r"""Update an API key + + :param hash: The hash identifier of the API key to update + :param name: New name for the API key + :param disabled: Whether to disable the API key + :param limit: New spending limit for the API key in USD + :param limit_reset: New limit reset type for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday. + :param include_byok_in_limit: Whether to include BYOK usage in the limit + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + + request = models.UpdateKeysRequest( + hash=hash, + body=models.UpdateKeysRequestBody( + name=name, + disabled=disabled, + limit=limit, + limit_reset=limit_reset, + include_byok_in_limit=include_byok_in_limit, + ), + ) + + req = self._build_request_async( + method="PATCH", + path="/keys/{hash}", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=True, + request_has_path_params=True, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + get_serialized_body=lambda: utils.serialize_request_body( + request.body, False, False, "json", models.UpdateKeysRequestBody + ), + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = await self.do_request_async( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="updateKeys", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=["400", "401", "404", "429", "4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response(models.UpdateKeysResponse, http_res) + if utils.match_response(http_res, "400", "application/json"): + response_data = unmarshal_json_response( + errors.BadRequestResponseErrorData, http_res + ) + raise errors.BadRequestResponseError(response_data, http_res) + if utils.match_response(http_res, "401", "application/json"): + response_data = unmarshal_json_response( + errors.UnauthorizedResponseErrorData, http_res + ) + raise errors.UnauthorizedResponseError(response_data, http_res) + if utils.match_response(http_res, "404", "application/json"): + response_data = unmarshal_json_response( + errors.NotFoundResponseErrorData, http_res + ) + raise errors.NotFoundResponseError(response_data, http_res) + if utils.match_response(http_res, "429", "application/json"): + response_data = unmarshal_json_response( + errors.TooManyRequestsResponseErrorData, http_res + ) + raise errors.TooManyRequestsResponseError(response_data, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) + + def delete( + self, + *, + hash: str, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.DeleteKeysResponse: + r"""Delete an API key + + :param hash: The hash identifier of the API key to delete + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + + request = models.DeleteKeysRequest( + hash=hash, + ) + + req = self._build_request( + method="DELETE", + path="/keys/{hash}", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=False, + request_has_path_params=True, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = self.do_request( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="deleteKeys", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=["401", "404", "429", "4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response(models.DeleteKeysResponse, http_res) + if utils.match_response(http_res, "401", "application/json"): + response_data = unmarshal_json_response( + errors.UnauthorizedResponseErrorData, http_res + ) + raise errors.UnauthorizedResponseError(response_data, http_res) + if utils.match_response(http_res, "404", "application/json"): + response_data = unmarshal_json_response( + errors.NotFoundResponseErrorData, http_res + ) + raise errors.NotFoundResponseError(response_data, http_res) + if utils.match_response(http_res, "429", "application/json"): + response_data = unmarshal_json_response( + errors.TooManyRequestsResponseErrorData, http_res + ) + raise errors.TooManyRequestsResponseError(response_data, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) + + async def delete_async( + self, + *, + hash: str, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.DeleteKeysResponse: + r"""Delete an API key + + :param hash: The hash identifier of the API key to delete + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + + request = models.DeleteKeysRequest( + hash=hash, + ) + + req = self._build_request_async( + method="DELETE", + path="/keys/{hash}", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=False, + request_has_path_params=True, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = await self.do_request_async( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="deleteKeys", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=["401", "404", "429", "4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response(models.DeleteKeysResponse, http_res) + if utils.match_response(http_res, "401", "application/json"): + response_data = unmarshal_json_response( + errors.UnauthorizedResponseErrorData, http_res + ) + raise errors.UnauthorizedResponseError(response_data, http_res) + if utils.match_response(http_res, "404", "application/json"): + response_data = unmarshal_json_response( + errors.NotFoundResponseErrorData, http_res + ) + raise errors.NotFoundResponseError(response_data, http_res) + if utils.match_response(http_res, "429", "application/json"): + response_data = unmarshal_json_response( + errors.TooManyRequestsResponseErrorData, http_res + ) + raise errors.TooManyRequestsResponseError(response_data, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) + + def get( + self, + *, + hash: str, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.GetKeyResponse: + r"""Get a single API key + + :param hash: The hash identifier of the API key to retrieve + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + + request = models.GetKeyRequest( + hash=hash, + ) + + req = self._build_request( + method="GET", + path="/keys/{hash}", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=False, + request_has_path_params=True, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = self.do_request( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="getKey", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=["401", "404", "429", "4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response(models.GetKeyResponse, http_res) + if utils.match_response(http_res, "401", "application/json"): + response_data = unmarshal_json_response( + errors.UnauthorizedResponseErrorData, http_res + ) + raise errors.UnauthorizedResponseError(response_data, http_res) + if utils.match_response(http_res, "404", "application/json"): + response_data = unmarshal_json_response( + errors.NotFoundResponseErrorData, http_res + ) + raise errors.NotFoundResponseError(response_data, http_res) + if utils.match_response(http_res, "429", "application/json"): + response_data = unmarshal_json_response( + errors.TooManyRequestsResponseErrorData, http_res + ) + raise errors.TooManyRequestsResponseError(response_data, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) + + async def get_async( + self, + *, + hash: str, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.GetKeyResponse: + r"""Get a single API key + + :param hash: The hash identifier of the API key to retrieve + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + + request = models.GetKeyRequest( + hash=hash, + ) + + req = self._build_request_async( + method="GET", + path="/keys/{hash}", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=False, + request_has_path_params=True, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = await self.do_request_async( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="getKey", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=["401", "404", "429", "4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response(models.GetKeyResponse, http_res) + if utils.match_response(http_res, "401", "application/json"): + response_data = unmarshal_json_response( + errors.UnauthorizedResponseErrorData, http_res + ) + raise errors.UnauthorizedResponseError(response_data, http_res) + if utils.match_response(http_res, "404", "application/json"): + response_data = unmarshal_json_response( + errors.NotFoundResponseErrorData, http_res + ) + raise errors.NotFoundResponseError(response_data, http_res) + if utils.match_response(http_res, "429", "application/json"): + response_data = unmarshal_json_response( + errors.TooManyRequestsResponseErrorData, http_res + ) + raise errors.TooManyRequestsResponseError(response_data, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) + + def get_current_key_metadata( + self, + *, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.GetCurrentKeyResponse: + r"""Get current API key + + Get information on the API key associated with the current authentication session + + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + req = self._build_request( + method="GET", + path="/key", + base_url=base_url, + url_variables=url_variables, + request=None, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = self.do_request( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="getCurrentKey", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=["401", "4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response(models.GetCurrentKeyResponse, http_res) + if utils.match_response(http_res, "401", "application/json"): + response_data = unmarshal_json_response( + errors.UnauthorizedResponseErrorData, http_res + ) + raise errors.UnauthorizedResponseError(response_data, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) + + async def get_current_key_metadata_async( + self, + *, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.GetCurrentKeyResponse: + r"""Get current API key + + Get information on the API key associated with the current authentication session + + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + req = self._build_request_async( + method="GET", + path="/key", + base_url=base_url, + url_variables=url_variables, + request=None, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = await self.do_request_async( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="getCurrentKey", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=["401", "4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response(models.GetCurrentKeyResponse, http_res) + if utils.match_response(http_res, "401", "application/json"): + response_data = unmarshal_json_response( + errors.UnauthorizedResponseErrorData, http_res + ) + raise errors.UnauthorizedResponseError(response_data, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) diff --git a/src/openrouter/basesdk.py b/src/openrouter/basesdk.py new file mode 100644 index 0000000..a550aff --- /dev/null +++ b/src/openrouter/basesdk.py @@ -0,0 +1,368 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from .sdkconfiguration import SDKConfiguration +import httpx +from openrouter import errors, models, utils +from openrouter._hooks import ( + AfterErrorContext, + AfterSuccessContext, + BeforeRequestContext, +) +from openrouter.utils import RetryConfig, SerializedRequestBody, get_body_content +from typing import Callable, List, Mapping, Optional, Tuple +from urllib.parse import parse_qs, urlparse + + +class BaseSDK: + sdk_configuration: SDKConfiguration + parent_ref: Optional[object] = None + """ + Reference to the root SDK instance, if any. This will prevent it from + being garbage collected while there are active streams. + """ + + def __init__( + self, + sdk_config: SDKConfiguration, + parent_ref: Optional[object] = None, + ) -> None: + self.sdk_configuration = sdk_config + self.parent_ref = parent_ref + + def _get_url(self, base_url, url_variables): + sdk_url, sdk_variables = self.sdk_configuration.get_server_details() + + if base_url is None: + base_url = sdk_url + + if url_variables is None: + url_variables = sdk_variables + + return utils.template_url(base_url, url_variables) + + def _build_request_async( + self, + method, + path, + base_url, + url_variables, + request, + request_body_required, + request_has_path_params, + request_has_query_params, + user_agent_header, + accept_header_value, + _globals=None, + security=None, + timeout_ms: Optional[int] = None, + get_serialized_body: Optional[ + Callable[[], Optional[SerializedRequestBody]] + ] = None, + url_override: Optional[str] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> httpx.Request: + client = self.sdk_configuration.async_client + return self._build_request_with_client( + client, + method, + path, + base_url, + url_variables, + request, + request_body_required, + request_has_path_params, + request_has_query_params, + user_agent_header, + accept_header_value, + _globals, + security, + timeout_ms, + get_serialized_body, + url_override, + http_headers, + ) + + def _build_request( + self, + method, + path, + base_url, + url_variables, + request, + request_body_required, + request_has_path_params, + request_has_query_params, + user_agent_header, + accept_header_value, + _globals=None, + security=None, + timeout_ms: Optional[int] = None, + get_serialized_body: Optional[ + Callable[[], Optional[SerializedRequestBody]] + ] = None, + url_override: Optional[str] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> httpx.Request: + client = self.sdk_configuration.client + return self._build_request_with_client( + client, + method, + path, + base_url, + url_variables, + request, + request_body_required, + request_has_path_params, + request_has_query_params, + user_agent_header, + accept_header_value, + _globals, + security, + timeout_ms, + get_serialized_body, + url_override, + http_headers, + ) + + def _build_request_with_client( + self, + client, + method, + path, + base_url, + url_variables, + request, + request_body_required, + request_has_path_params, + request_has_query_params, + user_agent_header, + accept_header_value, + _globals=None, + security=None, + timeout_ms: Optional[int] = None, + get_serialized_body: Optional[ + Callable[[], Optional[SerializedRequestBody]] + ] = None, + url_override: Optional[str] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> httpx.Request: + query_params = {} + + url = url_override + if url is None: + url = utils.generate_url( + self._get_url(base_url, url_variables), + path, + request if request_has_path_params else None, + _globals if request_has_path_params else None, + ) + + query_params = utils.get_query_params( + request if request_has_query_params else None, + _globals if request_has_query_params else None, + ) + else: + # Pick up the query parameter from the override so they can be + # preserved when building the request later on (necessary as of + # httpx 0.28). + parsed_override = urlparse(str(url_override)) + query_params = parse_qs(parsed_override.query, keep_blank_values=True) + + headers = utils.get_headers(request, _globals) + headers["Accept"] = accept_header_value + headers[user_agent_header] = self.sdk_configuration.user_agent + + if security is not None: + if callable(security): + security = security() + security = utils.get_security_from_env(security, models.Security) + if security is not None: + security_headers, security_query_params = utils.get_security(security) + headers = {**headers, **security_headers} + query_params = {**query_params, **security_query_params} + + serialized_request_body = SerializedRequestBody() + if get_serialized_body is not None: + rb = get_serialized_body() + if request_body_required and rb is None: + raise ValueError("request body is required") + + if rb is not None: + serialized_request_body = rb + + if ( + serialized_request_body.media_type is not None + and serialized_request_body.media_type + not in ( + "multipart/form-data", + "multipart/mixed", + ) + ): + headers["content-type"] = serialized_request_body.media_type + + if http_headers is not None: + for header, value in http_headers.items(): + headers[header] = value + + timeout = timeout_ms / 1000 if timeout_ms is not None else None + + return client.build_request( + method, + url, + params=query_params, + content=serialized_request_body.content, + data=serialized_request_body.data, + files=serialized_request_body.files, + headers=headers, + timeout=timeout, + ) + + def do_request( + self, + hook_ctx, + request, + error_status_codes, + stream=False, + retry_config: Optional[Tuple[RetryConfig, List[str]]] = None, + ) -> httpx.Response: + client = self.sdk_configuration.client + logger = self.sdk_configuration.debug_logger + + hooks = self.sdk_configuration.__dict__["_hooks"] + + def do(): + http_res = None + try: + req = hooks.before_request(BeforeRequestContext(hook_ctx), request) + logger.debug( + "Request:\nMethod: %s\nURL: %s\nHeaders: %s\nBody: %s", + req.method, + req.url, + req.headers, + get_body_content(req), + ) + + if client is None: + raise ValueError("client is required") + + http_res = client.send(req, stream=stream) + except Exception as e: + _, e = hooks.after_error(AfterErrorContext(hook_ctx), None, e) + if e is not None: + logger.debug("Request Exception", exc_info=True) + raise e + + if http_res is None: + logger.debug("Raising no response SDK error") + raise errors.NoResponseError("No response received") + + logger.debug( + "Response:\nStatus Code: %s\nURL: %s\nHeaders: %s\nBody: %s", + http_res.status_code, + http_res.url, + http_res.headers, + "" if stream else http_res.text, + ) + + if utils.match_status_codes(error_status_codes, http_res.status_code): + result, err = hooks.after_error( + AfterErrorContext(hook_ctx), http_res, None + ) + if err is not None: + logger.debug("Request Exception", exc_info=True) + raise err + if result is not None: + http_res = result + else: + logger.debug("Raising unexpected SDK error") + raise errors.OpenRouterDefaultError( + "Unexpected error occurred", http_res + ) + + return http_res + + if retry_config is not None: + http_res = utils.retry(do, utils.Retries(retry_config[0], retry_config[1])) + else: + http_res = do() + + if not utils.match_status_codes(error_status_codes, http_res.status_code): + http_res = hooks.after_success(AfterSuccessContext(hook_ctx), http_res) + + return http_res + + async def do_request_async( + self, + hook_ctx, + request, + error_status_codes, + stream=False, + retry_config: Optional[Tuple[RetryConfig, List[str]]] = None, + ) -> httpx.Response: + client = self.sdk_configuration.async_client + logger = self.sdk_configuration.debug_logger + + hooks = self.sdk_configuration.__dict__["_hooks"] + + async def do(): + http_res = None + try: + req = hooks.before_request(BeforeRequestContext(hook_ctx), request) + logger.debug( + "Request:\nMethod: %s\nURL: %s\nHeaders: %s\nBody: %s", + req.method, + req.url, + req.headers, + get_body_content(req), + ) + + if client is None: + raise ValueError("client is required") + + http_res = await client.send(req, stream=stream) + except Exception as e: + _, e = hooks.after_error(AfterErrorContext(hook_ctx), None, e) + if e is not None: + logger.debug("Request Exception", exc_info=True) + raise e + + if http_res is None: + logger.debug("Raising no response SDK error") + raise errors.NoResponseError("No response received") + + logger.debug( + "Response:\nStatus Code: %s\nURL: %s\nHeaders: %s\nBody: %s", + http_res.status_code, + http_res.url, + http_res.headers, + "" if stream else http_res.text, + ) + + if utils.match_status_codes(error_status_codes, http_res.status_code): + result, err = hooks.after_error( + AfterErrorContext(hook_ctx), http_res, None + ) + if err is not None: + logger.debug("Request Exception", exc_info=True) + raise err + if result is not None: + http_res = result + else: + logger.debug("Raising unexpected SDK error") + raise errors.OpenRouterDefaultError( + "Unexpected error occurred", http_res + ) + + return http_res + + if retry_config is not None: + http_res = await utils.retry_async( + do, utils.Retries(retry_config[0], retry_config[1]) + ) + else: + http_res = await do() + + if not utils.match_status_codes(error_status_codes, http_res.status_code): + http_res = hooks.after_success(AfterSuccessContext(hook_ctx), http_res) + + return http_res diff --git a/src/openrouter/beta.py b/src/openrouter/beta.py new file mode 100644 index 0000000..5e7c70d --- /dev/null +++ b/src/openrouter/beta.py @@ -0,0 +1,21 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from .basesdk import BaseSDK +from .sdkconfiguration import SDKConfiguration +from openrouter.responses import Responses +from typing import Optional + + +class Beta(BaseSDK): + responses: Responses + r"""beta.responses endpoints""" + + def __init__( + self, sdk_config: SDKConfiguration, parent_ref: Optional[object] = None + ) -> None: + BaseSDK.__init__(self, sdk_config, parent_ref=parent_ref) + self.sdk_configuration = sdk_config + self._init_sdks() + + def _init_sdks(self): + self.responses = Responses(self.sdk_configuration, parent_ref=self.parent_ref) diff --git a/src/openrouter/chat.py b/src/openrouter/chat.py new file mode 100644 index 0000000..b507cc9 --- /dev/null +++ b/src/openrouter/chat.py @@ -0,0 +1,751 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from .basesdk import BaseSDK +from enum import Enum +from openrouter import errors, models, utils +from openrouter._hooks import HookContext +from openrouter.types import OptionalNullable, UNSET +from openrouter.utils import eventstreaming, get_security_from_env +from openrouter.utils.unmarshal_json_response import unmarshal_json_response +from typing import Any, Dict, List, Literal, Mapping, Optional, Union, overload + + +class SendAcceptEnum(str, Enum): + APPLICATION_JSON = "application/json" + TEXT_EVENT_STREAM = "text/event-stream" + + +class Chat(BaseSDK): + @overload + def send( + self, + *, + messages: Union[List[models.Message], List[models.MessageTypedDict]], + model: Optional[str] = None, + models: Optional[List[str]] = None, + frequency_penalty: OptionalNullable[float] = UNSET, + logit_bias: OptionalNullable[Dict[str, float]] = UNSET, + logprobs: OptionalNullable[bool] = UNSET, + top_logprobs: OptionalNullable[float] = UNSET, + max_completion_tokens: OptionalNullable[float] = UNSET, + max_tokens: OptionalNullable[float] = UNSET, + metadata: Optional[Dict[str, str]] = None, + presence_penalty: OptionalNullable[float] = UNSET, + reasoning: Optional[Union[models.Reasoning, models.ReasoningTypedDict]] = None, + response_format: Optional[ + Union[ + models.ChatGenerationParamsResponseFormatUnion, + models.ChatGenerationParamsResponseFormatUnionTypedDict, + ] + ] = None, + seed: OptionalNullable[int] = UNSET, + stop: OptionalNullable[ + Union[ + models.ChatGenerationParamsStop, + models.ChatGenerationParamsStopTypedDict, + ] + ] = UNSET, + stream: Union[Literal[False], None] = None, + stream_options: OptionalNullable[ + Union[models.ChatStreamOptions, models.ChatStreamOptionsTypedDict] + ] = UNSET, + temperature: OptionalNullable[float] = UNSET, + tool_choice: Optional[Any] = None, + tools: Optional[ + Union[ + List[models.ToolDefinitionJSON], + List[models.ToolDefinitionJSONTypedDict], + ] + ] = None, + top_p: OptionalNullable[float] = UNSET, + user: Optional[str] = None, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.ChatResponse: + r"""Create a chat completion + + Sends a request for a model response for the given chat conversation. Supports both streaming and non-streaming modes. + + :param messages: + :param model: + :param models: + :param frequency_penalty: + :param logit_bias: + :param logprobs: + :param top_logprobs: + :param max_completion_tokens: + :param max_tokens: + :param metadata: + :param presence_penalty: + :param reasoning: + :param response_format: + :param seed: + :param stop: + :param stream: + :param stream_options: + :param temperature: + :param tool_choice: + :param tools: + :param top_p: + :param user: + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param accept_header_override: Override the default accept header for this method + :param http_headers: Additional headers to set or replace on requests. + """ + + @overload + def send( + self, + *, + messages: Union[List[models.Message], List[models.MessageTypedDict]], + model: Optional[str] = None, + models: Optional[List[str]] = None, + frequency_penalty: OptionalNullable[float] = UNSET, + logit_bias: OptionalNullable[Dict[str, float]] = UNSET, + logprobs: OptionalNullable[bool] = UNSET, + top_logprobs: OptionalNullable[float] = UNSET, + max_completion_tokens: OptionalNullable[float] = UNSET, + max_tokens: OptionalNullable[float] = UNSET, + metadata: Optional[Dict[str, str]] = None, + presence_penalty: OptionalNullable[float] = UNSET, + reasoning: Optional[Union[models.Reasoning, models.ReasoningTypedDict]] = None, + response_format: Optional[ + Union[ + models.ChatGenerationParamsResponseFormatUnion, + models.ChatGenerationParamsResponseFormatUnionTypedDict, + ] + ] = None, + seed: OptionalNullable[int] = UNSET, + stop: OptionalNullable[ + Union[ + models.ChatGenerationParamsStop, + models.ChatGenerationParamsStopTypedDict, + ] + ] = UNSET, + stream: Literal[True], + stream_options: OptionalNullable[ + Union[models.ChatStreamOptions, models.ChatStreamOptionsTypedDict] + ] = UNSET, + temperature: OptionalNullable[float] = UNSET, + tool_choice: Optional[Any] = None, + tools: Optional[ + Union[ + List[models.ToolDefinitionJSON], + List[models.ToolDefinitionJSONTypedDict], + ] + ] = None, + top_p: OptionalNullable[float] = UNSET, + user: Optional[str] = None, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> eventstreaming.EventStream[models.ChatStreamingResponseChunk]: + r"""Create a chat completion + + Sends a request for a model response for the given chat conversation. Supports both streaming and non-streaming modes. + + :param messages: + :param model: + :param models: + :param frequency_penalty: + :param logit_bias: + :param logprobs: + :param top_logprobs: + :param max_completion_tokens: + :param max_tokens: + :param metadata: + :param presence_penalty: + :param reasoning: + :param response_format: + :param seed: + :param stop: + :param stream: + :param stream_options: + :param temperature: + :param tool_choice: + :param tools: + :param top_p: + :param user: + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param accept_header_override: Override the default accept header for this method + :param http_headers: Additional headers to set or replace on requests. + """ + + def send( + self, + *, + messages: Union[List[models.Message], List[models.MessageTypedDict]], + model: Optional[str] = None, + models: Optional[List[str]] = None, + frequency_penalty: OptionalNullable[float] = UNSET, + logit_bias: OptionalNullable[Dict[str, float]] = UNSET, + logprobs: OptionalNullable[bool] = UNSET, + top_logprobs: OptionalNullable[float] = UNSET, + max_completion_tokens: OptionalNullable[float] = UNSET, + max_tokens: OptionalNullable[float] = UNSET, + metadata: Optional[Dict[str, str]] = None, + presence_penalty: OptionalNullable[float] = UNSET, + reasoning: Optional[Union[models.Reasoning, models.ReasoningTypedDict]] = None, + response_format: Optional[ + Union[ + models.ChatGenerationParamsResponseFormatUnion, + models.ChatGenerationParamsResponseFormatUnionTypedDict, + ] + ] = None, + seed: OptionalNullable[int] = UNSET, + stop: OptionalNullable[ + Union[ + models.ChatGenerationParamsStop, + models.ChatGenerationParamsStopTypedDict, + ] + ] = UNSET, + stream: Optional[bool] = False, + stream_options: OptionalNullable[ + Union[models.ChatStreamOptions, models.ChatStreamOptionsTypedDict] + ] = UNSET, + temperature: OptionalNullable[float] = UNSET, + tool_choice: Optional[Any] = None, + tools: Optional[ + Union[ + List[models.ToolDefinitionJSON], + List[models.ToolDefinitionJSONTypedDict], + ] + ] = None, + top_p: OptionalNullable[float] = UNSET, + user: Optional[str] = None, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.SendChatCompletionRequestResponse: + r"""Create a chat completion + + Sends a request for a model response for the given chat conversation. Supports both streaming and non-streaming modes. + + :param messages: + :param model: + :param models: + :param frequency_penalty: + :param logit_bias: + :param logprobs: + :param top_logprobs: + :param max_completion_tokens: + :param max_tokens: + :param metadata: + :param presence_penalty: + :param reasoning: + :param response_format: + :param seed: + :param stop: + :param stream: + :param stream_options: + :param temperature: + :param tool_choice: + :param tools: + :param top_p: + :param user: + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param accept_header_override: Override the default accept header for this method + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + + request = models.ChatGenerationParams( + messages=utils.get_pydantic_model(messages, List[models.Message]), + model=model, + models=models, + frequency_penalty=frequency_penalty, + logit_bias=logit_bias, + logprobs=logprobs, + top_logprobs=top_logprobs, + max_completion_tokens=max_completion_tokens, + max_tokens=max_tokens, + metadata=metadata, + presence_penalty=presence_penalty, + reasoning=utils.get_pydantic_model(reasoning, Optional[models.Reasoning]), + response_format=utils.get_pydantic_model( + response_format, + Optional[models.ChatGenerationParamsResponseFormatUnion], + ), + seed=seed, + stop=stop, + stream=stream, + stream_options=utils.get_pydantic_model( + stream_options, OptionalNullable[models.ChatStreamOptions] + ), + temperature=temperature, + tool_choice=tool_choice, + tools=utils.get_pydantic_model( + tools, Optional[List[models.ToolDefinitionJSON]] + ), + top_p=top_p, + user=user, + ) + + req = self._build_request( + method="POST", + path="/chat/completions", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=True, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="text/event-stream" if stream else "application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + get_serialized_body=lambda: utils.serialize_request_body( + request, False, False, "json", models.ChatGenerationParams + ), + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = self.do_request( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="sendChatCompletionRequest", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=["400", "401", "429", "4XX", "500", "5XX"], + stream=True, + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + http_res_text = utils.stream_to_text(http_res) + return unmarshal_json_response(models.ChatResponse, http_res, http_res_text) + if utils.match_response(http_res, "200", "text/event-stream"): + return eventstreaming.EventStream( + http_res, + lambda raw: utils.unmarshal_json( + raw, models.ChatStreamingResponseChunk + ), + sentinel="[DONE]", + client_ref=self, + ) + if utils.match_response(http_res, ["400", "401", "429"], "application/json"): + http_res_text = utils.stream_to_text(http_res) + response_data = unmarshal_json_response( + errors.ChatErrorData, http_res, http_res_text + ) + raise errors.ChatError(response_data, http_res, http_res_text) + if utils.match_response(http_res, "500", "application/json"): + http_res_text = utils.stream_to_text(http_res) + response_data = unmarshal_json_response( + errors.ChatErrorData, http_res, http_res_text + ) + raise errors.ChatError(response_data, http_res, http_res_text) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "Unexpected response received", http_res, http_res_text + ) + + @overload + async def send_async( + self, + *, + messages: Union[List[models.Message], List[models.MessageTypedDict]], + model: Optional[str] = None, + models: Optional[List[str]] = None, + frequency_penalty: OptionalNullable[float] = UNSET, + logit_bias: OptionalNullable[Dict[str, float]] = UNSET, + logprobs: OptionalNullable[bool] = UNSET, + top_logprobs: OptionalNullable[float] = UNSET, + max_completion_tokens: OptionalNullable[float] = UNSET, + max_tokens: OptionalNullable[float] = UNSET, + metadata: Optional[Dict[str, str]] = None, + presence_penalty: OptionalNullable[float] = UNSET, + reasoning: Optional[Union[models.Reasoning, models.ReasoningTypedDict]] = None, + response_format: Optional[ + Union[ + models.ChatGenerationParamsResponseFormatUnion, + models.ChatGenerationParamsResponseFormatUnionTypedDict, + ] + ] = None, + seed: OptionalNullable[int] = UNSET, + stop: OptionalNullable[ + Union[ + models.ChatGenerationParamsStop, + models.ChatGenerationParamsStopTypedDict, + ] + ] = UNSET, + stream: Union[Literal[False], None] = None, + stream_options: OptionalNullable[ + Union[models.ChatStreamOptions, models.ChatStreamOptionsTypedDict] + ] = UNSET, + temperature: OptionalNullable[float] = UNSET, + tool_choice: Optional[Any] = None, + tools: Optional[ + Union[ + List[models.ToolDefinitionJSON], + List[models.ToolDefinitionJSONTypedDict], + ] + ] = None, + top_p: OptionalNullable[float] = UNSET, + user: Optional[str] = None, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.ChatResponse: + r"""Create a chat completion + + Sends a request for a model response for the given chat conversation. Supports both streaming and non-streaming modes. + + :param messages: + :param model: + :param models: + :param frequency_penalty: + :param logit_bias: + :param logprobs: + :param top_logprobs: + :param max_completion_tokens: + :param max_tokens: + :param metadata: + :param presence_penalty: + :param reasoning: + :param response_format: + :param seed: + :param stop: + :param stream: + :param stream_options: + :param temperature: + :param tool_choice: + :param tools: + :param top_p: + :param user: + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param accept_header_override: Override the default accept header for this method + :param http_headers: Additional headers to set or replace on requests. + """ + + @overload + async def send_async( + self, + *, + messages: Union[List[models.Message], List[models.MessageTypedDict]], + model: Optional[str] = None, + models: Optional[List[str]] = None, + frequency_penalty: OptionalNullable[float] = UNSET, + logit_bias: OptionalNullable[Dict[str, float]] = UNSET, + logprobs: OptionalNullable[bool] = UNSET, + top_logprobs: OptionalNullable[float] = UNSET, + max_completion_tokens: OptionalNullable[float] = UNSET, + max_tokens: OptionalNullable[float] = UNSET, + metadata: Optional[Dict[str, str]] = None, + presence_penalty: OptionalNullable[float] = UNSET, + reasoning: Optional[Union[models.Reasoning, models.ReasoningTypedDict]] = None, + response_format: Optional[ + Union[ + models.ChatGenerationParamsResponseFormatUnion, + models.ChatGenerationParamsResponseFormatUnionTypedDict, + ] + ] = None, + seed: OptionalNullable[int] = UNSET, + stop: OptionalNullable[ + Union[ + models.ChatGenerationParamsStop, + models.ChatGenerationParamsStopTypedDict, + ] + ] = UNSET, + stream: Literal[True], + stream_options: OptionalNullable[ + Union[models.ChatStreamOptions, models.ChatStreamOptionsTypedDict] + ] = UNSET, + temperature: OptionalNullable[float] = UNSET, + tool_choice: Optional[Any] = None, + tools: Optional[ + Union[ + List[models.ToolDefinitionJSON], + List[models.ToolDefinitionJSONTypedDict], + ] + ] = None, + top_p: OptionalNullable[float] = UNSET, + user: Optional[str] = None, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> eventstreaming.EventStreamAsync[models.ChatStreamingResponseChunk]: + r"""Create a chat completion + + Sends a request for a model response for the given chat conversation. Supports both streaming and non-streaming modes. + + :param messages: + :param model: + :param models: + :param frequency_penalty: + :param logit_bias: + :param logprobs: + :param top_logprobs: + :param max_completion_tokens: + :param max_tokens: + :param metadata: + :param presence_penalty: + :param reasoning: + :param response_format: + :param seed: + :param stop: + :param stream: + :param stream_options: + :param temperature: + :param tool_choice: + :param tools: + :param top_p: + :param user: + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param accept_header_override: Override the default accept header for this method + :param http_headers: Additional headers to set or replace on requests. + """ + + async def send_async( + self, + *, + messages: Union[List[models.Message], List[models.MessageTypedDict]], + model: Optional[str] = None, + models: Optional[List[str]] = None, + frequency_penalty: OptionalNullable[float] = UNSET, + logit_bias: OptionalNullable[Dict[str, float]] = UNSET, + logprobs: OptionalNullable[bool] = UNSET, + top_logprobs: OptionalNullable[float] = UNSET, + max_completion_tokens: OptionalNullable[float] = UNSET, + max_tokens: OptionalNullable[float] = UNSET, + metadata: Optional[Dict[str, str]] = None, + presence_penalty: OptionalNullable[float] = UNSET, + reasoning: Optional[Union[models.Reasoning, models.ReasoningTypedDict]] = None, + response_format: Optional[ + Union[ + models.ChatGenerationParamsResponseFormatUnion, + models.ChatGenerationParamsResponseFormatUnionTypedDict, + ] + ] = None, + seed: OptionalNullable[int] = UNSET, + stop: OptionalNullable[ + Union[ + models.ChatGenerationParamsStop, + models.ChatGenerationParamsStopTypedDict, + ] + ] = UNSET, + stream: Optional[bool] = False, + stream_options: OptionalNullable[ + Union[models.ChatStreamOptions, models.ChatStreamOptionsTypedDict] + ] = UNSET, + temperature: OptionalNullable[float] = UNSET, + tool_choice: Optional[Any] = None, + tools: Optional[ + Union[ + List[models.ToolDefinitionJSON], + List[models.ToolDefinitionJSONTypedDict], + ] + ] = None, + top_p: OptionalNullable[float] = UNSET, + user: Optional[str] = None, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.SendChatCompletionRequestResponse: + r"""Create a chat completion + + Sends a request for a model response for the given chat conversation. Supports both streaming and non-streaming modes. + + :param messages: + :param model: + :param models: + :param frequency_penalty: + :param logit_bias: + :param logprobs: + :param top_logprobs: + :param max_completion_tokens: + :param max_tokens: + :param metadata: + :param presence_penalty: + :param reasoning: + :param response_format: + :param seed: + :param stop: + :param stream: + :param stream_options: + :param temperature: + :param tool_choice: + :param tools: + :param top_p: + :param user: + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param accept_header_override: Override the default accept header for this method + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + + request = models.ChatGenerationParams( + messages=utils.get_pydantic_model(messages, List[models.Message]), + model=model, + models=models, + frequency_penalty=frequency_penalty, + logit_bias=logit_bias, + logprobs=logprobs, + top_logprobs=top_logprobs, + max_completion_tokens=max_completion_tokens, + max_tokens=max_tokens, + metadata=metadata, + presence_penalty=presence_penalty, + reasoning=utils.get_pydantic_model(reasoning, Optional[models.Reasoning]), + response_format=utils.get_pydantic_model( + response_format, + Optional[models.ChatGenerationParamsResponseFormatUnion], + ), + seed=seed, + stop=stop, + stream=stream, + stream_options=utils.get_pydantic_model( + stream_options, OptionalNullable[models.ChatStreamOptions] + ), + temperature=temperature, + tool_choice=tool_choice, + tools=utils.get_pydantic_model( + tools, Optional[List[models.ToolDefinitionJSON]] + ), + top_p=top_p, + user=user, + ) + + req = self._build_request_async( + method="POST", + path="/chat/completions", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=True, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="text/event-stream" if stream else "application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + get_serialized_body=lambda: utils.serialize_request_body( + request, False, False, "json", models.ChatGenerationParams + ), + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = await self.do_request_async( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="sendChatCompletionRequest", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=["400", "401", "429", "4XX", "500", "5XX"], + stream=True, + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + http_res_text = await utils.stream_to_text_async(http_res) + return unmarshal_json_response(models.ChatResponse, http_res, http_res_text) + if utils.match_response(http_res, "200", "text/event-stream"): + return eventstreaming.EventStreamAsync( + http_res, + lambda raw: utils.unmarshal_json( + raw, models.ChatStreamingResponseChunk + ), + sentinel="[DONE]", + client_ref=self, + ) + if utils.match_response(http_res, ["400", "401", "429"], "application/json"): + http_res_text = await utils.stream_to_text_async(http_res) + response_data = unmarshal_json_response( + errors.ChatErrorData, http_res, http_res_text + ) + raise errors.ChatError(response_data, http_res, http_res_text) + if utils.match_response(http_res, "500", "application/json"): + http_res_text = await utils.stream_to_text_async(http_res) + response_data = unmarshal_json_response( + errors.ChatErrorData, http_res, http_res_text + ) + raise errors.ChatError(response_data, http_res, http_res_text) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "Unexpected response received", http_res, http_res_text + ) diff --git a/src/openrouter/completions.py b/src/openrouter/completions.py new file mode 100644 index 0000000..f73026f --- /dev/null +++ b/src/openrouter/completions.py @@ -0,0 +1,359 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from .basesdk import BaseSDK +from openrouter import errors, models, utils +from openrouter._hooks import HookContext +from openrouter.types import OptionalNullable, UNSET +from openrouter.utils import get_security_from_env +from openrouter.utils.unmarshal_json_response import unmarshal_json_response +from typing import Any, Dict, List, Mapping, Optional, Union + + +class Completions(BaseSDK): + def generate( + self, + *, + prompt: Union[models.Prompt, models.PromptTypedDict], + model: Optional[str] = None, + models: Optional[List[str]] = None, + best_of: OptionalNullable[int] = UNSET, + echo: OptionalNullable[bool] = UNSET, + frequency_penalty: OptionalNullable[float] = UNSET, + logit_bias: OptionalNullable[Dict[str, float]] = UNSET, + logprobs: OptionalNullable[int] = UNSET, + max_tokens: OptionalNullable[int] = UNSET, + n: OptionalNullable[int] = UNSET, + presence_penalty: OptionalNullable[float] = UNSET, + seed: OptionalNullable[int] = UNSET, + stop: OptionalNullable[ + Union[ + models.CompletionCreateParamsStop, + models.CompletionCreateParamsStopTypedDict, + ] + ] = UNSET, + stream: Optional[bool] = False, + stream_options: OptionalNullable[ + Union[models.StreamOptions, models.StreamOptionsTypedDict] + ] = UNSET, + suffix: OptionalNullable[str] = UNSET, + temperature: OptionalNullable[float] = UNSET, + top_p: OptionalNullable[float] = UNSET, + user: Optional[str] = None, + metadata: OptionalNullable[Dict[str, str]] = UNSET, + response_format: OptionalNullable[ + Union[ + models.CompletionCreateParamsResponseFormatUnion, + models.CompletionCreateParamsResponseFormatUnionTypedDict, + ] + ] = UNSET, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.CompletionResponse: + r"""Create a completion + + Creates a completion for the provided prompt and parameters. Supports both streaming and non-streaming modes. + + :param prompt: + :param model: + :param models: + :param best_of: + :param echo: + :param frequency_penalty: + :param logit_bias: + :param logprobs: + :param max_tokens: + :param n: + :param presence_penalty: + :param seed: + :param stop: + :param stream: + :param stream_options: + :param suffix: + :param temperature: + :param top_p: + :param user: + :param metadata: + :param response_format: + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + + request = models.CompletionCreateParams( + model=model, + models=models, + prompt=prompt, + best_of=best_of, + echo=echo, + frequency_penalty=frequency_penalty, + logit_bias=logit_bias, + logprobs=logprobs, + max_tokens=max_tokens, + n=n, + presence_penalty=presence_penalty, + seed=seed, + stop=stop, + stream=stream, + stream_options=utils.get_pydantic_model( + stream_options, OptionalNullable[models.StreamOptions] + ), + suffix=suffix, + temperature=temperature, + top_p=top_p, + user=user, + metadata=metadata, + response_format=utils.get_pydantic_model( + response_format, + OptionalNullable[models.CompletionCreateParamsResponseFormatUnion], + ), + ) + + req = self._build_request( + method="POST", + path="/completions", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=True, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + get_serialized_body=lambda: utils.serialize_request_body( + request, False, False, "json", models.CompletionCreateParams + ), + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = self.do_request( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="createCompletions", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=["400", "401", "429", "4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response(models.CompletionResponse, http_res) + if utils.match_response(http_res, ["400", "401", "429"], "application/json"): + response_data = unmarshal_json_response(errors.ChatErrorData, http_res) + raise errors.ChatError(response_data, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response(errors.ChatErrorData, http_res) + raise errors.ChatError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) + + async def generate_async( + self, + *, + prompt: Union[models.Prompt, models.PromptTypedDict], + model: Optional[str] = None, + models: Optional[List[str]] = None, + best_of: OptionalNullable[int] = UNSET, + echo: OptionalNullable[bool] = UNSET, + frequency_penalty: OptionalNullable[float] = UNSET, + logit_bias: OptionalNullable[Dict[str, float]] = UNSET, + logprobs: OptionalNullable[int] = UNSET, + max_tokens: OptionalNullable[int] = UNSET, + n: OptionalNullable[int] = UNSET, + presence_penalty: OptionalNullable[float] = UNSET, + seed: OptionalNullable[int] = UNSET, + stop: OptionalNullable[ + Union[ + models.CompletionCreateParamsStop, + models.CompletionCreateParamsStopTypedDict, + ] + ] = UNSET, + stream: Optional[bool] = False, + stream_options: OptionalNullable[ + Union[models.StreamOptions, models.StreamOptionsTypedDict] + ] = UNSET, + suffix: OptionalNullable[str] = UNSET, + temperature: OptionalNullable[float] = UNSET, + top_p: OptionalNullable[float] = UNSET, + user: Optional[str] = None, + metadata: OptionalNullable[Dict[str, str]] = UNSET, + response_format: OptionalNullable[ + Union[ + models.CompletionCreateParamsResponseFormatUnion, + models.CompletionCreateParamsResponseFormatUnionTypedDict, + ] + ] = UNSET, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.CompletionResponse: + r"""Create a completion + + Creates a completion for the provided prompt and parameters. Supports both streaming and non-streaming modes. + + :param prompt: + :param model: + :param models: + :param best_of: + :param echo: + :param frequency_penalty: + :param logit_bias: + :param logprobs: + :param max_tokens: + :param n: + :param presence_penalty: + :param seed: + :param stop: + :param stream: + :param stream_options: + :param suffix: + :param temperature: + :param top_p: + :param user: + :param metadata: + :param response_format: + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + + request = models.CompletionCreateParams( + model=model, + models=models, + prompt=prompt, + best_of=best_of, + echo=echo, + frequency_penalty=frequency_penalty, + logit_bias=logit_bias, + logprobs=logprobs, + max_tokens=max_tokens, + n=n, + presence_penalty=presence_penalty, + seed=seed, + stop=stop, + stream=stream, + stream_options=utils.get_pydantic_model( + stream_options, OptionalNullable[models.StreamOptions] + ), + suffix=suffix, + temperature=temperature, + top_p=top_p, + user=user, + metadata=metadata, + response_format=utils.get_pydantic_model( + response_format, + OptionalNullable[models.CompletionCreateParamsResponseFormatUnion], + ), + ) + + req = self._build_request_async( + method="POST", + path="/completions", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=True, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + get_serialized_body=lambda: utils.serialize_request_body( + request, False, False, "json", models.CompletionCreateParams + ), + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = await self.do_request_async( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="createCompletions", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=["400", "401", "429", "4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response(models.CompletionResponse, http_res) + if utils.match_response(http_res, ["400", "401", "429"], "application/json"): + response_data = unmarshal_json_response(errors.ChatErrorData, http_res) + raise errors.ChatError(response_data, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response(errors.ChatErrorData, http_res) + raise errors.ChatError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) diff --git a/src/openrouter/credits.py b/src/openrouter/credits.py new file mode 100644 index 0000000..516d95c --- /dev/null +++ b/src/openrouter/credits.py @@ -0,0 +1,453 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from .basesdk import BaseSDK +from openrouter import errors, models, utils +from openrouter._hooks import HookContext +from openrouter.types import OptionalNullable, UNSET +from openrouter.utils import get_security_from_env +from openrouter.utils.unmarshal_json_response import unmarshal_json_response +from typing import Any, Mapping, Optional, Union + + +class Credits(BaseSDK): + r"""Credit management endpoints""" + + def get_credits( + self, + *, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.GetCreditsResponse: + r"""Get remaining credits + + Get total credits purchased and used for the authenticated user + + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + req = self._build_request( + method="GET", + path="/credits", + base_url=base_url, + url_variables=url_variables, + request=None, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = self.do_request( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="getCredits", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=["401", "403", "4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response(models.GetCreditsResponse, http_res) + if utils.match_response(http_res, "401", "application/json"): + response_data = unmarshal_json_response( + errors.UnauthorizedResponseErrorData, http_res + ) + raise errors.UnauthorizedResponseError(response_data, http_res) + if utils.match_response(http_res, "403", "application/json"): + response_data = unmarshal_json_response( + errors.ForbiddenResponseErrorData, http_res + ) + raise errors.ForbiddenResponseError(response_data, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) + + async def get_credits_async( + self, + *, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.GetCreditsResponse: + r"""Get remaining credits + + Get total credits purchased and used for the authenticated user + + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + req = self._build_request_async( + method="GET", + path="/credits", + base_url=base_url, + url_variables=url_variables, + request=None, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = await self.do_request_async( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="getCredits", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=["401", "403", "4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response(models.GetCreditsResponse, http_res) + if utils.match_response(http_res, "401", "application/json"): + response_data = unmarshal_json_response( + errors.UnauthorizedResponseErrorData, http_res + ) + raise errors.UnauthorizedResponseError(response_data, http_res) + if utils.match_response(http_res, "403", "application/json"): + response_data = unmarshal_json_response( + errors.ForbiddenResponseErrorData, http_res + ) + raise errors.ForbiddenResponseError(response_data, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) + + def create_coinbase_charge( + self, + *, + security: Union[ + models.CreateCoinbaseChargeSecurity, + models.CreateCoinbaseChargeSecurityTypedDict, + ], + amount: float, + sender: str, + chain_id: models.ChainID, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.CreateCoinbaseChargeResponse: + r"""Create a Coinbase charge for crypto payment + + Create a Coinbase charge for crypto payment + + :param security: + :param amount: + :param sender: + :param chain_id: + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + + request = models.CreateChargeRequest( + amount=amount, + sender=sender, + chain_id=chain_id, + ) + + req = self._build_request( + method="POST", + path="/credits/coinbase", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=True, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=utils.get_pydantic_model( + security, models.CreateCoinbaseChargeSecurity + ), + get_serialized_body=lambda: utils.serialize_request_body( + request, False, False, "json", models.CreateChargeRequest + ), + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = self.do_request( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="createCoinbaseCharge", + oauth2_scopes=None, + security_source=get_security_from_env(security, models.Security), + ), + request=req, + error_status_codes=["400", "401", "429", "4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response( + models.CreateCoinbaseChargeResponse, http_res + ) + if utils.match_response(http_res, "400", "application/json"): + response_data = unmarshal_json_response( + errors.BadRequestResponseErrorData, http_res + ) + raise errors.BadRequestResponseError(response_data, http_res) + if utils.match_response(http_res, "401", "application/json"): + response_data = unmarshal_json_response( + errors.UnauthorizedResponseErrorData, http_res + ) + raise errors.UnauthorizedResponseError(response_data, http_res) + if utils.match_response(http_res, "429", "application/json"): + response_data = unmarshal_json_response( + errors.TooManyRequestsResponseErrorData, http_res + ) + raise errors.TooManyRequestsResponseError(response_data, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) + + async def create_coinbase_charge_async( + self, + *, + security: Union[ + models.CreateCoinbaseChargeSecurity, + models.CreateCoinbaseChargeSecurityTypedDict, + ], + amount: float, + sender: str, + chain_id: models.ChainID, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.CreateCoinbaseChargeResponse: + r"""Create a Coinbase charge for crypto payment + + Create a Coinbase charge for crypto payment + + :param security: + :param amount: + :param sender: + :param chain_id: + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + + request = models.CreateChargeRequest( + amount=amount, + sender=sender, + chain_id=chain_id, + ) + + req = self._build_request_async( + method="POST", + path="/credits/coinbase", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=True, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=utils.get_pydantic_model( + security, models.CreateCoinbaseChargeSecurity + ), + get_serialized_body=lambda: utils.serialize_request_body( + request, False, False, "json", models.CreateChargeRequest + ), + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = await self.do_request_async( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="createCoinbaseCharge", + oauth2_scopes=None, + security_source=get_security_from_env(security, models.Security), + ), + request=req, + error_status_codes=["400", "401", "429", "4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response( + models.CreateCoinbaseChargeResponse, http_res + ) + if utils.match_response(http_res, "400", "application/json"): + response_data = unmarshal_json_response( + errors.BadRequestResponseErrorData, http_res + ) + raise errors.BadRequestResponseError(response_data, http_res) + if utils.match_response(http_res, "401", "application/json"): + response_data = unmarshal_json_response( + errors.UnauthorizedResponseErrorData, http_res + ) + raise errors.UnauthorizedResponseError(response_data, http_res) + if utils.match_response(http_res, "429", "application/json"): + response_data = unmarshal_json_response( + errors.TooManyRequestsResponseErrorData, http_res + ) + raise errors.TooManyRequestsResponseError(response_data, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) diff --git a/src/openrouter/embeddings.py b/src/openrouter/embeddings.py new file mode 100644 index 0000000..9b1f5dd --- /dev/null +++ b/src/openrouter/embeddings.py @@ -0,0 +1,567 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from .basesdk import BaseSDK +from enum import Enum +from openrouter import errors, models, utils +from openrouter._hooks import HookContext +from openrouter.types import OptionalNullable, UNSET +from openrouter.utils import get_security_from_env +from openrouter.utils.unmarshal_json_response import unmarshal_json_response +from typing import Any, Mapping, Optional, Union + + +class GenerateAcceptEnum(str, Enum): + APPLICATION_JSON = "application/json" + TEXT_EVENT_STREAM = "text/event-stream" + + +class Embeddings(BaseSDK): + r"""Text embedding endpoints""" + + def generate( + self, + *, + input: Union[models.Input, models.InputTypedDict], + model: str, + provider: Optional[ + Union[ + models.CreateEmbeddingsProvider, + models.CreateEmbeddingsProviderTypedDict, + ] + ] = None, + encoding_format: Optional[ + Union[models.EncodingFormat, models.EncodingFormatTypedDict] + ] = None, + user: Optional[str] = None, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + accept_header_override: Optional[GenerateAcceptEnum] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.CreateEmbeddingsResponse: + r"""Submit an embedding request + + Submits an embedding request to the embeddings router + + :param input: + :param model: + :param provider: + :param encoding_format: + :param user: + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param accept_header_override: Override the default accept header for this method + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + + request = models.CreateEmbeddingsRequest( + input=input, + model=model, + provider=utils.get_pydantic_model( + provider, Optional[models.CreateEmbeddingsProvider] + ), + encoding_format=encoding_format, + user=user, + ) + + req = self._build_request( + method="POST", + path="/embeddings", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=True, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value=accept_header_override.value + if accept_header_override is not None + else "application/json;q=1, text/event-stream;q=0", + http_headers=http_headers, + security=self.sdk_configuration.security, + get_serialized_body=lambda: utils.serialize_request_body( + request, False, False, "json", models.CreateEmbeddingsRequest + ), + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = self.do_request( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="createEmbeddings", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=[ + "400", + "401", + "402", + "404", + "429", + "4XX", + "500", + "502", + "503", + "524", + "529", + "5XX", + ], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response( + models.CreateEmbeddingsResponseBody, http_res + ) + if utils.match_response(http_res, "200", "text/event-stream"): + return http_res.text + if utils.match_response(http_res, "400", "application/json"): + response_data = unmarshal_json_response( + errors.BadRequestResponseErrorData, http_res + ) + raise errors.BadRequestResponseError(response_data, http_res) + if utils.match_response(http_res, "401", "application/json"): + response_data = unmarshal_json_response( + errors.UnauthorizedResponseErrorData, http_res + ) + raise errors.UnauthorizedResponseError(response_data, http_res) + if utils.match_response(http_res, "402", "application/json"): + response_data = unmarshal_json_response( + errors.PaymentRequiredResponseErrorData, http_res + ) + raise errors.PaymentRequiredResponseError(response_data, http_res) + if utils.match_response(http_res, "404", "application/json"): + response_data = unmarshal_json_response( + errors.NotFoundResponseErrorData, http_res + ) + raise errors.NotFoundResponseError(response_data, http_res) + if utils.match_response(http_res, "429", "application/json"): + response_data = unmarshal_json_response( + errors.TooManyRequestsResponseErrorData, http_res + ) + raise errors.TooManyRequestsResponseError(response_data, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "502", "application/json"): + response_data = unmarshal_json_response( + errors.BadGatewayResponseErrorData, http_res + ) + raise errors.BadGatewayResponseError(response_data, http_res) + if utils.match_response(http_res, "503", "application/json"): + response_data = unmarshal_json_response( + errors.ServiceUnavailableResponseErrorData, http_res + ) + raise errors.ServiceUnavailableResponseError(response_data, http_res) + if utils.match_response(http_res, "524", "application/json"): + response_data = unmarshal_json_response( + errors.EdgeNetworkTimeoutResponseErrorData, http_res + ) + raise errors.EdgeNetworkTimeoutResponseError(response_data, http_res) + if utils.match_response(http_res, "529", "application/json"): + response_data = unmarshal_json_response( + errors.ProviderOverloadedResponseErrorData, http_res + ) + raise errors.ProviderOverloadedResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) + + async def generate_async( + self, + *, + input: Union[models.Input, models.InputTypedDict], + model: str, + provider: Optional[ + Union[ + models.CreateEmbeddingsProvider, + models.CreateEmbeddingsProviderTypedDict, + ] + ] = None, + encoding_format: Optional[ + Union[models.EncodingFormat, models.EncodingFormatTypedDict] + ] = None, + user: Optional[str] = None, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + accept_header_override: Optional[GenerateAcceptEnum] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.CreateEmbeddingsResponse: + r"""Submit an embedding request + + Submits an embedding request to the embeddings router + + :param input: + :param model: + :param provider: + :param encoding_format: + :param user: + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param accept_header_override: Override the default accept header for this method + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + + request = models.CreateEmbeddingsRequest( + input=input, + model=model, + provider=utils.get_pydantic_model( + provider, Optional[models.CreateEmbeddingsProvider] + ), + encoding_format=encoding_format, + user=user, + ) + + req = self._build_request_async( + method="POST", + path="/embeddings", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=True, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value=accept_header_override.value + if accept_header_override is not None + else "application/json;q=1, text/event-stream;q=0", + http_headers=http_headers, + security=self.sdk_configuration.security, + get_serialized_body=lambda: utils.serialize_request_body( + request, False, False, "json", models.CreateEmbeddingsRequest + ), + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = await self.do_request_async( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="createEmbeddings", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=[ + "400", + "401", + "402", + "404", + "429", + "4XX", + "500", + "502", + "503", + "524", + "529", + "5XX", + ], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response( + models.CreateEmbeddingsResponseBody, http_res + ) + if utils.match_response(http_res, "200", "text/event-stream"): + return http_res.text + if utils.match_response(http_res, "400", "application/json"): + response_data = unmarshal_json_response( + errors.BadRequestResponseErrorData, http_res + ) + raise errors.BadRequestResponseError(response_data, http_res) + if utils.match_response(http_res, "401", "application/json"): + response_data = unmarshal_json_response( + errors.UnauthorizedResponseErrorData, http_res + ) + raise errors.UnauthorizedResponseError(response_data, http_res) + if utils.match_response(http_res, "402", "application/json"): + response_data = unmarshal_json_response( + errors.PaymentRequiredResponseErrorData, http_res + ) + raise errors.PaymentRequiredResponseError(response_data, http_res) + if utils.match_response(http_res, "404", "application/json"): + response_data = unmarshal_json_response( + errors.NotFoundResponseErrorData, http_res + ) + raise errors.NotFoundResponseError(response_data, http_res) + if utils.match_response(http_res, "429", "application/json"): + response_data = unmarshal_json_response( + errors.TooManyRequestsResponseErrorData, http_res + ) + raise errors.TooManyRequestsResponseError(response_data, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "502", "application/json"): + response_data = unmarshal_json_response( + errors.BadGatewayResponseErrorData, http_res + ) + raise errors.BadGatewayResponseError(response_data, http_res) + if utils.match_response(http_res, "503", "application/json"): + response_data = unmarshal_json_response( + errors.ServiceUnavailableResponseErrorData, http_res + ) + raise errors.ServiceUnavailableResponseError(response_data, http_res) + if utils.match_response(http_res, "524", "application/json"): + response_data = unmarshal_json_response( + errors.EdgeNetworkTimeoutResponseErrorData, http_res + ) + raise errors.EdgeNetworkTimeoutResponseError(response_data, http_res) + if utils.match_response(http_res, "529", "application/json"): + response_data = unmarshal_json_response( + errors.ProviderOverloadedResponseErrorData, http_res + ) + raise errors.ProviderOverloadedResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) + + def list_models( + self, + *, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.ModelsListResponse: + r"""List all embeddings models + + Returns a list of all available embeddings models and their properties + + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + req = self._build_request( + method="GET", + path="/embeddings/models", + base_url=base_url, + url_variables=url_variables, + request=None, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = self.do_request( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="listEmbeddingsModels", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=["400", "4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response(models.ModelsListResponse, http_res) + if utils.match_response(http_res, "400", "application/json"): + response_data = unmarshal_json_response( + errors.BadRequestResponseErrorData, http_res + ) + raise errors.BadRequestResponseError(response_data, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) + + async def list_models_async( + self, + *, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.ModelsListResponse: + r"""List all embeddings models + + Returns a list of all available embeddings models and their properties + + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + req = self._build_request_async( + method="GET", + path="/embeddings/models", + base_url=base_url, + url_variables=url_variables, + request=None, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = await self.do_request_async( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="listEmbeddingsModels", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=["400", "4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response(models.ModelsListResponse, http_res) + if utils.match_response(http_res, "400", "application/json"): + response_data = unmarshal_json_response( + errors.BadRequestResponseErrorData, http_res + ) + raise errors.BadRequestResponseError(response_data, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) diff --git a/src/openrouter/endpoints.py b/src/openrouter/endpoints.py new file mode 100644 index 0000000..d1a1c79 --- /dev/null +++ b/src/openrouter/endpoints.py @@ -0,0 +1,383 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from .basesdk import BaseSDK +from openrouter import errors, models, utils +from openrouter._hooks import HookContext +from openrouter.types import OptionalNullable, UNSET +from openrouter.utils import get_security_from_env +from openrouter.utils.unmarshal_json_response import unmarshal_json_response +from typing import Any, Mapping, Optional + + +class Endpoints(BaseSDK): + r"""Endpoint information""" + + def list( + self, + *, + author: str, + slug: str, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.EndpointsListEndpointsResponse: + r"""List all endpoints for a model + + :param author: + :param slug: + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + + request = models.ListEndpointsRequest( + author=author, + slug=slug, + ) + + req = self._build_request( + method="GET", + path="/models/{author}/{slug}/endpoints", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=False, + request_has_path_params=True, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = self.do_request( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="listEndpoints", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=["404", "4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response( + models.EndpointsListEndpointsResponse, http_res + ) + if utils.match_response(http_res, "404", "application/json"): + response_data = unmarshal_json_response( + errors.NotFoundResponseErrorData, http_res + ) + raise errors.NotFoundResponseError(response_data, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) + + async def list_async( + self, + *, + author: str, + slug: str, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.EndpointsListEndpointsResponse: + r"""List all endpoints for a model + + :param author: + :param slug: + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + + request = models.ListEndpointsRequest( + author=author, + slug=slug, + ) + + req = self._build_request_async( + method="GET", + path="/models/{author}/{slug}/endpoints", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=False, + request_has_path_params=True, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = await self.do_request_async( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="listEndpoints", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=["404", "4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response( + models.EndpointsListEndpointsResponse, http_res + ) + if utils.match_response(http_res, "404", "application/json"): + response_data = unmarshal_json_response( + errors.NotFoundResponseErrorData, http_res + ) + raise errors.NotFoundResponseError(response_data, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) + + def list_zdr_endpoints( + self, + *, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.ListEndpointsZdrResponse: + r"""Preview the impact of ZDR on the available endpoints + + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + req = self._build_request( + method="GET", + path="/endpoints/zdr", + base_url=base_url, + url_variables=url_variables, + request=None, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = self.do_request( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="listEndpointsZdr", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=["4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response(models.ListEndpointsZdrResponse, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) + + async def list_zdr_endpoints_async( + self, + *, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.ListEndpointsZdrResponse: + r"""Preview the impact of ZDR on the available endpoints + + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + req = self._build_request_async( + method="GET", + path="/endpoints/zdr", + base_url=base_url, + url_variables=url_variables, + request=None, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = await self.do_request_async( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="listEndpointsZdr", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=["4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response(models.ListEndpointsZdrResponse, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) diff --git a/src/openrouter/errors/__init__.py b/src/openrouter/errors/__init__.py new file mode 100644 index 0000000..b8f32f8 --- /dev/null +++ b/src/openrouter/errors/__init__.py @@ -0,0 +1,177 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from .openroutererror import OpenRouterError +from typing import TYPE_CHECKING +from importlib import import_module +import builtins +import sys + +if TYPE_CHECKING: + from .badgatewayresponse_error import ( + BadGatewayResponseError, + BadGatewayResponseErrorData, + ) + from .badrequestresponse_error import ( + BadRequestResponseError, + BadRequestResponseErrorData, + ) + from .chaterror import ChatError, ChatErrorData + from .edgenetworktimeoutresponse_error import ( + EdgeNetworkTimeoutResponseError, + EdgeNetworkTimeoutResponseErrorData, + ) + from .forbiddenresponse_error import ( + ForbiddenResponseError, + ForbiddenResponseErrorData, + ) + from .internalserverresponse_error import ( + InternalServerResponseError, + InternalServerResponseErrorData, + ) + from .no_response_error import NoResponseError + from .notfoundresponse_error import NotFoundResponseError, NotFoundResponseErrorData + from .openrouterdefaulterror import OpenRouterDefaultError + from .payloadtoolargeresponse_error import ( + PayloadTooLargeResponseError, + PayloadTooLargeResponseErrorData, + ) + from .paymentrequiredresponse_error import ( + PaymentRequiredResponseError, + PaymentRequiredResponseErrorData, + ) + from .provideroverloadedresponse_error import ( + ProviderOverloadedResponseError, + ProviderOverloadedResponseErrorData, + ) + from .requesttimeoutresponse_error import ( + RequestTimeoutResponseError, + RequestTimeoutResponseErrorData, + ) + from .responsevalidationerror import ResponseValidationError + from .serviceunavailableresponse_error import ( + ServiceUnavailableResponseError, + ServiceUnavailableResponseErrorData, + ) + from .toomanyrequestsresponse_error import ( + TooManyRequestsResponseError, + TooManyRequestsResponseErrorData, + ) + from .unauthorizedresponse_error import ( + UnauthorizedResponseError, + UnauthorizedResponseErrorData, + ) + from .unprocessableentityresponse_error import ( + UnprocessableEntityResponseError, + UnprocessableEntityResponseErrorData, + ) + +__all__ = [ + "BadGatewayResponseError", + "BadGatewayResponseErrorData", + "BadRequestResponseError", + "BadRequestResponseErrorData", + "ChatError", + "ChatErrorData", + "EdgeNetworkTimeoutResponseError", + "EdgeNetworkTimeoutResponseErrorData", + "ForbiddenResponseError", + "ForbiddenResponseErrorData", + "InternalServerResponseError", + "InternalServerResponseErrorData", + "NoResponseError", + "NotFoundResponseError", + "NotFoundResponseErrorData", + "OpenRouterDefaultError", + "OpenRouterError", + "PayloadTooLargeResponseError", + "PayloadTooLargeResponseErrorData", + "PaymentRequiredResponseError", + "PaymentRequiredResponseErrorData", + "ProviderOverloadedResponseError", + "ProviderOverloadedResponseErrorData", + "RequestTimeoutResponseError", + "RequestTimeoutResponseErrorData", + "ResponseValidationError", + "ServiceUnavailableResponseError", + "ServiceUnavailableResponseErrorData", + "TooManyRequestsResponseError", + "TooManyRequestsResponseErrorData", + "UnauthorizedResponseError", + "UnauthorizedResponseErrorData", + "UnprocessableEntityResponseError", + "UnprocessableEntityResponseErrorData", +] + +_dynamic_imports: dict[str, str] = { + "BadGatewayResponseError": ".badgatewayresponse_error", + "BadGatewayResponseErrorData": ".badgatewayresponse_error", + "BadRequestResponseError": ".badrequestresponse_error", + "BadRequestResponseErrorData": ".badrequestresponse_error", + "ChatError": ".chaterror", + "ChatErrorData": ".chaterror", + "EdgeNetworkTimeoutResponseError": ".edgenetworktimeoutresponse_error", + "EdgeNetworkTimeoutResponseErrorData": ".edgenetworktimeoutresponse_error", + "ForbiddenResponseError": ".forbiddenresponse_error", + "ForbiddenResponseErrorData": ".forbiddenresponse_error", + "InternalServerResponseError": ".internalserverresponse_error", + "InternalServerResponseErrorData": ".internalserverresponse_error", + "NoResponseError": ".no_response_error", + "NotFoundResponseError": ".notfoundresponse_error", + "NotFoundResponseErrorData": ".notfoundresponse_error", + "OpenRouterDefaultError": ".openrouterdefaulterror", + "PayloadTooLargeResponseError": ".payloadtoolargeresponse_error", + "PayloadTooLargeResponseErrorData": ".payloadtoolargeresponse_error", + "PaymentRequiredResponseError": ".paymentrequiredresponse_error", + "PaymentRequiredResponseErrorData": ".paymentrequiredresponse_error", + "ProviderOverloadedResponseError": ".provideroverloadedresponse_error", + "ProviderOverloadedResponseErrorData": ".provideroverloadedresponse_error", + "RequestTimeoutResponseError": ".requesttimeoutresponse_error", + "RequestTimeoutResponseErrorData": ".requesttimeoutresponse_error", + "ResponseValidationError": ".responsevalidationerror", + "ServiceUnavailableResponseError": ".serviceunavailableresponse_error", + "ServiceUnavailableResponseErrorData": ".serviceunavailableresponse_error", + "TooManyRequestsResponseError": ".toomanyrequestsresponse_error", + "TooManyRequestsResponseErrorData": ".toomanyrequestsresponse_error", + "UnauthorizedResponseError": ".unauthorizedresponse_error", + "UnauthorizedResponseErrorData": ".unauthorizedresponse_error", + "UnprocessableEntityResponseError": ".unprocessableentityresponse_error", + "UnprocessableEntityResponseErrorData": ".unprocessableentityresponse_error", +} + + +def dynamic_import(modname, retries=3): + for attempt in range(retries): + try: + return import_module(modname, __package__) + except KeyError: + # Clear any half-initialized module and retry + sys.modules.pop(modname, None) + if attempt == retries - 1: + break + raise KeyError(f"Failed to import module '{modname}' after {retries} attempts") + + +def __getattr__(attr_name: str) -> object: + module_name = _dynamic_imports.get(attr_name) + if module_name is None: + raise AttributeError( + f"No {attr_name} found in _dynamic_imports for module name -> {__name__} " + ) + + try: + module = dynamic_import(module_name) + result = getattr(module, attr_name) + return result + except ImportError as e: + raise ImportError( + f"Failed to import {attr_name} from {module_name}: {e}" + ) from e + except AttributeError as e: + raise AttributeError( + f"Failed to get {attr_name} from {module_name}: {e}" + ) from e + + +def __dir__(): + lazy_attrs = builtins.list(_dynamic_imports.keys()) + return builtins.sorted(lazy_attrs) diff --git a/src/openrouter/errors/badgatewayresponse_error.py b/src/openrouter/errors/badgatewayresponse_error.py new file mode 100644 index 0000000..b395d6d --- /dev/null +++ b/src/openrouter/errors/badgatewayresponse_error.py @@ -0,0 +1,36 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from dataclasses import dataclass, field +import httpx +from openrouter.errors import OpenRouterError +from openrouter.models import ( + badgatewayresponseerrordata as models_badgatewayresponseerrordata, +) +from openrouter.types import BaseModel, OptionalNullable, UNSET +from typing import Optional + + +class BadGatewayResponseErrorData(BaseModel): + error: models_badgatewayresponseerrordata.BadGatewayResponseErrorData + r"""Error data for BadGatewayResponse""" + + user_id: OptionalNullable[str] = UNSET + + +@dataclass(unsafe_hash=True) +class BadGatewayResponseError(OpenRouterError): + r"""Bad Gateway - Provider/upstream API failure""" + + data: BadGatewayResponseErrorData = field(hash=False) + + def __init__( + self, + data: BadGatewayResponseErrorData, + raw_response: httpx.Response, + body: Optional[str] = None, + ): + fallback = body or raw_response.text + message = str(data.error.message) or fallback + super().__init__(message, raw_response, body) + object.__setattr__(self, "data", data) diff --git a/src/openrouter/errors/badrequestresponse_error.py b/src/openrouter/errors/badrequestresponse_error.py new file mode 100644 index 0000000..f2462cb --- /dev/null +++ b/src/openrouter/errors/badrequestresponse_error.py @@ -0,0 +1,36 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from dataclasses import dataclass, field +import httpx +from openrouter.errors import OpenRouterError +from openrouter.models import ( + badrequestresponseerrordata as models_badrequestresponseerrordata, +) +from openrouter.types import BaseModel, OptionalNullable, UNSET +from typing import Optional + + +class BadRequestResponseErrorData(BaseModel): + error: models_badrequestresponseerrordata.BadRequestResponseErrorData + r"""Error data for BadRequestResponse""" + + user_id: OptionalNullable[str] = UNSET + + +@dataclass(unsafe_hash=True) +class BadRequestResponseError(OpenRouterError): + r"""Bad Request - Invalid request parameters or malformed input""" + + data: BadRequestResponseErrorData = field(hash=False) + + def __init__( + self, + data: BadRequestResponseErrorData, + raw_response: httpx.Response, + body: Optional[str] = None, + ): + fallback = body or raw_response.text + message = str(data.error.message) or fallback + super().__init__(message, raw_response, body) + object.__setattr__(self, "data", data) diff --git a/src/openrouter/errors/chaterror.py b/src/openrouter/errors/chaterror.py new file mode 100644 index 0000000..fdc6324 --- /dev/null +++ b/src/openrouter/errors/chaterror.py @@ -0,0 +1,29 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from dataclasses import dataclass, field +import httpx +from openrouter.errors import OpenRouterError +from openrouter.models import chaterror as models_chaterror +from openrouter.types import BaseModel +from typing import Optional + + +class ChatErrorData(BaseModel): + error: models_chaterror.ChatErrorError + + +@dataclass(unsafe_hash=True) +class ChatError(OpenRouterError): + data: ChatErrorData = field(hash=False) + + def __init__( + self, + data: ChatErrorData, + raw_response: httpx.Response, + body: Optional[str] = None, + ): + fallback = body or raw_response.text + message = str(data.error.message) or fallback + super().__init__(message, raw_response, body) + object.__setattr__(self, "data", data) diff --git a/src/openrouter/errors/edgenetworktimeoutresponse_error.py b/src/openrouter/errors/edgenetworktimeoutresponse_error.py new file mode 100644 index 0000000..0970f19 --- /dev/null +++ b/src/openrouter/errors/edgenetworktimeoutresponse_error.py @@ -0,0 +1,38 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from dataclasses import dataclass, field +import httpx +from openrouter.errors import OpenRouterError +from openrouter.models import ( + edgenetworktimeoutresponseerrordata as models_edgenetworktimeoutresponseerrordata, +) +from openrouter.types import BaseModel, OptionalNullable, UNSET +from typing import Optional + + +class EdgeNetworkTimeoutResponseErrorData(BaseModel): + error: ( + models_edgenetworktimeoutresponseerrordata.EdgeNetworkTimeoutResponseErrorData + ) + r"""Error data for EdgeNetworkTimeoutResponse""" + + user_id: OptionalNullable[str] = UNSET + + +@dataclass(unsafe_hash=True) +class EdgeNetworkTimeoutResponseError(OpenRouterError): + r"""Infrastructure Timeout - Provider request timed out at edge network""" + + data: EdgeNetworkTimeoutResponseErrorData = field(hash=False) + + def __init__( + self, + data: EdgeNetworkTimeoutResponseErrorData, + raw_response: httpx.Response, + body: Optional[str] = None, + ): + fallback = body or raw_response.text + message = str(data.error.message) or fallback + super().__init__(message, raw_response, body) + object.__setattr__(self, "data", data) diff --git a/src/openrouter/errors/forbiddenresponse_error.py b/src/openrouter/errors/forbiddenresponse_error.py new file mode 100644 index 0000000..41c6e7c --- /dev/null +++ b/src/openrouter/errors/forbiddenresponse_error.py @@ -0,0 +1,36 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from dataclasses import dataclass, field +import httpx +from openrouter.errors import OpenRouterError +from openrouter.models import ( + forbiddenresponseerrordata as models_forbiddenresponseerrordata, +) +from openrouter.types import BaseModel, OptionalNullable, UNSET +from typing import Optional + + +class ForbiddenResponseErrorData(BaseModel): + error: models_forbiddenresponseerrordata.ForbiddenResponseErrorData + r"""Error data for ForbiddenResponse""" + + user_id: OptionalNullable[str] = UNSET + + +@dataclass(unsafe_hash=True) +class ForbiddenResponseError(OpenRouterError): + r"""Forbidden - Authentication successful but insufficient permissions""" + + data: ForbiddenResponseErrorData = field(hash=False) + + def __init__( + self, + data: ForbiddenResponseErrorData, + raw_response: httpx.Response, + body: Optional[str] = None, + ): + fallback = body or raw_response.text + message = str(data.error.message) or fallback + super().__init__(message, raw_response, body) + object.__setattr__(self, "data", data) diff --git a/src/openrouter/errors/internalserverresponse_error.py b/src/openrouter/errors/internalserverresponse_error.py new file mode 100644 index 0000000..2cee3a2 --- /dev/null +++ b/src/openrouter/errors/internalserverresponse_error.py @@ -0,0 +1,36 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from dataclasses import dataclass, field +import httpx +from openrouter.errors import OpenRouterError +from openrouter.models import ( + internalserverresponseerrordata as models_internalserverresponseerrordata, +) +from openrouter.types import BaseModel, OptionalNullable, UNSET +from typing import Optional + + +class InternalServerResponseErrorData(BaseModel): + error: models_internalserverresponseerrordata.InternalServerResponseErrorData + r"""Error data for InternalServerResponse""" + + user_id: OptionalNullable[str] = UNSET + + +@dataclass(unsafe_hash=True) +class InternalServerResponseError(OpenRouterError): + r"""Internal Server Error - Unexpected server error""" + + data: InternalServerResponseErrorData = field(hash=False) + + def __init__( + self, + data: InternalServerResponseErrorData, + raw_response: httpx.Response, + body: Optional[str] = None, + ): + fallback = body or raw_response.text + message = str(data.error.message) or fallback + super().__init__(message, raw_response, body) + object.__setattr__(self, "data", data) diff --git a/src/openrouter/errors/no_response_error.py b/src/openrouter/errors/no_response_error.py new file mode 100644 index 0000000..1deab64 --- /dev/null +++ b/src/openrouter/errors/no_response_error.py @@ -0,0 +1,17 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from dataclasses import dataclass + + +@dataclass(unsafe_hash=True) +class NoResponseError(Exception): + """Error raised when no HTTP response is received from the server.""" + + message: str + + def __init__(self, message: str = "No response received"): + object.__setattr__(self, "message", message) + super().__init__(message) + + def __str__(self): + return self.message diff --git a/src/openrouter/errors/notfoundresponse_error.py b/src/openrouter/errors/notfoundresponse_error.py new file mode 100644 index 0000000..6a51fb1 --- /dev/null +++ b/src/openrouter/errors/notfoundresponse_error.py @@ -0,0 +1,36 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from dataclasses import dataclass, field +import httpx +from openrouter.errors import OpenRouterError +from openrouter.models import ( + notfoundresponseerrordata as models_notfoundresponseerrordata, +) +from openrouter.types import BaseModel, OptionalNullable, UNSET +from typing import Optional + + +class NotFoundResponseErrorData(BaseModel): + error: models_notfoundresponseerrordata.NotFoundResponseErrorData + r"""Error data for NotFoundResponse""" + + user_id: OptionalNullable[str] = UNSET + + +@dataclass(unsafe_hash=True) +class NotFoundResponseError(OpenRouterError): + r"""Not Found - Resource does not exist""" + + data: NotFoundResponseErrorData = field(hash=False) + + def __init__( + self, + data: NotFoundResponseErrorData, + raw_response: httpx.Response, + body: Optional[str] = None, + ): + fallback = body or raw_response.text + message = str(data.error.message) or fallback + super().__init__(message, raw_response, body) + object.__setattr__(self, "data", data) diff --git a/src/openrouter/errors/openrouterdefaulterror.py b/src/openrouter/errors/openrouterdefaulterror.py new file mode 100644 index 0000000..385e3ec --- /dev/null +++ b/src/openrouter/errors/openrouterdefaulterror.py @@ -0,0 +1,40 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +import httpx +from typing import Optional +from dataclasses import dataclass + +from openrouter.errors import OpenRouterError + +MAX_MESSAGE_LEN = 10_000 + + +@dataclass(unsafe_hash=True) +class OpenRouterDefaultError(OpenRouterError): + """The fallback error class if no more specific error class is matched.""" + + def __init__( + self, message: str, raw_response: httpx.Response, body: Optional[str] = None + ): + body_display = body or raw_response.text or '""' + + if message: + message += ": " + message += f"Status {raw_response.status_code}" + + headers = raw_response.headers + content_type = headers.get("content-type", '""') + if content_type != "application/json": + if " " in content_type: + content_type = f'"{content_type}"' + message += f" Content-Type {content_type}" + + if len(body_display) > MAX_MESSAGE_LEN: + truncated = body_display[:MAX_MESSAGE_LEN] + remaining = len(body_display) - MAX_MESSAGE_LEN + body_display = f"{truncated}...and {remaining} more chars" + + message += f". Body: {body_display}" + message = message.strip() + + super().__init__(message, raw_response, body) diff --git a/src/openrouter/errors/openroutererror.py b/src/openrouter/errors/openroutererror.py new file mode 100644 index 0000000..a3218e9 --- /dev/null +++ b/src/openrouter/errors/openroutererror.py @@ -0,0 +1,30 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +import httpx +from typing import Optional +from dataclasses import dataclass, field + + +@dataclass(unsafe_hash=True) +class OpenRouterError(Exception): + """The base class for all HTTP error responses.""" + + message: str + status_code: int + body: str + headers: httpx.Headers = field(hash=False) + raw_response: httpx.Response = field(hash=False) + + def __init__( + self, message: str, raw_response: httpx.Response, body: Optional[str] = None + ): + object.__setattr__(self, "message", message) + object.__setattr__(self, "status_code", raw_response.status_code) + object.__setattr__( + self, "body", body if body is not None else raw_response.text + ) + object.__setattr__(self, "headers", raw_response.headers) + object.__setattr__(self, "raw_response", raw_response) + + def __str__(self): + return self.message diff --git a/src/openrouter/errors/payloadtoolargeresponse_error.py b/src/openrouter/errors/payloadtoolargeresponse_error.py new file mode 100644 index 0000000..993dd6f --- /dev/null +++ b/src/openrouter/errors/payloadtoolargeresponse_error.py @@ -0,0 +1,36 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from dataclasses import dataclass, field +import httpx +from openrouter.errors import OpenRouterError +from openrouter.models import ( + payloadtoolargeresponseerrordata as models_payloadtoolargeresponseerrordata, +) +from openrouter.types import BaseModel, OptionalNullable, UNSET +from typing import Optional + + +class PayloadTooLargeResponseErrorData(BaseModel): + error: models_payloadtoolargeresponseerrordata.PayloadTooLargeResponseErrorData + r"""Error data for PayloadTooLargeResponse""" + + user_id: OptionalNullable[str] = UNSET + + +@dataclass(unsafe_hash=True) +class PayloadTooLargeResponseError(OpenRouterError): + r"""Payload Too Large - Request payload exceeds size limits""" + + data: PayloadTooLargeResponseErrorData = field(hash=False) + + def __init__( + self, + data: PayloadTooLargeResponseErrorData, + raw_response: httpx.Response, + body: Optional[str] = None, + ): + fallback = body or raw_response.text + message = str(data.error.message) or fallback + super().__init__(message, raw_response, body) + object.__setattr__(self, "data", data) diff --git a/src/openrouter/errors/paymentrequiredresponse_error.py b/src/openrouter/errors/paymentrequiredresponse_error.py new file mode 100644 index 0000000..a7f8d72 --- /dev/null +++ b/src/openrouter/errors/paymentrequiredresponse_error.py @@ -0,0 +1,36 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from dataclasses import dataclass, field +import httpx +from openrouter.errors import OpenRouterError +from openrouter.models import ( + paymentrequiredresponseerrordata as models_paymentrequiredresponseerrordata, +) +from openrouter.types import BaseModel, OptionalNullable, UNSET +from typing import Optional + + +class PaymentRequiredResponseErrorData(BaseModel): + error: models_paymentrequiredresponseerrordata.PaymentRequiredResponseErrorData + r"""Error data for PaymentRequiredResponse""" + + user_id: OptionalNullable[str] = UNSET + + +@dataclass(unsafe_hash=True) +class PaymentRequiredResponseError(OpenRouterError): + r"""Payment Required - Insufficient credits or quota to complete request""" + + data: PaymentRequiredResponseErrorData = field(hash=False) + + def __init__( + self, + data: PaymentRequiredResponseErrorData, + raw_response: httpx.Response, + body: Optional[str] = None, + ): + fallback = body or raw_response.text + message = str(data.error.message) or fallback + super().__init__(message, raw_response, body) + object.__setattr__(self, "data", data) diff --git a/src/openrouter/errors/provideroverloadedresponse_error.py b/src/openrouter/errors/provideroverloadedresponse_error.py new file mode 100644 index 0000000..3b85954 --- /dev/null +++ b/src/openrouter/errors/provideroverloadedresponse_error.py @@ -0,0 +1,38 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from dataclasses import dataclass, field +import httpx +from openrouter.errors import OpenRouterError +from openrouter.models import ( + provideroverloadedresponseerrordata as models_provideroverloadedresponseerrordata, +) +from openrouter.types import BaseModel, OptionalNullable, UNSET +from typing import Optional + + +class ProviderOverloadedResponseErrorData(BaseModel): + error: ( + models_provideroverloadedresponseerrordata.ProviderOverloadedResponseErrorData + ) + r"""Error data for ProviderOverloadedResponse""" + + user_id: OptionalNullable[str] = UNSET + + +@dataclass(unsafe_hash=True) +class ProviderOverloadedResponseError(OpenRouterError): + r"""Provider Overloaded - Provider is temporarily overloaded""" + + data: ProviderOverloadedResponseErrorData = field(hash=False) + + def __init__( + self, + data: ProviderOverloadedResponseErrorData, + raw_response: httpx.Response, + body: Optional[str] = None, + ): + fallback = body or raw_response.text + message = str(data.error.message) or fallback + super().__init__(message, raw_response, body) + object.__setattr__(self, "data", data) diff --git a/src/openrouter/errors/requesttimeoutresponse_error.py b/src/openrouter/errors/requesttimeoutresponse_error.py new file mode 100644 index 0000000..824b253 --- /dev/null +++ b/src/openrouter/errors/requesttimeoutresponse_error.py @@ -0,0 +1,36 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from dataclasses import dataclass, field +import httpx +from openrouter.errors import OpenRouterError +from openrouter.models import ( + requesttimeoutresponseerrordata as models_requesttimeoutresponseerrordata, +) +from openrouter.types import BaseModel, OptionalNullable, UNSET +from typing import Optional + + +class RequestTimeoutResponseErrorData(BaseModel): + error: models_requesttimeoutresponseerrordata.RequestTimeoutResponseErrorData + r"""Error data for RequestTimeoutResponse""" + + user_id: OptionalNullable[str] = UNSET + + +@dataclass(unsafe_hash=True) +class RequestTimeoutResponseError(OpenRouterError): + r"""Request Timeout - Operation exceeded time limit""" + + data: RequestTimeoutResponseErrorData = field(hash=False) + + def __init__( + self, + data: RequestTimeoutResponseErrorData, + raw_response: httpx.Response, + body: Optional[str] = None, + ): + fallback = body or raw_response.text + message = str(data.error.message) or fallback + super().__init__(message, raw_response, body) + object.__setattr__(self, "data", data) diff --git a/src/openrouter/errors/responsevalidationerror.py b/src/openrouter/errors/responsevalidationerror.py new file mode 100644 index 0000000..8d0d6fd --- /dev/null +++ b/src/openrouter/errors/responsevalidationerror.py @@ -0,0 +1,27 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +import httpx +from typing import Optional +from dataclasses import dataclass + +from openrouter.errors import OpenRouterError + + +@dataclass(unsafe_hash=True) +class ResponseValidationError(OpenRouterError): + """Error raised when there is a type mismatch between the response data and the expected Pydantic model.""" + + def __init__( + self, + message: str, + raw_response: httpx.Response, + cause: Exception, + body: Optional[str] = None, + ): + message = f"{message}: {cause}" + super().__init__(message, raw_response, body) + + @property + def cause(self): + """Normally the Pydantic ValidationError""" + return self.__cause__ diff --git a/src/openrouter/errors/serviceunavailableresponse_error.py b/src/openrouter/errors/serviceunavailableresponse_error.py new file mode 100644 index 0000000..717120d --- /dev/null +++ b/src/openrouter/errors/serviceunavailableresponse_error.py @@ -0,0 +1,38 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from dataclasses import dataclass, field +import httpx +from openrouter.errors import OpenRouterError +from openrouter.models import ( + serviceunavailableresponseerrordata as models_serviceunavailableresponseerrordata, +) +from openrouter.types import BaseModel, OptionalNullable, UNSET +from typing import Optional + + +class ServiceUnavailableResponseErrorData(BaseModel): + error: ( + models_serviceunavailableresponseerrordata.ServiceUnavailableResponseErrorData + ) + r"""Error data for ServiceUnavailableResponse""" + + user_id: OptionalNullable[str] = UNSET + + +@dataclass(unsafe_hash=True) +class ServiceUnavailableResponseError(OpenRouterError): + r"""Service Unavailable - Service temporarily unavailable""" + + data: ServiceUnavailableResponseErrorData = field(hash=False) + + def __init__( + self, + data: ServiceUnavailableResponseErrorData, + raw_response: httpx.Response, + body: Optional[str] = None, + ): + fallback = body or raw_response.text + message = str(data.error.message) or fallback + super().__init__(message, raw_response, body) + object.__setattr__(self, "data", data) diff --git a/src/openrouter/errors/toomanyrequestsresponse_error.py b/src/openrouter/errors/toomanyrequestsresponse_error.py new file mode 100644 index 0000000..e5f68e7 --- /dev/null +++ b/src/openrouter/errors/toomanyrequestsresponse_error.py @@ -0,0 +1,36 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from dataclasses import dataclass, field +import httpx +from openrouter.errors import OpenRouterError +from openrouter.models import ( + toomanyrequestsresponseerrordata as models_toomanyrequestsresponseerrordata, +) +from openrouter.types import BaseModel, OptionalNullable, UNSET +from typing import Optional + + +class TooManyRequestsResponseErrorData(BaseModel): + error: models_toomanyrequestsresponseerrordata.TooManyRequestsResponseErrorData + r"""Error data for TooManyRequestsResponse""" + + user_id: OptionalNullable[str] = UNSET + + +@dataclass(unsafe_hash=True) +class TooManyRequestsResponseError(OpenRouterError): + r"""Too Many Requests - Rate limit exceeded""" + + data: TooManyRequestsResponseErrorData = field(hash=False) + + def __init__( + self, + data: TooManyRequestsResponseErrorData, + raw_response: httpx.Response, + body: Optional[str] = None, + ): + fallback = body or raw_response.text + message = str(data.error.message) or fallback + super().__init__(message, raw_response, body) + object.__setattr__(self, "data", data) diff --git a/src/openrouter/errors/unauthorizedresponse_error.py b/src/openrouter/errors/unauthorizedresponse_error.py new file mode 100644 index 0000000..3c7e981 --- /dev/null +++ b/src/openrouter/errors/unauthorizedresponse_error.py @@ -0,0 +1,36 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from dataclasses import dataclass, field +import httpx +from openrouter.errors import OpenRouterError +from openrouter.models import ( + unauthorizedresponseerrordata as models_unauthorizedresponseerrordata, +) +from openrouter.types import BaseModel, OptionalNullable, UNSET +from typing import Optional + + +class UnauthorizedResponseErrorData(BaseModel): + error: models_unauthorizedresponseerrordata.UnauthorizedResponseErrorData + r"""Error data for UnauthorizedResponse""" + + user_id: OptionalNullable[str] = UNSET + + +@dataclass(unsafe_hash=True) +class UnauthorizedResponseError(OpenRouterError): + r"""Unauthorized - Authentication required or invalid credentials""" + + data: UnauthorizedResponseErrorData = field(hash=False) + + def __init__( + self, + data: UnauthorizedResponseErrorData, + raw_response: httpx.Response, + body: Optional[str] = None, + ): + fallback = body or raw_response.text + message = str(data.error.message) or fallback + super().__init__(message, raw_response, body) + object.__setattr__(self, "data", data) diff --git a/src/openrouter/errors/unprocessableentityresponse_error.py b/src/openrouter/errors/unprocessableentityresponse_error.py new file mode 100644 index 0000000..587ba9b --- /dev/null +++ b/src/openrouter/errors/unprocessableentityresponse_error.py @@ -0,0 +1,38 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from dataclasses import dataclass, field +import httpx +from openrouter.errors import OpenRouterError +from openrouter.models import ( + unprocessableentityresponseerrordata as models_unprocessableentityresponseerrordata, +) +from openrouter.types import BaseModel, OptionalNullable, UNSET +from typing import Optional + + +class UnprocessableEntityResponseErrorData(BaseModel): + error: ( + models_unprocessableentityresponseerrordata.UnprocessableEntityResponseErrorData + ) + r"""Error data for UnprocessableEntityResponse""" + + user_id: OptionalNullable[str] = UNSET + + +@dataclass(unsafe_hash=True) +class UnprocessableEntityResponseError(OpenRouterError): + r"""Unprocessable Entity - Semantic validation failure""" + + data: UnprocessableEntityResponseErrorData = field(hash=False) + + def __init__( + self, + data: UnprocessableEntityResponseErrorData, + raw_response: httpx.Response, + body: Optional[str] = None, + ): + fallback = body or raw_response.text + message = str(data.error.message) or fallback + super().__init__(message, raw_response, body) + object.__setattr__(self, "data", data) diff --git a/src/openrouter/generations.py b/src/openrouter/generations.py new file mode 100644 index 0000000..4c38843 --- /dev/null +++ b/src/openrouter/generations.py @@ -0,0 +1,287 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from .basesdk import BaseSDK +from openrouter import errors, models, utils +from openrouter._hooks import HookContext +from openrouter.types import OptionalNullable, UNSET +from openrouter.utils import get_security_from_env +from openrouter.utils.unmarshal_json_response import unmarshal_json_response +from typing import Any, Mapping, Optional + + +class Generations(BaseSDK): + r"""Generation history endpoints""" + + def get_generation( + self, + *, + id: str, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.GetGenerationResponse: + r"""Get request & usage metadata for a generation + + :param id: + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + + request = models.GetGenerationRequest( + id=id, + ) + + req = self._build_request( + method="GET", + path="/generation", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = self.do_request( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="getGeneration", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=[ + "401", + "402", + "404", + "429", + "4XX", + "500", + "502", + "524", + "529", + "5XX", + ], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response(models.GetGenerationResponse, http_res) + if utils.match_response(http_res, "401", "application/json"): + response_data = unmarshal_json_response( + errors.UnauthorizedResponseErrorData, http_res + ) + raise errors.UnauthorizedResponseError(response_data, http_res) + if utils.match_response(http_res, "402", "application/json"): + response_data = unmarshal_json_response( + errors.PaymentRequiredResponseErrorData, http_res + ) + raise errors.PaymentRequiredResponseError(response_data, http_res) + if utils.match_response(http_res, "404", "application/json"): + response_data = unmarshal_json_response( + errors.NotFoundResponseErrorData, http_res + ) + raise errors.NotFoundResponseError(response_data, http_res) + if utils.match_response(http_res, "429", "application/json"): + response_data = unmarshal_json_response( + errors.TooManyRequestsResponseErrorData, http_res + ) + raise errors.TooManyRequestsResponseError(response_data, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "502", "application/json"): + response_data = unmarshal_json_response( + errors.BadGatewayResponseErrorData, http_res + ) + raise errors.BadGatewayResponseError(response_data, http_res) + if utils.match_response(http_res, "524", "application/json"): + response_data = unmarshal_json_response( + errors.EdgeNetworkTimeoutResponseErrorData, http_res + ) + raise errors.EdgeNetworkTimeoutResponseError(response_data, http_res) + if utils.match_response(http_res, "529", "application/json"): + response_data = unmarshal_json_response( + errors.ProviderOverloadedResponseErrorData, http_res + ) + raise errors.ProviderOverloadedResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) + + async def get_generation_async( + self, + *, + id: str, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.GetGenerationResponse: + r"""Get request & usage metadata for a generation + + :param id: + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + + request = models.GetGenerationRequest( + id=id, + ) + + req = self._build_request_async( + method="GET", + path="/generation", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = await self.do_request_async( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="getGeneration", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=[ + "401", + "402", + "404", + "429", + "4XX", + "500", + "502", + "524", + "529", + "5XX", + ], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response(models.GetGenerationResponse, http_res) + if utils.match_response(http_res, "401", "application/json"): + response_data = unmarshal_json_response( + errors.UnauthorizedResponseErrorData, http_res + ) + raise errors.UnauthorizedResponseError(response_data, http_res) + if utils.match_response(http_res, "402", "application/json"): + response_data = unmarshal_json_response( + errors.PaymentRequiredResponseErrorData, http_res + ) + raise errors.PaymentRequiredResponseError(response_data, http_res) + if utils.match_response(http_res, "404", "application/json"): + response_data = unmarshal_json_response( + errors.NotFoundResponseErrorData, http_res + ) + raise errors.NotFoundResponseError(response_data, http_res) + if utils.match_response(http_res, "429", "application/json"): + response_data = unmarshal_json_response( + errors.TooManyRequestsResponseErrorData, http_res + ) + raise errors.TooManyRequestsResponseError(response_data, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "502", "application/json"): + response_data = unmarshal_json_response( + errors.BadGatewayResponseErrorData, http_res + ) + raise errors.BadGatewayResponseError(response_data, http_res) + if utils.match_response(http_res, "524", "application/json"): + response_data = unmarshal_json_response( + errors.EdgeNetworkTimeoutResponseErrorData, http_res + ) + raise errors.EdgeNetworkTimeoutResponseError(response_data, http_res) + if utils.match_response(http_res, "529", "application/json"): + response_data = unmarshal_json_response( + errors.ProviderOverloadedResponseErrorData, http_res + ) + raise errors.ProviderOverloadedResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) diff --git a/src/openrouter/httpclient.py b/src/openrouter/httpclient.py new file mode 100644 index 0000000..89560b5 --- /dev/null +++ b/src/openrouter/httpclient.py @@ -0,0 +1,125 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +# pyright: reportReturnType = false +import asyncio +from typing_extensions import Protocol, runtime_checkable +import httpx +from typing import Any, Optional, Union + + +@runtime_checkable +class HttpClient(Protocol): + def send( + self, + request: httpx.Request, + *, + stream: bool = False, + auth: Union[ + httpx._types.AuthTypes, httpx._client.UseClientDefault, None + ] = httpx.USE_CLIENT_DEFAULT, + follow_redirects: Union[ + bool, httpx._client.UseClientDefault + ] = httpx.USE_CLIENT_DEFAULT, + ) -> httpx.Response: + pass + + def build_request( + self, + method: str, + url: httpx._types.URLTypes, + *, + content: Optional[httpx._types.RequestContent] = None, + data: Optional[httpx._types.RequestData] = None, + files: Optional[httpx._types.RequestFiles] = None, + json: Optional[Any] = None, + params: Optional[httpx._types.QueryParamTypes] = None, + headers: Optional[httpx._types.HeaderTypes] = None, + cookies: Optional[httpx._types.CookieTypes] = None, + timeout: Union[ + httpx._types.TimeoutTypes, httpx._client.UseClientDefault + ] = httpx.USE_CLIENT_DEFAULT, + extensions: Optional[httpx._types.RequestExtensions] = None, + ) -> httpx.Request: + pass + + def close(self) -> None: + pass + + +@runtime_checkable +class AsyncHttpClient(Protocol): + async def send( + self, + request: httpx.Request, + *, + stream: bool = False, + auth: Union[ + httpx._types.AuthTypes, httpx._client.UseClientDefault, None + ] = httpx.USE_CLIENT_DEFAULT, + follow_redirects: Union[ + bool, httpx._client.UseClientDefault + ] = httpx.USE_CLIENT_DEFAULT, + ) -> httpx.Response: + pass + + def build_request( + self, + method: str, + url: httpx._types.URLTypes, + *, + content: Optional[httpx._types.RequestContent] = None, + data: Optional[httpx._types.RequestData] = None, + files: Optional[httpx._types.RequestFiles] = None, + json: Optional[Any] = None, + params: Optional[httpx._types.QueryParamTypes] = None, + headers: Optional[httpx._types.HeaderTypes] = None, + cookies: Optional[httpx._types.CookieTypes] = None, + timeout: Union[ + httpx._types.TimeoutTypes, httpx._client.UseClientDefault + ] = httpx.USE_CLIENT_DEFAULT, + extensions: Optional[httpx._types.RequestExtensions] = None, + ) -> httpx.Request: + pass + + async def aclose(self) -> None: + pass + + +class ClientOwner(Protocol): + client: Union[HttpClient, None] + async_client: Union[AsyncHttpClient, None] + + +def close_clients( + owner: ClientOwner, + sync_client: Union[HttpClient, None], + sync_client_supplied: bool, + async_client: Union[AsyncHttpClient, None], + async_client_supplied: bool, +) -> None: + """ + A finalizer function that is meant to be used with weakref.finalize to close + httpx clients used by an SDK so that underlying resources can be garbage + collected. + """ + + # Unset the client/async_client properties so there are no more references + # to them from the owning SDK instance and they can be reaped. + owner.client = None + owner.async_client = None + if sync_client is not None and not sync_client_supplied: + try: + sync_client.close() + except Exception: + pass + + if async_client is not None and not async_client_supplied: + try: + loop = asyncio.get_running_loop() + asyncio.run_coroutine_threadsafe(async_client.aclose(), loop) + except RuntimeError: + try: + asyncio.run(async_client.aclose()) + except RuntimeError: + # best effort + pass diff --git a/src/openrouter/models/__init__.py b/src/openrouter/models/__init__.py new file mode 100644 index 0000000..a9df123 --- /dev/null +++ b/src/openrouter/models/__init__.py @@ -0,0 +1,2463 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from typing import TYPE_CHECKING +from importlib import import_module +import builtins +import sys + +if TYPE_CHECKING: + from .activityitem import ActivityItem, ActivityItemTypedDict + from .assistantmessage import ( + AssistantMessage, + AssistantMessageContent, + AssistantMessageContentTypedDict, + AssistantMessageTypedDict, + ) + from .badgatewayresponseerrordata import ( + BadGatewayResponseErrorData, + BadGatewayResponseErrorDataTypedDict, + ) + from .badrequestresponseerrordata import ( + BadRequestResponseErrorData, + BadRequestResponseErrorDataTypedDict, + ) + from .chatcompletionfinishreason import ChatCompletionFinishReason + from .chaterror import ChatErrorError, ChatErrorErrorTypedDict, Code, CodeTypedDict + from .chatgenerationparams import ( + ChatGenerationParams, + ChatGenerationParamsResponseFormatJSONObject, + ChatGenerationParamsResponseFormatJSONObjectTypedDict, + ChatGenerationParamsResponseFormatPython, + ChatGenerationParamsResponseFormatPythonTypedDict, + ChatGenerationParamsResponseFormatText, + ChatGenerationParamsResponseFormatTextTypedDict, + ChatGenerationParamsResponseFormatUnion, + ChatGenerationParamsResponseFormatUnionTypedDict, + ChatGenerationParamsStop, + ChatGenerationParamsStopTypedDict, + ChatGenerationParamsTypedDict, + Effort, + Reasoning, + ReasoningTypedDict, + ) + from .chatgenerationtokenusage import ( + ChatGenerationTokenUsage, + ChatGenerationTokenUsageTypedDict, + CompletionTokensDetails, + CompletionTokensDetailsTypedDict, + PromptTokensDetails, + PromptTokensDetailsTypedDict, + ) + from .chatmessagecontentitem import ( + ChatMessageContentItem, + ChatMessageContentItemTypedDict, + ) + from .chatmessagecontentitemaudio import ( + ChatMessageContentItemAudio, + ChatMessageContentItemAudioFormat, + ChatMessageContentItemAudioInputAudio, + ChatMessageContentItemAudioInputAudioTypedDict, + ChatMessageContentItemAudioTypedDict, + ) + from .chatmessagecontentitemimage import ( + ChatMessageContentItemImage, + ChatMessageContentItemImageDetail, + ChatMessageContentItemImageTypedDict, + ImageURL, + ImageURLTypedDict, + ) + from .chatmessagecontentitemtext import ( + ChatMessageContentItemText, + ChatMessageContentItemTextTypedDict, + ) + from .chatmessagecontentitemvideo import ( + ChatMessageContentItemVideo, + ChatMessageContentItemVideoTypedDict, + VideoURL, + VideoURLTypedDict, + ) + from .chatmessagetokenlogprob import ( + ChatMessageTokenLogprob, + ChatMessageTokenLogprobTypedDict, + TopLogprob, + TopLogprobTypedDict, + ) + from .chatmessagetokenlogprobs import ( + ChatMessageTokenLogprobs, + ChatMessageTokenLogprobsTypedDict, + ) + from .chatmessagetoolcall import ( + ChatMessageToolCall, + ChatMessageToolCallFunction, + ChatMessageToolCallFunctionTypedDict, + ChatMessageToolCallTypedDict, + ) + from .chatresponse import ChatResponse, ChatResponseTypedDict + from .chatresponsechoice import ChatResponseChoice, ChatResponseChoiceTypedDict + from .chatstreamingchoice import ChatStreamingChoice, ChatStreamingChoiceTypedDict + from .chatstreamingmessagechunk import ( + ChatStreamingMessageChunk, + ChatStreamingMessageChunkRole, + ChatStreamingMessageChunkTypedDict, + ) + from .chatstreamingmessagetoolcall import ( + ChatStreamingMessageToolCall, + ChatStreamingMessageToolCallFunction, + ChatStreamingMessageToolCallFunctionTypedDict, + ChatStreamingMessageToolCallTypedDict, + ) + from .chatstreamingresponsechunk import ( + ChatStreamingResponseChunk, + ChatStreamingResponseChunkData, + ChatStreamingResponseChunkDataTypedDict, + ChatStreamingResponseChunkError, + ChatStreamingResponseChunkErrorTypedDict, + ChatStreamingResponseChunkTypedDict, + ) + from .chatstreamoptions import ChatStreamOptions, ChatStreamOptionsTypedDict + from .completionchoice import ( + CompletionChoice, + CompletionChoiceTypedDict, + CompletionFinishReason, + ) + from .completioncreateparams import ( + CompletionCreateParams, + CompletionCreateParamsResponseFormatJSONObject, + CompletionCreateParamsResponseFormatJSONObjectTypedDict, + CompletionCreateParamsResponseFormatPython, + CompletionCreateParamsResponseFormatPythonTypedDict, + CompletionCreateParamsResponseFormatText, + CompletionCreateParamsResponseFormatTextTypedDict, + CompletionCreateParamsResponseFormatUnion, + CompletionCreateParamsResponseFormatUnionTypedDict, + CompletionCreateParamsStop, + CompletionCreateParamsStopTypedDict, + CompletionCreateParamsTypedDict, + Prompt, + PromptTypedDict, + StreamOptions, + StreamOptionsTypedDict, + ) + from .completionlogprobs import CompletionLogprobs, CompletionLogprobsTypedDict + from .completionresponse import CompletionResponse, CompletionResponseTypedDict + from .completionusage import CompletionUsage, CompletionUsageTypedDict + from .createauthkeyscodeop import ( + CreateAuthKeysCodeCodeChallengeMethod, + CreateAuthKeysCodeData, + CreateAuthKeysCodeDataTypedDict, + CreateAuthKeysCodeRequest, + CreateAuthKeysCodeRequestTypedDict, + CreateAuthKeysCodeResponse, + CreateAuthKeysCodeResponseTypedDict, + ) + from .createchargerequest import ( + ChainID, + CreateChargeRequest, + CreateChargeRequestTypedDict, + ) + from .createcoinbasechargeop import ( + CallData, + CallDataTypedDict, + CreateCoinbaseChargeData, + CreateCoinbaseChargeDataTypedDict, + CreateCoinbaseChargeResponse, + CreateCoinbaseChargeResponseTypedDict, + CreateCoinbaseChargeSecurity, + CreateCoinbaseChargeSecurityTypedDict, + Metadata, + MetadataTypedDict, + TransferIntent, + TransferIntentTypedDict, + Web3Data, + Web3DataTypedDict, + ) + from .createembeddingsop import ( + CreateEmbeddingsData, + CreateEmbeddingsDataCollection, + CreateEmbeddingsDataTypedDict, + CreateEmbeddingsIgnore, + CreateEmbeddingsIgnoreTypedDict, + CreateEmbeddingsMaxPrice, + CreateEmbeddingsMaxPriceTypedDict, + CreateEmbeddingsObject, + CreateEmbeddingsOnly, + CreateEmbeddingsOnlyTypedDict, + CreateEmbeddingsOrder, + CreateEmbeddingsOrderTypedDict, + CreateEmbeddingsProvider, + CreateEmbeddingsProviderTypedDict, + CreateEmbeddingsRequest, + CreateEmbeddingsRequestTypedDict, + CreateEmbeddingsResponse, + CreateEmbeddingsResponseBody, + CreateEmbeddingsResponseBodyTypedDict, + CreateEmbeddingsResponseTypedDict, + CreateEmbeddingsSort, + Embedding, + EmbeddingTypedDict, + EncodingFormat, + EncodingFormatBase64, + EncodingFormatFloat, + EncodingFormatTypedDict, + Input, + InputTypedDict, + ObjectEmbedding, + Usage, + UsageTypedDict, + ) + from .createkeysop import ( + CreateKeysData, + CreateKeysDataTypedDict, + CreateKeysLimitReset, + CreateKeysRequest, + CreateKeysRequestTypedDict, + CreateKeysResponse, + CreateKeysResponseTypedDict, + ) + from .createresponsesop import ( + CreateResponsesResponse, + CreateResponsesResponseBody, + CreateResponsesResponseBodyTypedDict, + CreateResponsesResponseTypedDict, + ) + from .defaultparameters import DefaultParameters, DefaultParametersTypedDict + from .deletekeysop import ( + DeleteKeysRequest, + DeleteKeysRequestTypedDict, + DeleteKeysResponse, + DeleteKeysResponseTypedDict, + ) + from .edgenetworktimeoutresponseerrordata import ( + EdgeNetworkTimeoutResponseErrorData, + EdgeNetworkTimeoutResponseErrorDataTypedDict, + ) + from .endpointstatus import EndpointStatus + from .exchangeauthcodeforapikeyop import ( + ExchangeAuthCodeForAPIKeyCodeChallengeMethod, + ExchangeAuthCodeForAPIKeyRequest, + ExchangeAuthCodeForAPIKeyRequestTypedDict, + ExchangeAuthCodeForAPIKeyResponse, + ExchangeAuthCodeForAPIKeyResponseTypedDict, + ) + from .filecitation import FileCitation, FileCitationType, FileCitationTypedDict + from .filepath import FilePath, FilePathType, FilePathTypedDict + from .forbiddenresponseerrordata import ( + ForbiddenResponseErrorData, + ForbiddenResponseErrorDataTypedDict, + ) + from .getcreditsop import GetCreditsResponse, GetCreditsResponseTypedDict + from .getcurrentkeyop import ( + GetCurrentKeyData, + GetCurrentKeyDataTypedDict, + GetCurrentKeyResponse, + GetCurrentKeyResponseTypedDict, + RateLimit, + RateLimitTypedDict, + ) + from .getgenerationop import ( + APIType, + GetGenerationData, + GetGenerationDataTypedDict, + GetGenerationRequest, + GetGenerationRequestTypedDict, + GetGenerationResponse, + GetGenerationResponseTypedDict, + ) + from .getkeyop import ( + GetKeyData, + GetKeyDataTypedDict, + GetKeyRequest, + GetKeyRequestTypedDict, + GetKeyResponse, + GetKeyResponseTypedDict, + ) + from .getmodelsop import GetModelsRequest, GetModelsRequestTypedDict + from .getparametersop import ( + GetParametersData, + GetParametersDataTypedDict, + GetParametersProvider, + GetParametersRequest, + GetParametersRequestTypedDict, + GetParametersResponse, + GetParametersResponseTypedDict, + GetParametersSecurity, + GetParametersSecurityTypedDict, + SupportedParameter, + ) + from .getuseractivityop import ( + GetUserActivityRequest, + GetUserActivityRequestTypedDict, + GetUserActivityResponse, + GetUserActivityResponseTypedDict, + ) + from .imagegenerationstatus import ImageGenerationStatus + from .inputmodality import InputModality + from .instructtype import InstructType + from .internalserverresponseerrordata import ( + InternalServerResponseErrorData, + InternalServerResponseErrorDataTypedDict, + ) + from .jsonschemaconfig import JSONSchemaConfig, JSONSchemaConfigTypedDict + from .listendpointsop import ( + EndpointsListEndpointsResponse, + EndpointsListEndpointsResponseTypedDict, + ListEndpointsRequest, + ListEndpointsRequestTypedDict, + ) + from .listendpointsresponse import ( + Architecture, + ArchitectureTypedDict, + ListEndpointsResponse, + ListEndpointsResponseTypedDict, + Tokenizer, + ) + from .listendpointszdrop import ( + ListEndpointsZdrResponse, + ListEndpointsZdrResponseTypedDict, + ) + from .listmodelsuserop import ( + ListModelsUserSecurity, + ListModelsUserSecurityTypedDict, + ) + from .listop import ( + ListData, + ListDataTypedDict, + ListRequest, + ListRequestTypedDict, + ListResponse, + ListResponseTypedDict, + ) + from .listprovidersop import ( + ListProvidersData, + ListProvidersDataTypedDict, + ListProvidersResponse, + ListProvidersResponseTypedDict, + ) + from .message import ( + Message, + MessageContent, + MessageContentTypedDict, + MessageDeveloper, + MessageDeveloperTypedDict, + MessageTypedDict, + ) + from .model import Model, ModelTypedDict + from .modelarchitecture import ( + ModelArchitecture, + ModelArchitectureInstructType, + ModelArchitectureTypedDict, + ) + from .modelgroup import ModelGroup + from .modelscountresponse import ( + ModelsCountResponse, + ModelsCountResponseData, + ModelsCountResponseDataTypedDict, + ModelsCountResponseTypedDict, + ) + from .modelslistresponse import ModelsListResponse, ModelsListResponseTypedDict + from .namedtoolchoice import ( + NamedToolChoice, + NamedToolChoiceFunction, + NamedToolChoiceFunctionTypedDict, + NamedToolChoiceTypedDict, + ) + from .notfoundresponseerrordata import ( + NotFoundResponseErrorData, + NotFoundResponseErrorDataTypedDict, + ) + from .openairesponsesannotation import ( + OpenAIResponsesAnnotation, + OpenAIResponsesAnnotationTypedDict, + ) + from .openairesponsesincludable import OpenAIResponsesIncludable + from .openairesponsesincompletedetails import ( + OpenAIResponsesIncompleteDetails, + OpenAIResponsesIncompleteDetailsTypedDict, + Reason, + ) + from .openairesponsesinput_union import ( + OpenAIResponsesInputContent1, + OpenAIResponsesInputContent1TypedDict, + OpenAIResponsesInputContent2, + OpenAIResponsesInputContent2TypedDict, + OpenAIResponsesInputContent3, + OpenAIResponsesInputContent3TypedDict, + OpenAIResponsesInputFunctionCall, + OpenAIResponsesInputFunctionCallOutput, + OpenAIResponsesInputFunctionCallOutputTypedDict, + OpenAIResponsesInputFunctionCallTypedDict, + OpenAIResponsesInputMessage1, + OpenAIResponsesInputMessage1TypedDict, + OpenAIResponsesInputMessage2, + OpenAIResponsesInputMessage2TypedDict, + OpenAIResponsesInputRoleAssistant, + OpenAIResponsesInputRoleDeveloper1, + OpenAIResponsesInputRoleDeveloper2, + OpenAIResponsesInputRoleSystem1, + OpenAIResponsesInputRoleSystem2, + OpenAIResponsesInputRoleUnion1, + OpenAIResponsesInputRoleUnion1TypedDict, + OpenAIResponsesInputRoleUnion2, + OpenAIResponsesInputRoleUnion2TypedDict, + OpenAIResponsesInputRoleUser1, + OpenAIResponsesInputRoleUser2, + OpenAIResponsesInputTypeFunctionCall, + OpenAIResponsesInputTypeFunctionCallOutput, + OpenAIResponsesInputTypeMessage1, + OpenAIResponsesInputTypeMessage2, + OpenAIResponsesInputUnion, + OpenAIResponsesInputUnion1, + OpenAIResponsesInputUnion1TypedDict, + OpenAIResponsesInputUnionTypedDict, + ) + from .openairesponsesprompt import ( + OpenAIResponsesPrompt, + OpenAIResponsesPromptTypedDict, + Variables, + VariablesTypedDict, + ) + from .openairesponsesreasoningconfig import ( + OpenAIResponsesReasoningConfig, + OpenAIResponsesReasoningConfigTypedDict, + ) + from .openairesponsesreasoningeffort import OpenAIResponsesReasoningEffort + from .openairesponsesrefusalcontent import ( + OpenAIResponsesRefusalContent, + OpenAIResponsesRefusalContentType, + OpenAIResponsesRefusalContentTypedDict, + ) + from .openairesponsesresponsestatus import OpenAIResponsesResponseStatus + from .openairesponsesservicetier import OpenAIResponsesServiceTier + from .openairesponsestoolchoice_union import ( + OpenAIResponsesToolChoice, + OpenAIResponsesToolChoiceAuto, + OpenAIResponsesToolChoiceFunction, + OpenAIResponsesToolChoiceFunctionTypedDict, + OpenAIResponsesToolChoiceNone, + OpenAIResponsesToolChoiceRequired, + OpenAIResponsesToolChoiceTypeFunction, + OpenAIResponsesToolChoiceTypeWebSearchPreview, + OpenAIResponsesToolChoiceTypeWebSearchPreview20250311, + OpenAIResponsesToolChoiceTypedDict, + OpenAIResponsesToolChoiceUnion, + OpenAIResponsesToolChoiceUnionTypedDict, + Type, + TypeTypedDict, + ) + from .openairesponsestruncation import OpenAIResponsesTruncation + from .openresponseseasyinputmessage import ( + OpenResponsesEasyInputMessage, + OpenResponsesEasyInputMessageContent1, + OpenResponsesEasyInputMessageContent1TypedDict, + OpenResponsesEasyInputMessageContent2, + OpenResponsesEasyInputMessageContent2TypedDict, + OpenResponsesEasyInputMessageRoleAssistant, + OpenResponsesEasyInputMessageRoleDeveloper, + OpenResponsesEasyInputMessageRoleSystem, + OpenResponsesEasyInputMessageRoleUnion, + OpenResponsesEasyInputMessageRoleUnionTypedDict, + OpenResponsesEasyInputMessageRoleUser, + OpenResponsesEasyInputMessageType, + OpenResponsesEasyInputMessageTypedDict, + ) + from .openresponseserrorevent import ( + OpenResponsesErrorEvent, + OpenResponsesErrorEventType, + OpenResponsesErrorEventTypedDict, + ) + from .openresponsesfunctioncalloutput import ( + OpenResponsesFunctionCallOutput, + OpenResponsesFunctionCallOutputType, + OpenResponsesFunctionCallOutputTypedDict, + ) + from .openresponsesfunctiontoolcall import ( + OpenResponsesFunctionToolCall, + OpenResponsesFunctionToolCallType, + OpenResponsesFunctionToolCallTypedDict, + ) + from .openresponsesimagegencallcompleted import ( + OpenResponsesImageGenCallCompleted, + OpenResponsesImageGenCallCompletedType, + OpenResponsesImageGenCallCompletedTypedDict, + ) + from .openresponsesimagegencallgenerating import ( + OpenResponsesImageGenCallGenerating, + OpenResponsesImageGenCallGeneratingType, + OpenResponsesImageGenCallGeneratingTypedDict, + ) + from .openresponsesimagegencallinprogress import ( + OpenResponsesImageGenCallInProgress, + OpenResponsesImageGenCallInProgressType, + OpenResponsesImageGenCallInProgressTypedDict, + ) + from .openresponsesimagegencallpartialimage import ( + OpenResponsesImageGenCallPartialImage, + OpenResponsesImageGenCallPartialImageType, + OpenResponsesImageGenCallPartialImageTypedDict, + ) + from .openresponsesinput import ( + OpenResponsesInput, + OpenResponsesInput1, + OpenResponsesInput1TypedDict, + OpenResponsesInputTypedDict, + ) + from .openresponsesinputmessageitem import ( + OpenResponsesInputMessageItem, + OpenResponsesInputMessageItemContent, + OpenResponsesInputMessageItemContentTypedDict, + OpenResponsesInputMessageItemRoleDeveloper, + OpenResponsesInputMessageItemRoleSystem, + OpenResponsesInputMessageItemRoleUnion, + OpenResponsesInputMessageItemRoleUnionTypedDict, + OpenResponsesInputMessageItemRoleUser, + OpenResponsesInputMessageItemType, + OpenResponsesInputMessageItemTypedDict, + ) + from .openresponseslogprobs import ( + OpenResponsesLogProbs, + OpenResponsesLogProbsTypedDict, + ) + from .openresponsesnonstreamingresponse import ( + Object, + OpenResponsesNonStreamingResponse, + OpenResponsesNonStreamingResponseToolFunction, + OpenResponsesNonStreamingResponseToolFunctionTypedDict, + OpenResponsesNonStreamingResponseToolUnion, + OpenResponsesNonStreamingResponseToolUnionTypedDict, + OpenResponsesNonStreamingResponseType, + OpenResponsesNonStreamingResponseTypedDict, + ) + from .openresponsesreasoning import ( + OpenResponsesReasoning, + OpenResponsesReasoningFormat, + OpenResponsesReasoningStatusCompleted, + OpenResponsesReasoningStatusInProgress, + OpenResponsesReasoningStatusIncomplete, + OpenResponsesReasoningStatusUnion, + OpenResponsesReasoningStatusUnionTypedDict, + OpenResponsesReasoningType, + OpenResponsesReasoningTypedDict, + ) + from .openresponsesreasoningconfig import ( + OpenResponsesReasoningConfig, + OpenResponsesReasoningConfigTypedDict, + ) + from .openresponsesreasoningdeltaevent import ( + OpenResponsesReasoningDeltaEvent, + OpenResponsesReasoningDeltaEventType, + OpenResponsesReasoningDeltaEventTypedDict, + ) + from .openresponsesreasoningdoneevent import ( + OpenResponsesReasoningDoneEvent, + OpenResponsesReasoningDoneEventType, + OpenResponsesReasoningDoneEventTypedDict, + ) + from .openresponsesreasoningsummarypartaddedevent import ( + OpenResponsesReasoningSummaryPartAddedEvent, + OpenResponsesReasoningSummaryPartAddedEventType, + OpenResponsesReasoningSummaryPartAddedEventTypedDict, + ) + from .openresponsesreasoningsummarytextdeltaevent import ( + OpenResponsesReasoningSummaryTextDeltaEvent, + OpenResponsesReasoningSummaryTextDeltaEventType, + OpenResponsesReasoningSummaryTextDeltaEventTypedDict, + ) + from .openresponsesreasoningsummarytextdoneevent import ( + OpenResponsesReasoningSummaryTextDoneEvent, + OpenResponsesReasoningSummaryTextDoneEventType, + OpenResponsesReasoningSummaryTextDoneEventTypedDict, + ) + from .openresponsesrequest import ( + DataCollection, + Engine, + IDFileParser, + IDModeration, + IDWeb, + Ignore, + IgnoreTypedDict, + MaxPrice, + MaxPriceTypedDict, + Only, + OnlyTypedDict, + OpenResponsesRequest, + OpenResponsesRequestToolFunction, + OpenResponsesRequestToolFunctionTypedDict, + OpenResponsesRequestToolUnion, + OpenResponsesRequestToolUnionTypedDict, + OpenResponsesRequestType, + OpenResponsesRequestTypedDict, + Order, + OrderTypedDict, + Pdf, + PdfEngine, + PdfTypedDict, + Plugin, + PluginFileParser, + PluginFileParserTypedDict, + PluginModeration, + PluginModerationTypedDict, + PluginTypedDict, + PluginWeb, + PluginWebTypedDict, + Provider, + ProviderTypedDict, + ServiceTier, + Sort, + Truncation, + ) + from .openresponsesresponsetext import ( + OpenResponsesResponseText, + OpenResponsesResponseTextTypedDict, + OpenResponsesResponseTextVerbosity, + ) + from .openresponsesstreamevent import ( + OpenResponsesStreamEvent, + OpenResponsesStreamEventResponseCompleted, + OpenResponsesStreamEventResponseCompletedTypedDict, + OpenResponsesStreamEventResponseContentPartAdded, + OpenResponsesStreamEventResponseContentPartAddedTypedDict, + OpenResponsesStreamEventResponseContentPartDone, + OpenResponsesStreamEventResponseContentPartDoneTypedDict, + OpenResponsesStreamEventResponseCreated, + OpenResponsesStreamEventResponseCreatedTypedDict, + OpenResponsesStreamEventResponseFailed, + OpenResponsesStreamEventResponseFailedTypedDict, + OpenResponsesStreamEventResponseFunctionCallArgumentsDelta, + OpenResponsesStreamEventResponseFunctionCallArgumentsDeltaTypedDict, + OpenResponsesStreamEventResponseFunctionCallArgumentsDone, + OpenResponsesStreamEventResponseFunctionCallArgumentsDoneTypedDict, + OpenResponsesStreamEventResponseInProgress, + OpenResponsesStreamEventResponseInProgressTypedDict, + OpenResponsesStreamEventResponseIncomplete, + OpenResponsesStreamEventResponseIncompleteTypedDict, + OpenResponsesStreamEventResponseOutputItemAdded, + OpenResponsesStreamEventResponseOutputItemAddedTypedDict, + OpenResponsesStreamEventResponseOutputItemDone, + OpenResponsesStreamEventResponseOutputItemDoneTypedDict, + OpenResponsesStreamEventResponseOutputTextAnnotationAdded, + OpenResponsesStreamEventResponseOutputTextAnnotationAddedTypedDict, + OpenResponsesStreamEventResponseOutputTextDelta, + OpenResponsesStreamEventResponseOutputTextDeltaTypedDict, + OpenResponsesStreamEventResponseOutputTextDone, + OpenResponsesStreamEventResponseOutputTextDoneTypedDict, + OpenResponsesStreamEventResponseReasoningSummaryPartDone, + OpenResponsesStreamEventResponseReasoningSummaryPartDoneTypedDict, + OpenResponsesStreamEventResponseRefusalDelta, + OpenResponsesStreamEventResponseRefusalDeltaTypedDict, + OpenResponsesStreamEventResponseRefusalDone, + OpenResponsesStreamEventResponseRefusalDoneTypedDict, + OpenResponsesStreamEventTypedDict, + Part1, + Part1TypedDict, + Part2, + Part2TypedDict, + TypeResponseCompleted, + TypeResponseContentPartAdded, + TypeResponseContentPartDone, + TypeResponseCreated, + TypeResponseFailed, + TypeResponseFunctionCallArgumentsDelta, + TypeResponseFunctionCallArgumentsDone, + TypeResponseInProgress, + TypeResponseIncomplete, + TypeResponseOutputItemAdded, + TypeResponseOutputItemDone, + TypeResponseOutputTextAnnotationAdded, + TypeResponseOutputTextDelta, + TypeResponseOutputTextDone, + TypeResponseReasoningSummaryPartDone, + TypeResponseRefusalDelta, + TypeResponseRefusalDone, + ) + from .openresponsestoplogprobs import ( + OpenResponsesTopLogprobs, + OpenResponsesTopLogprobsTypedDict, + ) + from .openresponsesusage import ( + CostDetails, + CostDetailsTypedDict, + InputTokensDetails, + InputTokensDetailsTypedDict, + OpenResponsesUsage, + OpenResponsesUsageTypedDict, + OutputTokensDetails, + OutputTokensDetailsTypedDict, + ) + from .openresponseswebsearch20250826tool import ( + OpenResponsesWebSearch20250826Tool, + OpenResponsesWebSearch20250826ToolFilters, + OpenResponsesWebSearch20250826ToolFiltersTypedDict, + OpenResponsesWebSearch20250826ToolType, + OpenResponsesWebSearch20250826ToolTypedDict, + ) + from .openresponseswebsearchpreview20250311tool import ( + OpenResponsesWebSearchPreview20250311Tool, + OpenResponsesWebSearchPreview20250311ToolType, + OpenResponsesWebSearchPreview20250311ToolTypedDict, + ) + from .openresponseswebsearchpreviewtool import ( + OpenResponsesWebSearchPreviewTool, + OpenResponsesWebSearchPreviewToolType, + OpenResponsesWebSearchPreviewToolTypedDict, + ) + from .openresponseswebsearchtool import ( + OpenResponsesWebSearchTool, + OpenResponsesWebSearchToolFilters, + OpenResponsesWebSearchToolFiltersTypedDict, + OpenResponsesWebSearchToolType, + OpenResponsesWebSearchToolTypedDict, + ) + from .outputitemimagegenerationcall import ( + OutputItemImageGenerationCall, + OutputItemImageGenerationCallType, + OutputItemImageGenerationCallTypedDict, + ) + from .outputmessage import ( + OutputMessage, + OutputMessageContent, + OutputMessageContentTypedDict, + OutputMessageRole, + OutputMessageStatusCompleted, + OutputMessageStatusInProgress, + OutputMessageStatusIncomplete, + OutputMessageStatusUnion, + OutputMessageStatusUnionTypedDict, + OutputMessageType, + OutputMessageTypedDict, + ) + from .outputmodality import OutputModality + from .parameter import Parameter + from .payloadtoolargeresponseerrordata import ( + PayloadTooLargeResponseErrorData, + PayloadTooLargeResponseErrorDataTypedDict, + ) + from .paymentrequiredresponseerrordata import ( + PaymentRequiredResponseErrorData, + PaymentRequiredResponseErrorDataTypedDict, + ) + from .perrequestlimits import PerRequestLimits, PerRequestLimitsTypedDict + from .providername import ProviderName + from .provideroverloadedresponseerrordata import ( + ProviderOverloadedResponseErrorData, + ProviderOverloadedResponseErrorDataTypedDict, + ) + from .publicendpoint import ( + Pricing, + PricingTypedDict, + PublicEndpoint, + PublicEndpointQuantization, + PublicEndpointTypedDict, + ) + from .publicpricing import PublicPricing, PublicPricingTypedDict + from .quantization import Quantization + from .reasoningsummarytext import ( + ReasoningSummaryText, + ReasoningSummaryTextType, + ReasoningSummaryTextTypedDict, + ) + from .reasoningsummaryverbosity import ReasoningSummaryVerbosity + from .reasoningtextcontent import ( + ReasoningTextContent, + ReasoningTextContentType, + ReasoningTextContentTypedDict, + ) + from .requesttimeoutresponseerrordata import ( + RequestTimeoutResponseErrorData, + RequestTimeoutResponseErrorDataTypedDict, + ) + from .responseformatjsonschema import ( + ResponseFormatJSONSchema, + ResponseFormatJSONSchemaTypedDict, + ) + from .responseformattextconfig import ( + ResponseFormatTextConfig, + ResponseFormatTextConfigTypedDict, + ) + from .responseformattextgrammar import ( + ResponseFormatTextGrammar, + ResponseFormatTextGrammarTypedDict, + ) + from .responseinputaudio import ( + ResponseInputAudio, + ResponseInputAudioFormat, + ResponseInputAudioInputAudio, + ResponseInputAudioInputAudioTypedDict, + ResponseInputAudioType, + ResponseInputAudioTypedDict, + ) + from .responseinputfile import ( + ResponseInputFile, + ResponseInputFileType, + ResponseInputFileTypedDict, + ) + from .responseinputimage import ( + ResponseInputImage, + ResponseInputImageDetail, + ResponseInputImageType, + ResponseInputImageTypedDict, + ) + from .responseinputtext import ( + ResponseInputText, + ResponseInputTextType, + ResponseInputTextTypedDict, + ) + from .responseoutputtext import ( + ResponseOutputText, + ResponseOutputTextType, + ResponseOutputTextTypedDict, + ) + from .responseserrorfield import ( + CodeEnum, + ResponsesErrorField, + ResponsesErrorFieldTypedDict, + ) + from .responsesformatjsonobject import ( + ResponsesFormatJSONObject, + ResponsesFormatJSONObjectType, + ResponsesFormatJSONObjectTypedDict, + ) + from .responsesformattext import ( + ResponsesFormatText, + ResponsesFormatTextType, + ResponsesFormatTextTypedDict, + ) + from .responsesformattextjsonschemaconfig import ( + ResponsesFormatTextJSONSchemaConfig, + ResponsesFormatTextJSONSchemaConfigType, + ResponsesFormatTextJSONSchemaConfigTypedDict, + ) + from .responsesimagegenerationcall import ( + ResponsesImageGenerationCall, + ResponsesImageGenerationCallType, + ResponsesImageGenerationCallTypedDict, + ) + from .responsesoutputitem import ResponsesOutputItem, ResponsesOutputItemTypedDict + from .responsesoutputitemfilesearchcall import ( + ResponsesOutputItemFileSearchCall, + ResponsesOutputItemFileSearchCallType, + ResponsesOutputItemFileSearchCallTypedDict, + ) + from .responsesoutputitemfunctioncall import ( + ResponsesOutputItemFunctionCall, + ResponsesOutputItemFunctionCallStatusCompleted, + ResponsesOutputItemFunctionCallStatusInProgress, + ResponsesOutputItemFunctionCallStatusIncomplete, + ResponsesOutputItemFunctionCallStatusUnion, + ResponsesOutputItemFunctionCallStatusUnionTypedDict, + ResponsesOutputItemFunctionCallType, + ResponsesOutputItemFunctionCallTypedDict, + ) + from .responsesoutputitemreasoning import ( + ResponsesOutputItemReasoning, + ResponsesOutputItemReasoningStatusCompleted, + ResponsesOutputItemReasoningStatusInProgress, + ResponsesOutputItemReasoningStatusIncomplete, + ResponsesOutputItemReasoningStatusUnion, + ResponsesOutputItemReasoningStatusUnionTypedDict, + ResponsesOutputItemReasoningType, + ResponsesOutputItemReasoningTypedDict, + ) + from .responsesoutputmessage import ( + ResponsesOutputMessage, + ResponsesOutputMessageContent, + ResponsesOutputMessageContentTypedDict, + ResponsesOutputMessageRole, + ResponsesOutputMessageStatusCompleted, + ResponsesOutputMessageStatusInProgress, + ResponsesOutputMessageStatusIncomplete, + ResponsesOutputMessageStatusUnion, + ResponsesOutputMessageStatusUnionTypedDict, + ResponsesOutputMessageType, + ResponsesOutputMessageTypedDict, + ) + from .responsessearchcontextsize import ResponsesSearchContextSize + from .responseswebsearchcalloutput import ( + ResponsesWebSearchCallOutput, + ResponsesWebSearchCallOutputType, + ResponsesWebSearchCallOutputTypedDict, + ) + from .responseswebsearchuserlocation import ( + ResponsesWebSearchUserLocation, + ResponsesWebSearchUserLocationType, + ResponsesWebSearchUserLocationTypedDict, + ) + from .responsetextconfig import ( + ResponseTextConfig, + ResponseTextConfigTypedDict, + ResponseTextConfigVerbosity, + ) + from .security import Security, SecurityTypedDict + from .sendchatcompletionrequestop import ( + SendChatCompletionRequestResponse, + SendChatCompletionRequestResponseTypedDict, + ) + from .serviceunavailableresponseerrordata import ( + ServiceUnavailableResponseErrorData, + ServiceUnavailableResponseErrorDataTypedDict, + ) + from .systemmessage import ( + SystemMessage, + SystemMessageContent, + SystemMessageContentTypedDict, + SystemMessageTypedDict, + ) + from .toolcallstatus import ToolCallStatus + from .tooldefinitionjson import ( + ToolDefinitionJSON, + ToolDefinitionJSONFunction, + ToolDefinitionJSONFunctionTypedDict, + ToolDefinitionJSONTypedDict, + ) + from .toolresponsemessage import ( + ToolResponseMessage, + ToolResponseMessageContent, + ToolResponseMessageContentTypedDict, + ToolResponseMessageTypedDict, + ) + from .toomanyrequestsresponseerrordata import ( + TooManyRequestsResponseErrorData, + TooManyRequestsResponseErrorDataTypedDict, + ) + from .topproviderinfo import TopProviderInfo, TopProviderInfoTypedDict + from .unauthorizedresponseerrordata import ( + UnauthorizedResponseErrorData, + UnauthorizedResponseErrorDataTypedDict, + ) + from .unprocessableentityresponseerrordata import ( + UnprocessableEntityResponseErrorData, + UnprocessableEntityResponseErrorDataTypedDict, + ) + from .updatekeysop import ( + UpdateKeysData, + UpdateKeysDataTypedDict, + UpdateKeysLimitReset, + UpdateKeysRequest, + UpdateKeysRequestBody, + UpdateKeysRequestBodyTypedDict, + UpdateKeysRequestTypedDict, + UpdateKeysResponse, + UpdateKeysResponseTypedDict, + ) + from .urlcitation import URLCitation, URLCitationType, URLCitationTypedDict + from .usermessage import ( + UserMessage, + UserMessageContent, + UserMessageContentTypedDict, + UserMessageTypedDict, + ) + from .websearchpreviewtooluserlocation import ( + WebSearchPreviewToolUserLocation, + WebSearchPreviewToolUserLocationType, + WebSearchPreviewToolUserLocationTypedDict, + ) + from .websearchstatus import WebSearchStatus + +__all__ = [ + "APIType", + "ActivityItem", + "ActivityItemTypedDict", + "Architecture", + "ArchitectureTypedDict", + "AssistantMessage", + "AssistantMessageContent", + "AssistantMessageContentTypedDict", + "AssistantMessageTypedDict", + "BadGatewayResponseErrorData", + "BadGatewayResponseErrorDataTypedDict", + "BadRequestResponseErrorData", + "BadRequestResponseErrorDataTypedDict", + "CallData", + "CallDataTypedDict", + "ChainID", + "ChatCompletionFinishReason", + "ChatErrorError", + "ChatErrorErrorTypedDict", + "ChatGenerationParams", + "ChatGenerationParamsResponseFormatJSONObject", + "ChatGenerationParamsResponseFormatJSONObjectTypedDict", + "ChatGenerationParamsResponseFormatPython", + "ChatGenerationParamsResponseFormatPythonTypedDict", + "ChatGenerationParamsResponseFormatText", + "ChatGenerationParamsResponseFormatTextTypedDict", + "ChatGenerationParamsResponseFormatUnion", + "ChatGenerationParamsResponseFormatUnionTypedDict", + "ChatGenerationParamsStop", + "ChatGenerationParamsStopTypedDict", + "ChatGenerationParamsTypedDict", + "ChatGenerationTokenUsage", + "ChatGenerationTokenUsageTypedDict", + "ChatMessageContentItem", + "ChatMessageContentItemAudio", + "ChatMessageContentItemAudioFormat", + "ChatMessageContentItemAudioInputAudio", + "ChatMessageContentItemAudioInputAudioTypedDict", + "ChatMessageContentItemAudioTypedDict", + "ChatMessageContentItemImage", + "ChatMessageContentItemImageDetail", + "ChatMessageContentItemImageTypedDict", + "ChatMessageContentItemText", + "ChatMessageContentItemTextTypedDict", + "ChatMessageContentItemTypedDict", + "ChatMessageContentItemVideo", + "ChatMessageContentItemVideoTypedDict", + "ChatMessageTokenLogprob", + "ChatMessageTokenLogprobTypedDict", + "ChatMessageTokenLogprobs", + "ChatMessageTokenLogprobsTypedDict", + "ChatMessageToolCall", + "ChatMessageToolCallFunction", + "ChatMessageToolCallFunctionTypedDict", + "ChatMessageToolCallTypedDict", + "ChatResponse", + "ChatResponseChoice", + "ChatResponseChoiceTypedDict", + "ChatResponseTypedDict", + "ChatStreamOptions", + "ChatStreamOptionsTypedDict", + "ChatStreamingChoice", + "ChatStreamingChoiceTypedDict", + "ChatStreamingMessageChunk", + "ChatStreamingMessageChunkRole", + "ChatStreamingMessageChunkTypedDict", + "ChatStreamingMessageToolCall", + "ChatStreamingMessageToolCallFunction", + "ChatStreamingMessageToolCallFunctionTypedDict", + "ChatStreamingMessageToolCallTypedDict", + "ChatStreamingResponseChunk", + "ChatStreamingResponseChunkData", + "ChatStreamingResponseChunkDataTypedDict", + "ChatStreamingResponseChunkError", + "ChatStreamingResponseChunkErrorTypedDict", + "ChatStreamingResponseChunkTypedDict", + "Code", + "CodeEnum", + "CodeTypedDict", + "CompletionChoice", + "CompletionChoiceTypedDict", + "CompletionCreateParams", + "CompletionCreateParamsResponseFormatJSONObject", + "CompletionCreateParamsResponseFormatJSONObjectTypedDict", + "CompletionCreateParamsResponseFormatPython", + "CompletionCreateParamsResponseFormatPythonTypedDict", + "CompletionCreateParamsResponseFormatText", + "CompletionCreateParamsResponseFormatTextTypedDict", + "CompletionCreateParamsResponseFormatUnion", + "CompletionCreateParamsResponseFormatUnionTypedDict", + "CompletionCreateParamsStop", + "CompletionCreateParamsStopTypedDict", + "CompletionCreateParamsTypedDict", + "CompletionFinishReason", + "CompletionLogprobs", + "CompletionLogprobsTypedDict", + "CompletionResponse", + "CompletionResponseTypedDict", + "CompletionTokensDetails", + "CompletionTokensDetailsTypedDict", + "CompletionUsage", + "CompletionUsageTypedDict", + "CostDetails", + "CostDetailsTypedDict", + "CreateAuthKeysCodeCodeChallengeMethod", + "CreateAuthKeysCodeData", + "CreateAuthKeysCodeDataTypedDict", + "CreateAuthKeysCodeRequest", + "CreateAuthKeysCodeRequestTypedDict", + "CreateAuthKeysCodeResponse", + "CreateAuthKeysCodeResponseTypedDict", + "CreateChargeRequest", + "CreateChargeRequestTypedDict", + "CreateCoinbaseChargeData", + "CreateCoinbaseChargeDataTypedDict", + "CreateCoinbaseChargeResponse", + "CreateCoinbaseChargeResponseTypedDict", + "CreateCoinbaseChargeSecurity", + "CreateCoinbaseChargeSecurityTypedDict", + "CreateEmbeddingsData", + "CreateEmbeddingsDataCollection", + "CreateEmbeddingsDataTypedDict", + "CreateEmbeddingsIgnore", + "CreateEmbeddingsIgnoreTypedDict", + "CreateEmbeddingsMaxPrice", + "CreateEmbeddingsMaxPriceTypedDict", + "CreateEmbeddingsObject", + "CreateEmbeddingsOnly", + "CreateEmbeddingsOnlyTypedDict", + "CreateEmbeddingsOrder", + "CreateEmbeddingsOrderTypedDict", + "CreateEmbeddingsProvider", + "CreateEmbeddingsProviderTypedDict", + "CreateEmbeddingsRequest", + "CreateEmbeddingsRequestTypedDict", + "CreateEmbeddingsResponse", + "CreateEmbeddingsResponseBody", + "CreateEmbeddingsResponseBodyTypedDict", + "CreateEmbeddingsResponseTypedDict", + "CreateEmbeddingsSort", + "CreateKeysData", + "CreateKeysDataTypedDict", + "CreateKeysLimitReset", + "CreateKeysRequest", + "CreateKeysRequestTypedDict", + "CreateKeysResponse", + "CreateKeysResponseTypedDict", + "CreateResponsesResponse", + "CreateResponsesResponseBody", + "CreateResponsesResponseBodyTypedDict", + "CreateResponsesResponseTypedDict", + "DataCollection", + "DefaultParameters", + "DefaultParametersTypedDict", + "DeleteKeysRequest", + "DeleteKeysRequestTypedDict", + "DeleteKeysResponse", + "DeleteKeysResponseTypedDict", + "EdgeNetworkTimeoutResponseErrorData", + "EdgeNetworkTimeoutResponseErrorDataTypedDict", + "Effort", + "Embedding", + "EmbeddingTypedDict", + "EncodingFormat", + "EncodingFormatBase64", + "EncodingFormatFloat", + "EncodingFormatTypedDict", + "EndpointStatus", + "EndpointsListEndpointsResponse", + "EndpointsListEndpointsResponseTypedDict", + "Engine", + "ExchangeAuthCodeForAPIKeyCodeChallengeMethod", + "ExchangeAuthCodeForAPIKeyRequest", + "ExchangeAuthCodeForAPIKeyRequestTypedDict", + "ExchangeAuthCodeForAPIKeyResponse", + "ExchangeAuthCodeForAPIKeyResponseTypedDict", + "FileCitation", + "FileCitationType", + "FileCitationTypedDict", + "FilePath", + "FilePathType", + "FilePathTypedDict", + "ForbiddenResponseErrorData", + "ForbiddenResponseErrorDataTypedDict", + "GetCreditsResponse", + "GetCreditsResponseTypedDict", + "GetCurrentKeyData", + "GetCurrentKeyDataTypedDict", + "GetCurrentKeyResponse", + "GetCurrentKeyResponseTypedDict", + "GetGenerationData", + "GetGenerationDataTypedDict", + "GetGenerationRequest", + "GetGenerationRequestTypedDict", + "GetGenerationResponse", + "GetGenerationResponseTypedDict", + "GetKeyData", + "GetKeyDataTypedDict", + "GetKeyRequest", + "GetKeyRequestTypedDict", + "GetKeyResponse", + "GetKeyResponseTypedDict", + "GetModelsRequest", + "GetModelsRequestTypedDict", + "GetParametersData", + "GetParametersDataTypedDict", + "GetParametersProvider", + "GetParametersRequest", + "GetParametersRequestTypedDict", + "GetParametersResponse", + "GetParametersResponseTypedDict", + "GetParametersSecurity", + "GetParametersSecurityTypedDict", + "GetUserActivityRequest", + "GetUserActivityRequestTypedDict", + "GetUserActivityResponse", + "GetUserActivityResponseTypedDict", + "IDFileParser", + "IDModeration", + "IDWeb", + "Ignore", + "IgnoreTypedDict", + "ImageGenerationStatus", + "ImageURL", + "ImageURLTypedDict", + "Input", + "InputModality", + "InputTokensDetails", + "InputTokensDetailsTypedDict", + "InputTypedDict", + "InstructType", + "InternalServerResponseErrorData", + "InternalServerResponseErrorDataTypedDict", + "JSONSchemaConfig", + "JSONSchemaConfigTypedDict", + "ListData", + "ListDataTypedDict", + "ListEndpointsRequest", + "ListEndpointsRequestTypedDict", + "ListEndpointsResponse", + "ListEndpointsResponseTypedDict", + "ListEndpointsZdrResponse", + "ListEndpointsZdrResponseTypedDict", + "ListModelsUserSecurity", + "ListModelsUserSecurityTypedDict", + "ListProvidersData", + "ListProvidersDataTypedDict", + "ListProvidersResponse", + "ListProvidersResponseTypedDict", + "ListRequest", + "ListRequestTypedDict", + "ListResponse", + "ListResponseTypedDict", + "MaxPrice", + "MaxPriceTypedDict", + "Message", + "MessageContent", + "MessageContentTypedDict", + "MessageDeveloper", + "MessageDeveloperTypedDict", + "MessageTypedDict", + "Metadata", + "MetadataTypedDict", + "Model", + "ModelArchitecture", + "ModelArchitectureInstructType", + "ModelArchitectureTypedDict", + "ModelGroup", + "ModelTypedDict", + "ModelsCountResponse", + "ModelsCountResponseData", + "ModelsCountResponseDataTypedDict", + "ModelsCountResponseTypedDict", + "ModelsListResponse", + "ModelsListResponseTypedDict", + "NamedToolChoice", + "NamedToolChoiceFunction", + "NamedToolChoiceFunctionTypedDict", + "NamedToolChoiceTypedDict", + "NotFoundResponseErrorData", + "NotFoundResponseErrorDataTypedDict", + "Object", + "ObjectEmbedding", + "Only", + "OnlyTypedDict", + "OpenAIResponsesAnnotation", + "OpenAIResponsesAnnotationTypedDict", + "OpenAIResponsesIncludable", + "OpenAIResponsesIncompleteDetails", + "OpenAIResponsesIncompleteDetailsTypedDict", + "OpenAIResponsesInputContent1", + "OpenAIResponsesInputContent1TypedDict", + "OpenAIResponsesInputContent2", + "OpenAIResponsesInputContent2TypedDict", + "OpenAIResponsesInputContent3", + "OpenAIResponsesInputContent3TypedDict", + "OpenAIResponsesInputFunctionCall", + "OpenAIResponsesInputFunctionCallOutput", + "OpenAIResponsesInputFunctionCallOutputTypedDict", + "OpenAIResponsesInputFunctionCallTypedDict", + "OpenAIResponsesInputMessage1", + "OpenAIResponsesInputMessage1TypedDict", + "OpenAIResponsesInputMessage2", + "OpenAIResponsesInputMessage2TypedDict", + "OpenAIResponsesInputRoleAssistant", + "OpenAIResponsesInputRoleDeveloper1", + "OpenAIResponsesInputRoleDeveloper2", + "OpenAIResponsesInputRoleSystem1", + "OpenAIResponsesInputRoleSystem2", + "OpenAIResponsesInputRoleUnion1", + "OpenAIResponsesInputRoleUnion1TypedDict", + "OpenAIResponsesInputRoleUnion2", + "OpenAIResponsesInputRoleUnion2TypedDict", + "OpenAIResponsesInputRoleUser1", + "OpenAIResponsesInputRoleUser2", + "OpenAIResponsesInputTypeFunctionCall", + "OpenAIResponsesInputTypeFunctionCallOutput", + "OpenAIResponsesInputTypeMessage1", + "OpenAIResponsesInputTypeMessage2", + "OpenAIResponsesInputUnion", + "OpenAIResponsesInputUnion1", + "OpenAIResponsesInputUnion1TypedDict", + "OpenAIResponsesInputUnionTypedDict", + "OpenAIResponsesPrompt", + "OpenAIResponsesPromptTypedDict", + "OpenAIResponsesReasoningConfig", + "OpenAIResponsesReasoningConfigTypedDict", + "OpenAIResponsesReasoningEffort", + "OpenAIResponsesRefusalContent", + "OpenAIResponsesRefusalContentType", + "OpenAIResponsesRefusalContentTypedDict", + "OpenAIResponsesResponseStatus", + "OpenAIResponsesServiceTier", + "OpenAIResponsesToolChoice", + "OpenAIResponsesToolChoiceAuto", + "OpenAIResponsesToolChoiceFunction", + "OpenAIResponsesToolChoiceFunctionTypedDict", + "OpenAIResponsesToolChoiceNone", + "OpenAIResponsesToolChoiceRequired", + "OpenAIResponsesToolChoiceTypeFunction", + "OpenAIResponsesToolChoiceTypeWebSearchPreview", + "OpenAIResponsesToolChoiceTypeWebSearchPreview20250311", + "OpenAIResponsesToolChoiceTypedDict", + "OpenAIResponsesToolChoiceUnion", + "OpenAIResponsesToolChoiceUnionTypedDict", + "OpenAIResponsesTruncation", + "OpenResponsesEasyInputMessage", + "OpenResponsesEasyInputMessageContent1", + "OpenResponsesEasyInputMessageContent1TypedDict", + "OpenResponsesEasyInputMessageContent2", + "OpenResponsesEasyInputMessageContent2TypedDict", + "OpenResponsesEasyInputMessageRoleAssistant", + "OpenResponsesEasyInputMessageRoleDeveloper", + "OpenResponsesEasyInputMessageRoleSystem", + "OpenResponsesEasyInputMessageRoleUnion", + "OpenResponsesEasyInputMessageRoleUnionTypedDict", + "OpenResponsesEasyInputMessageRoleUser", + "OpenResponsesEasyInputMessageType", + "OpenResponsesEasyInputMessageTypedDict", + "OpenResponsesErrorEvent", + "OpenResponsesErrorEventType", + "OpenResponsesErrorEventTypedDict", + "OpenResponsesFunctionCallOutput", + "OpenResponsesFunctionCallOutputType", + "OpenResponsesFunctionCallOutputTypedDict", + "OpenResponsesFunctionToolCall", + "OpenResponsesFunctionToolCallType", + "OpenResponsesFunctionToolCallTypedDict", + "OpenResponsesImageGenCallCompleted", + "OpenResponsesImageGenCallCompletedType", + "OpenResponsesImageGenCallCompletedTypedDict", + "OpenResponsesImageGenCallGenerating", + "OpenResponsesImageGenCallGeneratingType", + "OpenResponsesImageGenCallGeneratingTypedDict", + "OpenResponsesImageGenCallInProgress", + "OpenResponsesImageGenCallInProgressType", + "OpenResponsesImageGenCallInProgressTypedDict", + "OpenResponsesImageGenCallPartialImage", + "OpenResponsesImageGenCallPartialImageType", + "OpenResponsesImageGenCallPartialImageTypedDict", + "OpenResponsesInput", + "OpenResponsesInput1", + "OpenResponsesInput1TypedDict", + "OpenResponsesInputMessageItem", + "OpenResponsesInputMessageItemContent", + "OpenResponsesInputMessageItemContentTypedDict", + "OpenResponsesInputMessageItemRoleDeveloper", + "OpenResponsesInputMessageItemRoleSystem", + "OpenResponsesInputMessageItemRoleUnion", + "OpenResponsesInputMessageItemRoleUnionTypedDict", + "OpenResponsesInputMessageItemRoleUser", + "OpenResponsesInputMessageItemType", + "OpenResponsesInputMessageItemTypedDict", + "OpenResponsesInputTypedDict", + "OpenResponsesLogProbs", + "OpenResponsesLogProbsTypedDict", + "OpenResponsesNonStreamingResponse", + "OpenResponsesNonStreamingResponseToolFunction", + "OpenResponsesNonStreamingResponseToolFunctionTypedDict", + "OpenResponsesNonStreamingResponseToolUnion", + "OpenResponsesNonStreamingResponseToolUnionTypedDict", + "OpenResponsesNonStreamingResponseType", + "OpenResponsesNonStreamingResponseTypedDict", + "OpenResponsesReasoning", + "OpenResponsesReasoningConfig", + "OpenResponsesReasoningConfigTypedDict", + "OpenResponsesReasoningDeltaEvent", + "OpenResponsesReasoningDeltaEventType", + "OpenResponsesReasoningDeltaEventTypedDict", + "OpenResponsesReasoningDoneEvent", + "OpenResponsesReasoningDoneEventType", + "OpenResponsesReasoningDoneEventTypedDict", + "OpenResponsesReasoningFormat", + "OpenResponsesReasoningStatusCompleted", + "OpenResponsesReasoningStatusInProgress", + "OpenResponsesReasoningStatusIncomplete", + "OpenResponsesReasoningStatusUnion", + "OpenResponsesReasoningStatusUnionTypedDict", + "OpenResponsesReasoningSummaryPartAddedEvent", + "OpenResponsesReasoningSummaryPartAddedEventType", + "OpenResponsesReasoningSummaryPartAddedEventTypedDict", + "OpenResponsesReasoningSummaryTextDeltaEvent", + "OpenResponsesReasoningSummaryTextDeltaEventType", + "OpenResponsesReasoningSummaryTextDeltaEventTypedDict", + "OpenResponsesReasoningSummaryTextDoneEvent", + "OpenResponsesReasoningSummaryTextDoneEventType", + "OpenResponsesReasoningSummaryTextDoneEventTypedDict", + "OpenResponsesReasoningType", + "OpenResponsesReasoningTypedDict", + "OpenResponsesRequest", + "OpenResponsesRequestToolFunction", + "OpenResponsesRequestToolFunctionTypedDict", + "OpenResponsesRequestToolUnion", + "OpenResponsesRequestToolUnionTypedDict", + "OpenResponsesRequestType", + "OpenResponsesRequestTypedDict", + "OpenResponsesResponseText", + "OpenResponsesResponseTextTypedDict", + "OpenResponsesResponseTextVerbosity", + "OpenResponsesStreamEvent", + "OpenResponsesStreamEventResponseCompleted", + "OpenResponsesStreamEventResponseCompletedTypedDict", + "OpenResponsesStreamEventResponseContentPartAdded", + "OpenResponsesStreamEventResponseContentPartAddedTypedDict", + "OpenResponsesStreamEventResponseContentPartDone", + "OpenResponsesStreamEventResponseContentPartDoneTypedDict", + "OpenResponsesStreamEventResponseCreated", + "OpenResponsesStreamEventResponseCreatedTypedDict", + "OpenResponsesStreamEventResponseFailed", + "OpenResponsesStreamEventResponseFailedTypedDict", + "OpenResponsesStreamEventResponseFunctionCallArgumentsDelta", + "OpenResponsesStreamEventResponseFunctionCallArgumentsDeltaTypedDict", + "OpenResponsesStreamEventResponseFunctionCallArgumentsDone", + "OpenResponsesStreamEventResponseFunctionCallArgumentsDoneTypedDict", + "OpenResponsesStreamEventResponseInProgress", + "OpenResponsesStreamEventResponseInProgressTypedDict", + "OpenResponsesStreamEventResponseIncomplete", + "OpenResponsesStreamEventResponseIncompleteTypedDict", + "OpenResponsesStreamEventResponseOutputItemAdded", + "OpenResponsesStreamEventResponseOutputItemAddedTypedDict", + "OpenResponsesStreamEventResponseOutputItemDone", + "OpenResponsesStreamEventResponseOutputItemDoneTypedDict", + "OpenResponsesStreamEventResponseOutputTextAnnotationAdded", + "OpenResponsesStreamEventResponseOutputTextAnnotationAddedTypedDict", + "OpenResponsesStreamEventResponseOutputTextDelta", + "OpenResponsesStreamEventResponseOutputTextDeltaTypedDict", + "OpenResponsesStreamEventResponseOutputTextDone", + "OpenResponsesStreamEventResponseOutputTextDoneTypedDict", + "OpenResponsesStreamEventResponseReasoningSummaryPartDone", + "OpenResponsesStreamEventResponseReasoningSummaryPartDoneTypedDict", + "OpenResponsesStreamEventResponseRefusalDelta", + "OpenResponsesStreamEventResponseRefusalDeltaTypedDict", + "OpenResponsesStreamEventResponseRefusalDone", + "OpenResponsesStreamEventResponseRefusalDoneTypedDict", + "OpenResponsesStreamEventTypedDict", + "OpenResponsesTopLogprobs", + "OpenResponsesTopLogprobsTypedDict", + "OpenResponsesUsage", + "OpenResponsesUsageTypedDict", + "OpenResponsesWebSearch20250826Tool", + "OpenResponsesWebSearch20250826ToolFilters", + "OpenResponsesWebSearch20250826ToolFiltersTypedDict", + "OpenResponsesWebSearch20250826ToolType", + "OpenResponsesWebSearch20250826ToolTypedDict", + "OpenResponsesWebSearchPreview20250311Tool", + "OpenResponsesWebSearchPreview20250311ToolType", + "OpenResponsesWebSearchPreview20250311ToolTypedDict", + "OpenResponsesWebSearchPreviewTool", + "OpenResponsesWebSearchPreviewToolType", + "OpenResponsesWebSearchPreviewToolTypedDict", + "OpenResponsesWebSearchTool", + "OpenResponsesWebSearchToolFilters", + "OpenResponsesWebSearchToolFiltersTypedDict", + "OpenResponsesWebSearchToolType", + "OpenResponsesWebSearchToolTypedDict", + "Order", + "OrderTypedDict", + "OutputItemImageGenerationCall", + "OutputItemImageGenerationCallType", + "OutputItemImageGenerationCallTypedDict", + "OutputMessage", + "OutputMessageContent", + "OutputMessageContentTypedDict", + "OutputMessageRole", + "OutputMessageStatusCompleted", + "OutputMessageStatusInProgress", + "OutputMessageStatusIncomplete", + "OutputMessageStatusUnion", + "OutputMessageStatusUnionTypedDict", + "OutputMessageType", + "OutputMessageTypedDict", + "OutputModality", + "OutputTokensDetails", + "OutputTokensDetailsTypedDict", + "Parameter", + "Part1", + "Part1TypedDict", + "Part2", + "Part2TypedDict", + "PayloadTooLargeResponseErrorData", + "PayloadTooLargeResponseErrorDataTypedDict", + "PaymentRequiredResponseErrorData", + "PaymentRequiredResponseErrorDataTypedDict", + "Pdf", + "PdfEngine", + "PdfTypedDict", + "PerRequestLimits", + "PerRequestLimitsTypedDict", + "Plugin", + "PluginFileParser", + "PluginFileParserTypedDict", + "PluginModeration", + "PluginModerationTypedDict", + "PluginTypedDict", + "PluginWeb", + "PluginWebTypedDict", + "Pricing", + "PricingTypedDict", + "Prompt", + "PromptTokensDetails", + "PromptTokensDetailsTypedDict", + "PromptTypedDict", + "Provider", + "ProviderName", + "ProviderOverloadedResponseErrorData", + "ProviderOverloadedResponseErrorDataTypedDict", + "ProviderTypedDict", + "PublicEndpoint", + "PublicEndpointQuantization", + "PublicEndpointTypedDict", + "PublicPricing", + "PublicPricingTypedDict", + "Quantization", + "RateLimit", + "RateLimitTypedDict", + "Reason", + "Reasoning", + "ReasoningSummaryText", + "ReasoningSummaryTextType", + "ReasoningSummaryTextTypedDict", + "ReasoningSummaryVerbosity", + "ReasoningTextContent", + "ReasoningTextContentType", + "ReasoningTextContentTypedDict", + "ReasoningTypedDict", + "RequestTimeoutResponseErrorData", + "RequestTimeoutResponseErrorDataTypedDict", + "ResponseFormatJSONSchema", + "ResponseFormatJSONSchemaTypedDict", + "ResponseFormatTextConfig", + "ResponseFormatTextConfigTypedDict", + "ResponseFormatTextGrammar", + "ResponseFormatTextGrammarTypedDict", + "ResponseInputAudio", + "ResponseInputAudioFormat", + "ResponseInputAudioInputAudio", + "ResponseInputAudioInputAudioTypedDict", + "ResponseInputAudioType", + "ResponseInputAudioTypedDict", + "ResponseInputFile", + "ResponseInputFileType", + "ResponseInputFileTypedDict", + "ResponseInputImage", + "ResponseInputImageDetail", + "ResponseInputImageType", + "ResponseInputImageTypedDict", + "ResponseInputText", + "ResponseInputTextType", + "ResponseInputTextTypedDict", + "ResponseOutputText", + "ResponseOutputTextType", + "ResponseOutputTextTypedDict", + "ResponseTextConfig", + "ResponseTextConfigTypedDict", + "ResponseTextConfigVerbosity", + "ResponsesErrorField", + "ResponsesErrorFieldTypedDict", + "ResponsesFormatJSONObject", + "ResponsesFormatJSONObjectType", + "ResponsesFormatJSONObjectTypedDict", + "ResponsesFormatText", + "ResponsesFormatTextJSONSchemaConfig", + "ResponsesFormatTextJSONSchemaConfigType", + "ResponsesFormatTextJSONSchemaConfigTypedDict", + "ResponsesFormatTextType", + "ResponsesFormatTextTypedDict", + "ResponsesImageGenerationCall", + "ResponsesImageGenerationCallType", + "ResponsesImageGenerationCallTypedDict", + "ResponsesOutputItem", + "ResponsesOutputItemFileSearchCall", + "ResponsesOutputItemFileSearchCallType", + "ResponsesOutputItemFileSearchCallTypedDict", + "ResponsesOutputItemFunctionCall", + "ResponsesOutputItemFunctionCallStatusCompleted", + "ResponsesOutputItemFunctionCallStatusInProgress", + "ResponsesOutputItemFunctionCallStatusIncomplete", + "ResponsesOutputItemFunctionCallStatusUnion", + "ResponsesOutputItemFunctionCallStatusUnionTypedDict", + "ResponsesOutputItemFunctionCallType", + "ResponsesOutputItemFunctionCallTypedDict", + "ResponsesOutputItemReasoning", + "ResponsesOutputItemReasoningStatusCompleted", + "ResponsesOutputItemReasoningStatusInProgress", + "ResponsesOutputItemReasoningStatusIncomplete", + "ResponsesOutputItemReasoningStatusUnion", + "ResponsesOutputItemReasoningStatusUnionTypedDict", + "ResponsesOutputItemReasoningType", + "ResponsesOutputItemReasoningTypedDict", + "ResponsesOutputItemTypedDict", + "ResponsesOutputMessage", + "ResponsesOutputMessageContent", + "ResponsesOutputMessageContentTypedDict", + "ResponsesOutputMessageRole", + "ResponsesOutputMessageStatusCompleted", + "ResponsesOutputMessageStatusInProgress", + "ResponsesOutputMessageStatusIncomplete", + "ResponsesOutputMessageStatusUnion", + "ResponsesOutputMessageStatusUnionTypedDict", + "ResponsesOutputMessageType", + "ResponsesOutputMessageTypedDict", + "ResponsesSearchContextSize", + "ResponsesWebSearchCallOutput", + "ResponsesWebSearchCallOutputType", + "ResponsesWebSearchCallOutputTypedDict", + "ResponsesWebSearchUserLocation", + "ResponsesWebSearchUserLocationType", + "ResponsesWebSearchUserLocationTypedDict", + "Security", + "SecurityTypedDict", + "SendChatCompletionRequestResponse", + "SendChatCompletionRequestResponseTypedDict", + "ServiceTier", + "ServiceUnavailableResponseErrorData", + "ServiceUnavailableResponseErrorDataTypedDict", + "Sort", + "StreamOptions", + "StreamOptionsTypedDict", + "SupportedParameter", + "SystemMessage", + "SystemMessageContent", + "SystemMessageContentTypedDict", + "SystemMessageTypedDict", + "Tokenizer", + "TooManyRequestsResponseErrorData", + "TooManyRequestsResponseErrorDataTypedDict", + "ToolCallStatus", + "ToolDefinitionJSON", + "ToolDefinitionJSONFunction", + "ToolDefinitionJSONFunctionTypedDict", + "ToolDefinitionJSONTypedDict", + "ToolResponseMessage", + "ToolResponseMessageContent", + "ToolResponseMessageContentTypedDict", + "ToolResponseMessageTypedDict", + "TopLogprob", + "TopLogprobTypedDict", + "TopProviderInfo", + "TopProviderInfoTypedDict", + "TransferIntent", + "TransferIntentTypedDict", + "Truncation", + "Type", + "TypeResponseCompleted", + "TypeResponseContentPartAdded", + "TypeResponseContentPartDone", + "TypeResponseCreated", + "TypeResponseFailed", + "TypeResponseFunctionCallArgumentsDelta", + "TypeResponseFunctionCallArgumentsDone", + "TypeResponseInProgress", + "TypeResponseIncomplete", + "TypeResponseOutputItemAdded", + "TypeResponseOutputItemDone", + "TypeResponseOutputTextAnnotationAdded", + "TypeResponseOutputTextDelta", + "TypeResponseOutputTextDone", + "TypeResponseReasoningSummaryPartDone", + "TypeResponseRefusalDelta", + "TypeResponseRefusalDone", + "TypeTypedDict", + "URLCitation", + "URLCitationType", + "URLCitationTypedDict", + "UnauthorizedResponseErrorData", + "UnauthorizedResponseErrorDataTypedDict", + "UnprocessableEntityResponseErrorData", + "UnprocessableEntityResponseErrorDataTypedDict", + "UpdateKeysData", + "UpdateKeysDataTypedDict", + "UpdateKeysLimitReset", + "UpdateKeysRequest", + "UpdateKeysRequestBody", + "UpdateKeysRequestBodyTypedDict", + "UpdateKeysRequestTypedDict", + "UpdateKeysResponse", + "UpdateKeysResponseTypedDict", + "Usage", + "UsageTypedDict", + "UserMessage", + "UserMessageContent", + "UserMessageContentTypedDict", + "UserMessageTypedDict", + "Variables", + "VariablesTypedDict", + "VideoURL", + "VideoURLTypedDict", + "Web3Data", + "Web3DataTypedDict", + "WebSearchPreviewToolUserLocation", + "WebSearchPreviewToolUserLocationType", + "WebSearchPreviewToolUserLocationTypedDict", + "WebSearchStatus", +] + +_dynamic_imports: dict[str, str] = { + "ActivityItem": ".activityitem", + "ActivityItemTypedDict": ".activityitem", + "AssistantMessage": ".assistantmessage", + "AssistantMessageContent": ".assistantmessage", + "AssistantMessageContentTypedDict": ".assistantmessage", + "AssistantMessageTypedDict": ".assistantmessage", + "BadGatewayResponseErrorData": ".badgatewayresponseerrordata", + "BadGatewayResponseErrorDataTypedDict": ".badgatewayresponseerrordata", + "BadRequestResponseErrorData": ".badrequestresponseerrordata", + "BadRequestResponseErrorDataTypedDict": ".badrequestresponseerrordata", + "ChatCompletionFinishReason": ".chatcompletionfinishreason", + "ChatErrorError": ".chaterror", + "ChatErrorErrorTypedDict": ".chaterror", + "Code": ".chaterror", + "CodeTypedDict": ".chaterror", + "ChatGenerationParams": ".chatgenerationparams", + "ChatGenerationParamsResponseFormatJSONObject": ".chatgenerationparams", + "ChatGenerationParamsResponseFormatJSONObjectTypedDict": ".chatgenerationparams", + "ChatGenerationParamsResponseFormatPython": ".chatgenerationparams", + "ChatGenerationParamsResponseFormatPythonTypedDict": ".chatgenerationparams", + "ChatGenerationParamsResponseFormatText": ".chatgenerationparams", + "ChatGenerationParamsResponseFormatTextTypedDict": ".chatgenerationparams", + "ChatGenerationParamsResponseFormatUnion": ".chatgenerationparams", + "ChatGenerationParamsResponseFormatUnionTypedDict": ".chatgenerationparams", + "ChatGenerationParamsStop": ".chatgenerationparams", + "ChatGenerationParamsStopTypedDict": ".chatgenerationparams", + "ChatGenerationParamsTypedDict": ".chatgenerationparams", + "Effort": ".chatgenerationparams", + "Reasoning": ".chatgenerationparams", + "ReasoningTypedDict": ".chatgenerationparams", + "ChatGenerationTokenUsage": ".chatgenerationtokenusage", + "ChatGenerationTokenUsageTypedDict": ".chatgenerationtokenusage", + "CompletionTokensDetails": ".chatgenerationtokenusage", + "CompletionTokensDetailsTypedDict": ".chatgenerationtokenusage", + "PromptTokensDetails": ".chatgenerationtokenusage", + "PromptTokensDetailsTypedDict": ".chatgenerationtokenusage", + "ChatMessageContentItem": ".chatmessagecontentitem", + "ChatMessageContentItemTypedDict": ".chatmessagecontentitem", + "ChatMessageContentItemAudio": ".chatmessagecontentitemaudio", + "ChatMessageContentItemAudioFormat": ".chatmessagecontentitemaudio", + "ChatMessageContentItemAudioInputAudio": ".chatmessagecontentitemaudio", + "ChatMessageContentItemAudioInputAudioTypedDict": ".chatmessagecontentitemaudio", + "ChatMessageContentItemAudioTypedDict": ".chatmessagecontentitemaudio", + "ChatMessageContentItemImage": ".chatmessagecontentitemimage", + "ChatMessageContentItemImageDetail": ".chatmessagecontentitemimage", + "ChatMessageContentItemImageTypedDict": ".chatmessagecontentitemimage", + "ImageURL": ".chatmessagecontentitemimage", + "ImageURLTypedDict": ".chatmessagecontentitemimage", + "ChatMessageContentItemText": ".chatmessagecontentitemtext", + "ChatMessageContentItemTextTypedDict": ".chatmessagecontentitemtext", + "ChatMessageContentItemVideo": ".chatmessagecontentitemvideo", + "ChatMessageContentItemVideoTypedDict": ".chatmessagecontentitemvideo", + "VideoURL": ".chatmessagecontentitemvideo", + "VideoURLTypedDict": ".chatmessagecontentitemvideo", + "ChatMessageTokenLogprob": ".chatmessagetokenlogprob", + "ChatMessageTokenLogprobTypedDict": ".chatmessagetokenlogprob", + "TopLogprob": ".chatmessagetokenlogprob", + "TopLogprobTypedDict": ".chatmessagetokenlogprob", + "ChatMessageTokenLogprobs": ".chatmessagetokenlogprobs", + "ChatMessageTokenLogprobsTypedDict": ".chatmessagetokenlogprobs", + "ChatMessageToolCall": ".chatmessagetoolcall", + "ChatMessageToolCallFunction": ".chatmessagetoolcall", + "ChatMessageToolCallFunctionTypedDict": ".chatmessagetoolcall", + "ChatMessageToolCallTypedDict": ".chatmessagetoolcall", + "ChatResponse": ".chatresponse", + "ChatResponseTypedDict": ".chatresponse", + "ChatResponseChoice": ".chatresponsechoice", + "ChatResponseChoiceTypedDict": ".chatresponsechoice", + "ChatStreamingChoice": ".chatstreamingchoice", + "ChatStreamingChoiceTypedDict": ".chatstreamingchoice", + "ChatStreamingMessageChunk": ".chatstreamingmessagechunk", + "ChatStreamingMessageChunkRole": ".chatstreamingmessagechunk", + "ChatStreamingMessageChunkTypedDict": ".chatstreamingmessagechunk", + "ChatStreamingMessageToolCall": ".chatstreamingmessagetoolcall", + "ChatStreamingMessageToolCallFunction": ".chatstreamingmessagetoolcall", + "ChatStreamingMessageToolCallFunctionTypedDict": ".chatstreamingmessagetoolcall", + "ChatStreamingMessageToolCallTypedDict": ".chatstreamingmessagetoolcall", + "ChatStreamingResponseChunk": ".chatstreamingresponsechunk", + "ChatStreamingResponseChunkData": ".chatstreamingresponsechunk", + "ChatStreamingResponseChunkDataTypedDict": ".chatstreamingresponsechunk", + "ChatStreamingResponseChunkError": ".chatstreamingresponsechunk", + "ChatStreamingResponseChunkErrorTypedDict": ".chatstreamingresponsechunk", + "ChatStreamingResponseChunkTypedDict": ".chatstreamingresponsechunk", + "ChatStreamOptions": ".chatstreamoptions", + "ChatStreamOptionsTypedDict": ".chatstreamoptions", + "CompletionChoice": ".completionchoice", + "CompletionChoiceTypedDict": ".completionchoice", + "CompletionFinishReason": ".completionchoice", + "CompletionCreateParams": ".completioncreateparams", + "CompletionCreateParamsResponseFormatJSONObject": ".completioncreateparams", + "CompletionCreateParamsResponseFormatJSONObjectTypedDict": ".completioncreateparams", + "CompletionCreateParamsResponseFormatPython": ".completioncreateparams", + "CompletionCreateParamsResponseFormatPythonTypedDict": ".completioncreateparams", + "CompletionCreateParamsResponseFormatText": ".completioncreateparams", + "CompletionCreateParamsResponseFormatTextTypedDict": ".completioncreateparams", + "CompletionCreateParamsResponseFormatUnion": ".completioncreateparams", + "CompletionCreateParamsResponseFormatUnionTypedDict": ".completioncreateparams", + "CompletionCreateParamsStop": ".completioncreateparams", + "CompletionCreateParamsStopTypedDict": ".completioncreateparams", + "CompletionCreateParamsTypedDict": ".completioncreateparams", + "Prompt": ".completioncreateparams", + "PromptTypedDict": ".completioncreateparams", + "StreamOptions": ".completioncreateparams", + "StreamOptionsTypedDict": ".completioncreateparams", + "CompletionLogprobs": ".completionlogprobs", + "CompletionLogprobsTypedDict": ".completionlogprobs", + "CompletionResponse": ".completionresponse", + "CompletionResponseTypedDict": ".completionresponse", + "CompletionUsage": ".completionusage", + "CompletionUsageTypedDict": ".completionusage", + "CreateAuthKeysCodeCodeChallengeMethod": ".createauthkeyscodeop", + "CreateAuthKeysCodeData": ".createauthkeyscodeop", + "CreateAuthKeysCodeDataTypedDict": ".createauthkeyscodeop", + "CreateAuthKeysCodeRequest": ".createauthkeyscodeop", + "CreateAuthKeysCodeRequestTypedDict": ".createauthkeyscodeop", + "CreateAuthKeysCodeResponse": ".createauthkeyscodeop", + "CreateAuthKeysCodeResponseTypedDict": ".createauthkeyscodeop", + "ChainID": ".createchargerequest", + "CreateChargeRequest": ".createchargerequest", + "CreateChargeRequestTypedDict": ".createchargerequest", + "CallData": ".createcoinbasechargeop", + "CallDataTypedDict": ".createcoinbasechargeop", + "CreateCoinbaseChargeData": ".createcoinbasechargeop", + "CreateCoinbaseChargeDataTypedDict": ".createcoinbasechargeop", + "CreateCoinbaseChargeResponse": ".createcoinbasechargeop", + "CreateCoinbaseChargeResponseTypedDict": ".createcoinbasechargeop", + "CreateCoinbaseChargeSecurity": ".createcoinbasechargeop", + "CreateCoinbaseChargeSecurityTypedDict": ".createcoinbasechargeop", + "Metadata": ".createcoinbasechargeop", + "MetadataTypedDict": ".createcoinbasechargeop", + "TransferIntent": ".createcoinbasechargeop", + "TransferIntentTypedDict": ".createcoinbasechargeop", + "Web3Data": ".createcoinbasechargeop", + "Web3DataTypedDict": ".createcoinbasechargeop", + "CreateEmbeddingsData": ".createembeddingsop", + "CreateEmbeddingsDataCollection": ".createembeddingsop", + "CreateEmbeddingsDataTypedDict": ".createembeddingsop", + "CreateEmbeddingsIgnore": ".createembeddingsop", + "CreateEmbeddingsIgnoreTypedDict": ".createembeddingsop", + "CreateEmbeddingsMaxPrice": ".createembeddingsop", + "CreateEmbeddingsMaxPriceTypedDict": ".createembeddingsop", + "CreateEmbeddingsObject": ".createembeddingsop", + "CreateEmbeddingsOnly": ".createembeddingsop", + "CreateEmbeddingsOnlyTypedDict": ".createembeddingsop", + "CreateEmbeddingsOrder": ".createembeddingsop", + "CreateEmbeddingsOrderTypedDict": ".createembeddingsop", + "CreateEmbeddingsProvider": ".createembeddingsop", + "CreateEmbeddingsProviderTypedDict": ".createembeddingsop", + "CreateEmbeddingsRequest": ".createembeddingsop", + "CreateEmbeddingsRequestTypedDict": ".createembeddingsop", + "CreateEmbeddingsResponse": ".createembeddingsop", + "CreateEmbeddingsResponseBody": ".createembeddingsop", + "CreateEmbeddingsResponseBodyTypedDict": ".createembeddingsop", + "CreateEmbeddingsResponseTypedDict": ".createembeddingsop", + "CreateEmbeddingsSort": ".createembeddingsop", + "Embedding": ".createembeddingsop", + "EmbeddingTypedDict": ".createembeddingsop", + "EncodingFormat": ".createembeddingsop", + "EncodingFormatBase64": ".createembeddingsop", + "EncodingFormatFloat": ".createembeddingsop", + "EncodingFormatTypedDict": ".createembeddingsop", + "Input": ".createembeddingsop", + "InputTypedDict": ".createembeddingsop", + "ObjectEmbedding": ".createembeddingsop", + "Usage": ".createembeddingsop", + "UsageTypedDict": ".createembeddingsop", + "CreateKeysData": ".createkeysop", + "CreateKeysDataTypedDict": ".createkeysop", + "CreateKeysLimitReset": ".createkeysop", + "CreateKeysRequest": ".createkeysop", + "CreateKeysRequestTypedDict": ".createkeysop", + "CreateKeysResponse": ".createkeysop", + "CreateKeysResponseTypedDict": ".createkeysop", + "CreateResponsesResponse": ".createresponsesop", + "CreateResponsesResponseBody": ".createresponsesop", + "CreateResponsesResponseBodyTypedDict": ".createresponsesop", + "CreateResponsesResponseTypedDict": ".createresponsesop", + "DefaultParameters": ".defaultparameters", + "DefaultParametersTypedDict": ".defaultparameters", + "DeleteKeysRequest": ".deletekeysop", + "DeleteKeysRequestTypedDict": ".deletekeysop", + "DeleteKeysResponse": ".deletekeysop", + "DeleteKeysResponseTypedDict": ".deletekeysop", + "EdgeNetworkTimeoutResponseErrorData": ".edgenetworktimeoutresponseerrordata", + "EdgeNetworkTimeoutResponseErrorDataTypedDict": ".edgenetworktimeoutresponseerrordata", + "EndpointStatus": ".endpointstatus", + "ExchangeAuthCodeForAPIKeyCodeChallengeMethod": ".exchangeauthcodeforapikeyop", + "ExchangeAuthCodeForAPIKeyRequest": ".exchangeauthcodeforapikeyop", + "ExchangeAuthCodeForAPIKeyRequestTypedDict": ".exchangeauthcodeforapikeyop", + "ExchangeAuthCodeForAPIKeyResponse": ".exchangeauthcodeforapikeyop", + "ExchangeAuthCodeForAPIKeyResponseTypedDict": ".exchangeauthcodeforapikeyop", + "FileCitation": ".filecitation", + "FileCitationType": ".filecitation", + "FileCitationTypedDict": ".filecitation", + "FilePath": ".filepath", + "FilePathType": ".filepath", + "FilePathTypedDict": ".filepath", + "ForbiddenResponseErrorData": ".forbiddenresponseerrordata", + "ForbiddenResponseErrorDataTypedDict": ".forbiddenresponseerrordata", + "GetCreditsResponse": ".getcreditsop", + "GetCreditsResponseTypedDict": ".getcreditsop", + "GetCurrentKeyData": ".getcurrentkeyop", + "GetCurrentKeyDataTypedDict": ".getcurrentkeyop", + "GetCurrentKeyResponse": ".getcurrentkeyop", + "GetCurrentKeyResponseTypedDict": ".getcurrentkeyop", + "RateLimit": ".getcurrentkeyop", + "RateLimitTypedDict": ".getcurrentkeyop", + "APIType": ".getgenerationop", + "GetGenerationData": ".getgenerationop", + "GetGenerationDataTypedDict": ".getgenerationop", + "GetGenerationRequest": ".getgenerationop", + "GetGenerationRequestTypedDict": ".getgenerationop", + "GetGenerationResponse": ".getgenerationop", + "GetGenerationResponseTypedDict": ".getgenerationop", + "GetKeyData": ".getkeyop", + "GetKeyDataTypedDict": ".getkeyop", + "GetKeyRequest": ".getkeyop", + "GetKeyRequestTypedDict": ".getkeyop", + "GetKeyResponse": ".getkeyop", + "GetKeyResponseTypedDict": ".getkeyop", + "GetModelsRequest": ".getmodelsop", + "GetModelsRequestTypedDict": ".getmodelsop", + "GetParametersData": ".getparametersop", + "GetParametersDataTypedDict": ".getparametersop", + "GetParametersProvider": ".getparametersop", + "GetParametersRequest": ".getparametersop", + "GetParametersRequestTypedDict": ".getparametersop", + "GetParametersResponse": ".getparametersop", + "GetParametersResponseTypedDict": ".getparametersop", + "GetParametersSecurity": ".getparametersop", + "GetParametersSecurityTypedDict": ".getparametersop", + "SupportedParameter": ".getparametersop", + "GetUserActivityRequest": ".getuseractivityop", + "GetUserActivityRequestTypedDict": ".getuseractivityop", + "GetUserActivityResponse": ".getuseractivityop", + "GetUserActivityResponseTypedDict": ".getuseractivityop", + "ImageGenerationStatus": ".imagegenerationstatus", + "InputModality": ".inputmodality", + "InstructType": ".instructtype", + "InternalServerResponseErrorData": ".internalserverresponseerrordata", + "InternalServerResponseErrorDataTypedDict": ".internalserverresponseerrordata", + "JSONSchemaConfig": ".jsonschemaconfig", + "JSONSchemaConfigTypedDict": ".jsonschemaconfig", + "EndpointsListEndpointsResponse": ".listendpointsop", + "EndpointsListEndpointsResponseTypedDict": ".listendpointsop", + "ListEndpointsRequest": ".listendpointsop", + "ListEndpointsRequestTypedDict": ".listendpointsop", + "Architecture": ".listendpointsresponse", + "ArchitectureTypedDict": ".listendpointsresponse", + "ListEndpointsResponse": ".listendpointsresponse", + "ListEndpointsResponseTypedDict": ".listendpointsresponse", + "Tokenizer": ".listendpointsresponse", + "ListEndpointsZdrResponse": ".listendpointszdrop", + "ListEndpointsZdrResponseTypedDict": ".listendpointszdrop", + "ListModelsUserSecurity": ".listmodelsuserop", + "ListModelsUserSecurityTypedDict": ".listmodelsuserop", + "ListData": ".listop", + "ListDataTypedDict": ".listop", + "ListRequest": ".listop", + "ListRequestTypedDict": ".listop", + "ListResponse": ".listop", + "ListResponseTypedDict": ".listop", + "ListProvidersData": ".listprovidersop", + "ListProvidersDataTypedDict": ".listprovidersop", + "ListProvidersResponse": ".listprovidersop", + "ListProvidersResponseTypedDict": ".listprovidersop", + "Message": ".message", + "MessageContent": ".message", + "MessageContentTypedDict": ".message", + "MessageDeveloper": ".message", + "MessageDeveloperTypedDict": ".message", + "MessageTypedDict": ".message", + "Model": ".model", + "ModelTypedDict": ".model", + "ModelArchitecture": ".modelarchitecture", + "ModelArchitectureInstructType": ".modelarchitecture", + "ModelArchitectureTypedDict": ".modelarchitecture", + "ModelGroup": ".modelgroup", + "ModelsCountResponse": ".modelscountresponse", + "ModelsCountResponseData": ".modelscountresponse", + "ModelsCountResponseDataTypedDict": ".modelscountresponse", + "ModelsCountResponseTypedDict": ".modelscountresponse", + "ModelsListResponse": ".modelslistresponse", + "ModelsListResponseTypedDict": ".modelslistresponse", + "NamedToolChoice": ".namedtoolchoice", + "NamedToolChoiceFunction": ".namedtoolchoice", + "NamedToolChoiceFunctionTypedDict": ".namedtoolchoice", + "NamedToolChoiceTypedDict": ".namedtoolchoice", + "NotFoundResponseErrorData": ".notfoundresponseerrordata", + "NotFoundResponseErrorDataTypedDict": ".notfoundresponseerrordata", + "OpenAIResponsesAnnotation": ".openairesponsesannotation", + "OpenAIResponsesAnnotationTypedDict": ".openairesponsesannotation", + "OpenAIResponsesIncludable": ".openairesponsesincludable", + "OpenAIResponsesIncompleteDetails": ".openairesponsesincompletedetails", + "OpenAIResponsesIncompleteDetailsTypedDict": ".openairesponsesincompletedetails", + "Reason": ".openairesponsesincompletedetails", + "OpenAIResponsesInputContent1": ".openairesponsesinput_union", + "OpenAIResponsesInputContent1TypedDict": ".openairesponsesinput_union", + "OpenAIResponsesInputContent2": ".openairesponsesinput_union", + "OpenAIResponsesInputContent2TypedDict": ".openairesponsesinput_union", + "OpenAIResponsesInputContent3": ".openairesponsesinput_union", + "OpenAIResponsesInputContent3TypedDict": ".openairesponsesinput_union", + "OpenAIResponsesInputFunctionCall": ".openairesponsesinput_union", + "OpenAIResponsesInputFunctionCallOutput": ".openairesponsesinput_union", + "OpenAIResponsesInputFunctionCallOutputTypedDict": ".openairesponsesinput_union", + "OpenAIResponsesInputFunctionCallTypedDict": ".openairesponsesinput_union", + "OpenAIResponsesInputMessage1": ".openairesponsesinput_union", + "OpenAIResponsesInputMessage1TypedDict": ".openairesponsesinput_union", + "OpenAIResponsesInputMessage2": ".openairesponsesinput_union", + "OpenAIResponsesInputMessage2TypedDict": ".openairesponsesinput_union", + "OpenAIResponsesInputRoleAssistant": ".openairesponsesinput_union", + "OpenAIResponsesInputRoleDeveloper1": ".openairesponsesinput_union", + "OpenAIResponsesInputRoleDeveloper2": ".openairesponsesinput_union", + "OpenAIResponsesInputRoleSystem1": ".openairesponsesinput_union", + "OpenAIResponsesInputRoleSystem2": ".openairesponsesinput_union", + "OpenAIResponsesInputRoleUnion1": ".openairesponsesinput_union", + "OpenAIResponsesInputRoleUnion1TypedDict": ".openairesponsesinput_union", + "OpenAIResponsesInputRoleUnion2": ".openairesponsesinput_union", + "OpenAIResponsesInputRoleUnion2TypedDict": ".openairesponsesinput_union", + "OpenAIResponsesInputRoleUser1": ".openairesponsesinput_union", + "OpenAIResponsesInputRoleUser2": ".openairesponsesinput_union", + "OpenAIResponsesInputTypeFunctionCall": ".openairesponsesinput_union", + "OpenAIResponsesInputTypeFunctionCallOutput": ".openairesponsesinput_union", + "OpenAIResponsesInputTypeMessage1": ".openairesponsesinput_union", + "OpenAIResponsesInputTypeMessage2": ".openairesponsesinput_union", + "OpenAIResponsesInputUnion": ".openairesponsesinput_union", + "OpenAIResponsesInputUnion1": ".openairesponsesinput_union", + "OpenAIResponsesInputUnion1TypedDict": ".openairesponsesinput_union", + "OpenAIResponsesInputUnionTypedDict": ".openairesponsesinput_union", + "OpenAIResponsesPrompt": ".openairesponsesprompt", + "OpenAIResponsesPromptTypedDict": ".openairesponsesprompt", + "Variables": ".openairesponsesprompt", + "VariablesTypedDict": ".openairesponsesprompt", + "OpenAIResponsesReasoningConfig": ".openairesponsesreasoningconfig", + "OpenAIResponsesReasoningConfigTypedDict": ".openairesponsesreasoningconfig", + "OpenAIResponsesReasoningEffort": ".openairesponsesreasoningeffort", + "OpenAIResponsesRefusalContent": ".openairesponsesrefusalcontent", + "OpenAIResponsesRefusalContentType": ".openairesponsesrefusalcontent", + "OpenAIResponsesRefusalContentTypedDict": ".openairesponsesrefusalcontent", + "OpenAIResponsesResponseStatus": ".openairesponsesresponsestatus", + "OpenAIResponsesServiceTier": ".openairesponsesservicetier", + "OpenAIResponsesToolChoice": ".openairesponsestoolchoice_union", + "OpenAIResponsesToolChoiceAuto": ".openairesponsestoolchoice_union", + "OpenAIResponsesToolChoiceFunction": ".openairesponsestoolchoice_union", + "OpenAIResponsesToolChoiceFunctionTypedDict": ".openairesponsestoolchoice_union", + "OpenAIResponsesToolChoiceNone": ".openairesponsestoolchoice_union", + "OpenAIResponsesToolChoiceRequired": ".openairesponsestoolchoice_union", + "OpenAIResponsesToolChoiceTypeFunction": ".openairesponsestoolchoice_union", + "OpenAIResponsesToolChoiceTypeWebSearchPreview": ".openairesponsestoolchoice_union", + "OpenAIResponsesToolChoiceTypeWebSearchPreview20250311": ".openairesponsestoolchoice_union", + "OpenAIResponsesToolChoiceTypedDict": ".openairesponsestoolchoice_union", + "OpenAIResponsesToolChoiceUnion": ".openairesponsestoolchoice_union", + "OpenAIResponsesToolChoiceUnionTypedDict": ".openairesponsestoolchoice_union", + "Type": ".openairesponsestoolchoice_union", + "TypeTypedDict": ".openairesponsestoolchoice_union", + "OpenAIResponsesTruncation": ".openairesponsestruncation", + "OpenResponsesEasyInputMessage": ".openresponseseasyinputmessage", + "OpenResponsesEasyInputMessageContent1": ".openresponseseasyinputmessage", + "OpenResponsesEasyInputMessageContent1TypedDict": ".openresponseseasyinputmessage", + "OpenResponsesEasyInputMessageContent2": ".openresponseseasyinputmessage", + "OpenResponsesEasyInputMessageContent2TypedDict": ".openresponseseasyinputmessage", + "OpenResponsesEasyInputMessageRoleAssistant": ".openresponseseasyinputmessage", + "OpenResponsesEasyInputMessageRoleDeveloper": ".openresponseseasyinputmessage", + "OpenResponsesEasyInputMessageRoleSystem": ".openresponseseasyinputmessage", + "OpenResponsesEasyInputMessageRoleUnion": ".openresponseseasyinputmessage", + "OpenResponsesEasyInputMessageRoleUnionTypedDict": ".openresponseseasyinputmessage", + "OpenResponsesEasyInputMessageRoleUser": ".openresponseseasyinputmessage", + "OpenResponsesEasyInputMessageType": ".openresponseseasyinputmessage", + "OpenResponsesEasyInputMessageTypedDict": ".openresponseseasyinputmessage", + "OpenResponsesErrorEvent": ".openresponseserrorevent", + "OpenResponsesErrorEventType": ".openresponseserrorevent", + "OpenResponsesErrorEventTypedDict": ".openresponseserrorevent", + "OpenResponsesFunctionCallOutput": ".openresponsesfunctioncalloutput", + "OpenResponsesFunctionCallOutputType": ".openresponsesfunctioncalloutput", + "OpenResponsesFunctionCallOutputTypedDict": ".openresponsesfunctioncalloutput", + "OpenResponsesFunctionToolCall": ".openresponsesfunctiontoolcall", + "OpenResponsesFunctionToolCallType": ".openresponsesfunctiontoolcall", + "OpenResponsesFunctionToolCallTypedDict": ".openresponsesfunctiontoolcall", + "OpenResponsesImageGenCallCompleted": ".openresponsesimagegencallcompleted", + "OpenResponsesImageGenCallCompletedType": ".openresponsesimagegencallcompleted", + "OpenResponsesImageGenCallCompletedTypedDict": ".openresponsesimagegencallcompleted", + "OpenResponsesImageGenCallGenerating": ".openresponsesimagegencallgenerating", + "OpenResponsesImageGenCallGeneratingType": ".openresponsesimagegencallgenerating", + "OpenResponsesImageGenCallGeneratingTypedDict": ".openresponsesimagegencallgenerating", + "OpenResponsesImageGenCallInProgress": ".openresponsesimagegencallinprogress", + "OpenResponsesImageGenCallInProgressType": ".openresponsesimagegencallinprogress", + "OpenResponsesImageGenCallInProgressTypedDict": ".openresponsesimagegencallinprogress", + "OpenResponsesImageGenCallPartialImage": ".openresponsesimagegencallpartialimage", + "OpenResponsesImageGenCallPartialImageType": ".openresponsesimagegencallpartialimage", + "OpenResponsesImageGenCallPartialImageTypedDict": ".openresponsesimagegencallpartialimage", + "OpenResponsesInput": ".openresponsesinput", + "OpenResponsesInput1": ".openresponsesinput", + "OpenResponsesInput1TypedDict": ".openresponsesinput", + "OpenResponsesInputTypedDict": ".openresponsesinput", + "OpenResponsesInputMessageItem": ".openresponsesinputmessageitem", + "OpenResponsesInputMessageItemContent": ".openresponsesinputmessageitem", + "OpenResponsesInputMessageItemContentTypedDict": ".openresponsesinputmessageitem", + "OpenResponsesInputMessageItemRoleDeveloper": ".openresponsesinputmessageitem", + "OpenResponsesInputMessageItemRoleSystem": ".openresponsesinputmessageitem", + "OpenResponsesInputMessageItemRoleUnion": ".openresponsesinputmessageitem", + "OpenResponsesInputMessageItemRoleUnionTypedDict": ".openresponsesinputmessageitem", + "OpenResponsesInputMessageItemRoleUser": ".openresponsesinputmessageitem", + "OpenResponsesInputMessageItemType": ".openresponsesinputmessageitem", + "OpenResponsesInputMessageItemTypedDict": ".openresponsesinputmessageitem", + "OpenResponsesLogProbs": ".openresponseslogprobs", + "OpenResponsesLogProbsTypedDict": ".openresponseslogprobs", + "Object": ".openresponsesnonstreamingresponse", + "OpenResponsesNonStreamingResponse": ".openresponsesnonstreamingresponse", + "OpenResponsesNonStreamingResponseToolFunction": ".openresponsesnonstreamingresponse", + "OpenResponsesNonStreamingResponseToolFunctionTypedDict": ".openresponsesnonstreamingresponse", + "OpenResponsesNonStreamingResponseToolUnion": ".openresponsesnonstreamingresponse", + "OpenResponsesNonStreamingResponseToolUnionTypedDict": ".openresponsesnonstreamingresponse", + "OpenResponsesNonStreamingResponseType": ".openresponsesnonstreamingresponse", + "OpenResponsesNonStreamingResponseTypedDict": ".openresponsesnonstreamingresponse", + "OpenResponsesReasoning": ".openresponsesreasoning", + "OpenResponsesReasoningFormat": ".openresponsesreasoning", + "OpenResponsesReasoningStatusCompleted": ".openresponsesreasoning", + "OpenResponsesReasoningStatusInProgress": ".openresponsesreasoning", + "OpenResponsesReasoningStatusIncomplete": ".openresponsesreasoning", + "OpenResponsesReasoningStatusUnion": ".openresponsesreasoning", + "OpenResponsesReasoningStatusUnionTypedDict": ".openresponsesreasoning", + "OpenResponsesReasoningType": ".openresponsesreasoning", + "OpenResponsesReasoningTypedDict": ".openresponsesreasoning", + "OpenResponsesReasoningConfig": ".openresponsesreasoningconfig", + "OpenResponsesReasoningConfigTypedDict": ".openresponsesreasoningconfig", + "OpenResponsesReasoningDeltaEvent": ".openresponsesreasoningdeltaevent", + "OpenResponsesReasoningDeltaEventType": ".openresponsesreasoningdeltaevent", + "OpenResponsesReasoningDeltaEventTypedDict": ".openresponsesreasoningdeltaevent", + "OpenResponsesReasoningDoneEvent": ".openresponsesreasoningdoneevent", + "OpenResponsesReasoningDoneEventType": ".openresponsesreasoningdoneevent", + "OpenResponsesReasoningDoneEventTypedDict": ".openresponsesreasoningdoneevent", + "OpenResponsesReasoningSummaryPartAddedEvent": ".openresponsesreasoningsummarypartaddedevent", + "OpenResponsesReasoningSummaryPartAddedEventType": ".openresponsesreasoningsummarypartaddedevent", + "OpenResponsesReasoningSummaryPartAddedEventTypedDict": ".openresponsesreasoningsummarypartaddedevent", + "OpenResponsesReasoningSummaryTextDeltaEvent": ".openresponsesreasoningsummarytextdeltaevent", + "OpenResponsesReasoningSummaryTextDeltaEventType": ".openresponsesreasoningsummarytextdeltaevent", + "OpenResponsesReasoningSummaryTextDeltaEventTypedDict": ".openresponsesreasoningsummarytextdeltaevent", + "OpenResponsesReasoningSummaryTextDoneEvent": ".openresponsesreasoningsummarytextdoneevent", + "OpenResponsesReasoningSummaryTextDoneEventType": ".openresponsesreasoningsummarytextdoneevent", + "OpenResponsesReasoningSummaryTextDoneEventTypedDict": ".openresponsesreasoningsummarytextdoneevent", + "DataCollection": ".openresponsesrequest", + "Engine": ".openresponsesrequest", + "IDFileParser": ".openresponsesrequest", + "IDModeration": ".openresponsesrequest", + "IDWeb": ".openresponsesrequest", + "Ignore": ".openresponsesrequest", + "IgnoreTypedDict": ".openresponsesrequest", + "MaxPrice": ".openresponsesrequest", + "MaxPriceTypedDict": ".openresponsesrequest", + "Only": ".openresponsesrequest", + "OnlyTypedDict": ".openresponsesrequest", + "OpenResponsesRequest": ".openresponsesrequest", + "OpenResponsesRequestToolFunction": ".openresponsesrequest", + "OpenResponsesRequestToolFunctionTypedDict": ".openresponsesrequest", + "OpenResponsesRequestToolUnion": ".openresponsesrequest", + "OpenResponsesRequestToolUnionTypedDict": ".openresponsesrequest", + "OpenResponsesRequestType": ".openresponsesrequest", + "OpenResponsesRequestTypedDict": ".openresponsesrequest", + "Order": ".openresponsesrequest", + "OrderTypedDict": ".openresponsesrequest", + "Pdf": ".openresponsesrequest", + "PdfEngine": ".openresponsesrequest", + "PdfTypedDict": ".openresponsesrequest", + "Plugin": ".openresponsesrequest", + "PluginFileParser": ".openresponsesrequest", + "PluginFileParserTypedDict": ".openresponsesrequest", + "PluginModeration": ".openresponsesrequest", + "PluginModerationTypedDict": ".openresponsesrequest", + "PluginTypedDict": ".openresponsesrequest", + "PluginWeb": ".openresponsesrequest", + "PluginWebTypedDict": ".openresponsesrequest", + "Provider": ".openresponsesrequest", + "ProviderTypedDict": ".openresponsesrequest", + "ServiceTier": ".openresponsesrequest", + "Sort": ".openresponsesrequest", + "Truncation": ".openresponsesrequest", + "OpenResponsesResponseText": ".openresponsesresponsetext", + "OpenResponsesResponseTextTypedDict": ".openresponsesresponsetext", + "OpenResponsesResponseTextVerbosity": ".openresponsesresponsetext", + "OpenResponsesStreamEvent": ".openresponsesstreamevent", + "OpenResponsesStreamEventResponseCompleted": ".openresponsesstreamevent", + "OpenResponsesStreamEventResponseCompletedTypedDict": ".openresponsesstreamevent", + "OpenResponsesStreamEventResponseContentPartAdded": ".openresponsesstreamevent", + "OpenResponsesStreamEventResponseContentPartAddedTypedDict": ".openresponsesstreamevent", + "OpenResponsesStreamEventResponseContentPartDone": ".openresponsesstreamevent", + "OpenResponsesStreamEventResponseContentPartDoneTypedDict": ".openresponsesstreamevent", + "OpenResponsesStreamEventResponseCreated": ".openresponsesstreamevent", + "OpenResponsesStreamEventResponseCreatedTypedDict": ".openresponsesstreamevent", + "OpenResponsesStreamEventResponseFailed": ".openresponsesstreamevent", + "OpenResponsesStreamEventResponseFailedTypedDict": ".openresponsesstreamevent", + "OpenResponsesStreamEventResponseFunctionCallArgumentsDelta": ".openresponsesstreamevent", + "OpenResponsesStreamEventResponseFunctionCallArgumentsDeltaTypedDict": ".openresponsesstreamevent", + "OpenResponsesStreamEventResponseFunctionCallArgumentsDone": ".openresponsesstreamevent", + "OpenResponsesStreamEventResponseFunctionCallArgumentsDoneTypedDict": ".openresponsesstreamevent", + "OpenResponsesStreamEventResponseInProgress": ".openresponsesstreamevent", + "OpenResponsesStreamEventResponseInProgressTypedDict": ".openresponsesstreamevent", + "OpenResponsesStreamEventResponseIncomplete": ".openresponsesstreamevent", + "OpenResponsesStreamEventResponseIncompleteTypedDict": ".openresponsesstreamevent", + "OpenResponsesStreamEventResponseOutputItemAdded": ".openresponsesstreamevent", + "OpenResponsesStreamEventResponseOutputItemAddedTypedDict": ".openresponsesstreamevent", + "OpenResponsesStreamEventResponseOutputItemDone": ".openresponsesstreamevent", + "OpenResponsesStreamEventResponseOutputItemDoneTypedDict": ".openresponsesstreamevent", + "OpenResponsesStreamEventResponseOutputTextAnnotationAdded": ".openresponsesstreamevent", + "OpenResponsesStreamEventResponseOutputTextAnnotationAddedTypedDict": ".openresponsesstreamevent", + "OpenResponsesStreamEventResponseOutputTextDelta": ".openresponsesstreamevent", + "OpenResponsesStreamEventResponseOutputTextDeltaTypedDict": ".openresponsesstreamevent", + "OpenResponsesStreamEventResponseOutputTextDone": ".openresponsesstreamevent", + "OpenResponsesStreamEventResponseOutputTextDoneTypedDict": ".openresponsesstreamevent", + "OpenResponsesStreamEventResponseReasoningSummaryPartDone": ".openresponsesstreamevent", + "OpenResponsesStreamEventResponseReasoningSummaryPartDoneTypedDict": ".openresponsesstreamevent", + "OpenResponsesStreamEventResponseRefusalDelta": ".openresponsesstreamevent", + "OpenResponsesStreamEventResponseRefusalDeltaTypedDict": ".openresponsesstreamevent", + "OpenResponsesStreamEventResponseRefusalDone": ".openresponsesstreamevent", + "OpenResponsesStreamEventResponseRefusalDoneTypedDict": ".openresponsesstreamevent", + "OpenResponsesStreamEventTypedDict": ".openresponsesstreamevent", + "Part1": ".openresponsesstreamevent", + "Part1TypedDict": ".openresponsesstreamevent", + "Part2": ".openresponsesstreamevent", + "Part2TypedDict": ".openresponsesstreamevent", + "TypeResponseCompleted": ".openresponsesstreamevent", + "TypeResponseContentPartAdded": ".openresponsesstreamevent", + "TypeResponseContentPartDone": ".openresponsesstreamevent", + "TypeResponseCreated": ".openresponsesstreamevent", + "TypeResponseFailed": ".openresponsesstreamevent", + "TypeResponseFunctionCallArgumentsDelta": ".openresponsesstreamevent", + "TypeResponseFunctionCallArgumentsDone": ".openresponsesstreamevent", + "TypeResponseInProgress": ".openresponsesstreamevent", + "TypeResponseIncomplete": ".openresponsesstreamevent", + "TypeResponseOutputItemAdded": ".openresponsesstreamevent", + "TypeResponseOutputItemDone": ".openresponsesstreamevent", + "TypeResponseOutputTextAnnotationAdded": ".openresponsesstreamevent", + "TypeResponseOutputTextDelta": ".openresponsesstreamevent", + "TypeResponseOutputTextDone": ".openresponsesstreamevent", + "TypeResponseReasoningSummaryPartDone": ".openresponsesstreamevent", + "TypeResponseRefusalDelta": ".openresponsesstreamevent", + "TypeResponseRefusalDone": ".openresponsesstreamevent", + "OpenResponsesTopLogprobs": ".openresponsestoplogprobs", + "OpenResponsesTopLogprobsTypedDict": ".openresponsestoplogprobs", + "CostDetails": ".openresponsesusage", + "CostDetailsTypedDict": ".openresponsesusage", + "InputTokensDetails": ".openresponsesusage", + "InputTokensDetailsTypedDict": ".openresponsesusage", + "OpenResponsesUsage": ".openresponsesusage", + "OpenResponsesUsageTypedDict": ".openresponsesusage", + "OutputTokensDetails": ".openresponsesusage", + "OutputTokensDetailsTypedDict": ".openresponsesusage", + "OpenResponsesWebSearch20250826Tool": ".openresponseswebsearch20250826tool", + "OpenResponsesWebSearch20250826ToolFilters": ".openresponseswebsearch20250826tool", + "OpenResponsesWebSearch20250826ToolFiltersTypedDict": ".openresponseswebsearch20250826tool", + "OpenResponsesWebSearch20250826ToolType": ".openresponseswebsearch20250826tool", + "OpenResponsesWebSearch20250826ToolTypedDict": ".openresponseswebsearch20250826tool", + "OpenResponsesWebSearchPreview20250311Tool": ".openresponseswebsearchpreview20250311tool", + "OpenResponsesWebSearchPreview20250311ToolType": ".openresponseswebsearchpreview20250311tool", + "OpenResponsesWebSearchPreview20250311ToolTypedDict": ".openresponseswebsearchpreview20250311tool", + "OpenResponsesWebSearchPreviewTool": ".openresponseswebsearchpreviewtool", + "OpenResponsesWebSearchPreviewToolType": ".openresponseswebsearchpreviewtool", + "OpenResponsesWebSearchPreviewToolTypedDict": ".openresponseswebsearchpreviewtool", + "OpenResponsesWebSearchTool": ".openresponseswebsearchtool", + "OpenResponsesWebSearchToolFilters": ".openresponseswebsearchtool", + "OpenResponsesWebSearchToolFiltersTypedDict": ".openresponseswebsearchtool", + "OpenResponsesWebSearchToolType": ".openresponseswebsearchtool", + "OpenResponsesWebSearchToolTypedDict": ".openresponseswebsearchtool", + "OutputItemImageGenerationCall": ".outputitemimagegenerationcall", + "OutputItemImageGenerationCallType": ".outputitemimagegenerationcall", + "OutputItemImageGenerationCallTypedDict": ".outputitemimagegenerationcall", + "OutputMessage": ".outputmessage", + "OutputMessageContent": ".outputmessage", + "OutputMessageContentTypedDict": ".outputmessage", + "OutputMessageRole": ".outputmessage", + "OutputMessageStatusCompleted": ".outputmessage", + "OutputMessageStatusInProgress": ".outputmessage", + "OutputMessageStatusIncomplete": ".outputmessage", + "OutputMessageStatusUnion": ".outputmessage", + "OutputMessageStatusUnionTypedDict": ".outputmessage", + "OutputMessageType": ".outputmessage", + "OutputMessageTypedDict": ".outputmessage", + "OutputModality": ".outputmodality", + "Parameter": ".parameter", + "PayloadTooLargeResponseErrorData": ".payloadtoolargeresponseerrordata", + "PayloadTooLargeResponseErrorDataTypedDict": ".payloadtoolargeresponseerrordata", + "PaymentRequiredResponseErrorData": ".paymentrequiredresponseerrordata", + "PaymentRequiredResponseErrorDataTypedDict": ".paymentrequiredresponseerrordata", + "PerRequestLimits": ".perrequestlimits", + "PerRequestLimitsTypedDict": ".perrequestlimits", + "ProviderName": ".providername", + "ProviderOverloadedResponseErrorData": ".provideroverloadedresponseerrordata", + "ProviderOverloadedResponseErrorDataTypedDict": ".provideroverloadedresponseerrordata", + "Pricing": ".publicendpoint", + "PricingTypedDict": ".publicendpoint", + "PublicEndpoint": ".publicendpoint", + "PublicEndpointQuantization": ".publicendpoint", + "PublicEndpointTypedDict": ".publicendpoint", + "PublicPricing": ".publicpricing", + "PublicPricingTypedDict": ".publicpricing", + "Quantization": ".quantization", + "ReasoningSummaryText": ".reasoningsummarytext", + "ReasoningSummaryTextType": ".reasoningsummarytext", + "ReasoningSummaryTextTypedDict": ".reasoningsummarytext", + "ReasoningSummaryVerbosity": ".reasoningsummaryverbosity", + "ReasoningTextContent": ".reasoningtextcontent", + "ReasoningTextContentType": ".reasoningtextcontent", + "ReasoningTextContentTypedDict": ".reasoningtextcontent", + "RequestTimeoutResponseErrorData": ".requesttimeoutresponseerrordata", + "RequestTimeoutResponseErrorDataTypedDict": ".requesttimeoutresponseerrordata", + "ResponseFormatJSONSchema": ".responseformatjsonschema", + "ResponseFormatJSONSchemaTypedDict": ".responseformatjsonschema", + "ResponseFormatTextConfig": ".responseformattextconfig", + "ResponseFormatTextConfigTypedDict": ".responseformattextconfig", + "ResponseFormatTextGrammar": ".responseformattextgrammar", + "ResponseFormatTextGrammarTypedDict": ".responseformattextgrammar", + "ResponseInputAudio": ".responseinputaudio", + "ResponseInputAudioFormat": ".responseinputaudio", + "ResponseInputAudioInputAudio": ".responseinputaudio", + "ResponseInputAudioInputAudioTypedDict": ".responseinputaudio", + "ResponseInputAudioType": ".responseinputaudio", + "ResponseInputAudioTypedDict": ".responseinputaudio", + "ResponseInputFile": ".responseinputfile", + "ResponseInputFileType": ".responseinputfile", + "ResponseInputFileTypedDict": ".responseinputfile", + "ResponseInputImage": ".responseinputimage", + "ResponseInputImageDetail": ".responseinputimage", + "ResponseInputImageType": ".responseinputimage", + "ResponseInputImageTypedDict": ".responseinputimage", + "ResponseInputText": ".responseinputtext", + "ResponseInputTextType": ".responseinputtext", + "ResponseInputTextTypedDict": ".responseinputtext", + "ResponseOutputText": ".responseoutputtext", + "ResponseOutputTextType": ".responseoutputtext", + "ResponseOutputTextTypedDict": ".responseoutputtext", + "CodeEnum": ".responseserrorfield", + "ResponsesErrorField": ".responseserrorfield", + "ResponsesErrorFieldTypedDict": ".responseserrorfield", + "ResponsesFormatJSONObject": ".responsesformatjsonobject", + "ResponsesFormatJSONObjectType": ".responsesformatjsonobject", + "ResponsesFormatJSONObjectTypedDict": ".responsesformatjsonobject", + "ResponsesFormatText": ".responsesformattext", + "ResponsesFormatTextType": ".responsesformattext", + "ResponsesFormatTextTypedDict": ".responsesformattext", + "ResponsesFormatTextJSONSchemaConfig": ".responsesformattextjsonschemaconfig", + "ResponsesFormatTextJSONSchemaConfigType": ".responsesformattextjsonschemaconfig", + "ResponsesFormatTextJSONSchemaConfigTypedDict": ".responsesformattextjsonschemaconfig", + "ResponsesImageGenerationCall": ".responsesimagegenerationcall", + "ResponsesImageGenerationCallType": ".responsesimagegenerationcall", + "ResponsesImageGenerationCallTypedDict": ".responsesimagegenerationcall", + "ResponsesOutputItem": ".responsesoutputitem", + "ResponsesOutputItemTypedDict": ".responsesoutputitem", + "ResponsesOutputItemFileSearchCall": ".responsesoutputitemfilesearchcall", + "ResponsesOutputItemFileSearchCallType": ".responsesoutputitemfilesearchcall", + "ResponsesOutputItemFileSearchCallTypedDict": ".responsesoutputitemfilesearchcall", + "ResponsesOutputItemFunctionCall": ".responsesoutputitemfunctioncall", + "ResponsesOutputItemFunctionCallStatusCompleted": ".responsesoutputitemfunctioncall", + "ResponsesOutputItemFunctionCallStatusInProgress": ".responsesoutputitemfunctioncall", + "ResponsesOutputItemFunctionCallStatusIncomplete": ".responsesoutputitemfunctioncall", + "ResponsesOutputItemFunctionCallStatusUnion": ".responsesoutputitemfunctioncall", + "ResponsesOutputItemFunctionCallStatusUnionTypedDict": ".responsesoutputitemfunctioncall", + "ResponsesOutputItemFunctionCallType": ".responsesoutputitemfunctioncall", + "ResponsesOutputItemFunctionCallTypedDict": ".responsesoutputitemfunctioncall", + "ResponsesOutputItemReasoning": ".responsesoutputitemreasoning", + "ResponsesOutputItemReasoningStatusCompleted": ".responsesoutputitemreasoning", + "ResponsesOutputItemReasoningStatusInProgress": ".responsesoutputitemreasoning", + "ResponsesOutputItemReasoningStatusIncomplete": ".responsesoutputitemreasoning", + "ResponsesOutputItemReasoningStatusUnion": ".responsesoutputitemreasoning", + "ResponsesOutputItemReasoningStatusUnionTypedDict": ".responsesoutputitemreasoning", + "ResponsesOutputItemReasoningType": ".responsesoutputitemreasoning", + "ResponsesOutputItemReasoningTypedDict": ".responsesoutputitemreasoning", + "ResponsesOutputMessage": ".responsesoutputmessage", + "ResponsesOutputMessageContent": ".responsesoutputmessage", + "ResponsesOutputMessageContentTypedDict": ".responsesoutputmessage", + "ResponsesOutputMessageRole": ".responsesoutputmessage", + "ResponsesOutputMessageStatusCompleted": ".responsesoutputmessage", + "ResponsesOutputMessageStatusInProgress": ".responsesoutputmessage", + "ResponsesOutputMessageStatusIncomplete": ".responsesoutputmessage", + "ResponsesOutputMessageStatusUnion": ".responsesoutputmessage", + "ResponsesOutputMessageStatusUnionTypedDict": ".responsesoutputmessage", + "ResponsesOutputMessageType": ".responsesoutputmessage", + "ResponsesOutputMessageTypedDict": ".responsesoutputmessage", + "ResponsesSearchContextSize": ".responsessearchcontextsize", + "ResponsesWebSearchCallOutput": ".responseswebsearchcalloutput", + "ResponsesWebSearchCallOutputType": ".responseswebsearchcalloutput", + "ResponsesWebSearchCallOutputTypedDict": ".responseswebsearchcalloutput", + "ResponsesWebSearchUserLocation": ".responseswebsearchuserlocation", + "ResponsesWebSearchUserLocationType": ".responseswebsearchuserlocation", + "ResponsesWebSearchUserLocationTypedDict": ".responseswebsearchuserlocation", + "ResponseTextConfig": ".responsetextconfig", + "ResponseTextConfigTypedDict": ".responsetextconfig", + "ResponseTextConfigVerbosity": ".responsetextconfig", + "Security": ".security", + "SecurityTypedDict": ".security", + "SendChatCompletionRequestResponse": ".sendchatcompletionrequestop", + "SendChatCompletionRequestResponseTypedDict": ".sendchatcompletionrequestop", + "ServiceUnavailableResponseErrorData": ".serviceunavailableresponseerrordata", + "ServiceUnavailableResponseErrorDataTypedDict": ".serviceunavailableresponseerrordata", + "SystemMessage": ".systemmessage", + "SystemMessageContent": ".systemmessage", + "SystemMessageContentTypedDict": ".systemmessage", + "SystemMessageTypedDict": ".systemmessage", + "ToolCallStatus": ".toolcallstatus", + "ToolDefinitionJSON": ".tooldefinitionjson", + "ToolDefinitionJSONFunction": ".tooldefinitionjson", + "ToolDefinitionJSONFunctionTypedDict": ".tooldefinitionjson", + "ToolDefinitionJSONTypedDict": ".tooldefinitionjson", + "ToolResponseMessage": ".toolresponsemessage", + "ToolResponseMessageContent": ".toolresponsemessage", + "ToolResponseMessageContentTypedDict": ".toolresponsemessage", + "ToolResponseMessageTypedDict": ".toolresponsemessage", + "TooManyRequestsResponseErrorData": ".toomanyrequestsresponseerrordata", + "TooManyRequestsResponseErrorDataTypedDict": ".toomanyrequestsresponseerrordata", + "TopProviderInfo": ".topproviderinfo", + "TopProviderInfoTypedDict": ".topproviderinfo", + "UnauthorizedResponseErrorData": ".unauthorizedresponseerrordata", + "UnauthorizedResponseErrorDataTypedDict": ".unauthorizedresponseerrordata", + "UnprocessableEntityResponseErrorData": ".unprocessableentityresponseerrordata", + "UnprocessableEntityResponseErrorDataTypedDict": ".unprocessableentityresponseerrordata", + "UpdateKeysData": ".updatekeysop", + "UpdateKeysDataTypedDict": ".updatekeysop", + "UpdateKeysLimitReset": ".updatekeysop", + "UpdateKeysRequest": ".updatekeysop", + "UpdateKeysRequestBody": ".updatekeysop", + "UpdateKeysRequestBodyTypedDict": ".updatekeysop", + "UpdateKeysRequestTypedDict": ".updatekeysop", + "UpdateKeysResponse": ".updatekeysop", + "UpdateKeysResponseTypedDict": ".updatekeysop", + "URLCitation": ".urlcitation", + "URLCitationType": ".urlcitation", + "URLCitationTypedDict": ".urlcitation", + "UserMessage": ".usermessage", + "UserMessageContent": ".usermessage", + "UserMessageContentTypedDict": ".usermessage", + "UserMessageTypedDict": ".usermessage", + "WebSearchPreviewToolUserLocation": ".websearchpreviewtooluserlocation", + "WebSearchPreviewToolUserLocationType": ".websearchpreviewtooluserlocation", + "WebSearchPreviewToolUserLocationTypedDict": ".websearchpreviewtooluserlocation", + "WebSearchStatus": ".websearchstatus", +} + + +def dynamic_import(modname, retries=3): + for attempt in range(retries): + try: + return import_module(modname, __package__) + except KeyError: + # Clear any half-initialized module and retry + sys.modules.pop(modname, None) + if attempt == retries - 1: + break + raise KeyError(f"Failed to import module '{modname}' after {retries} attempts") + + +def __getattr__(attr_name: str) -> object: + module_name = _dynamic_imports.get(attr_name) + if module_name is None: + raise AttributeError( + f"No {attr_name} found in _dynamic_imports for module name -> {__name__} " + ) + + try: + module = dynamic_import(module_name) + result = getattr(module, attr_name) + return result + except ImportError as e: + raise ImportError( + f"Failed to import {attr_name} from {module_name}: {e}" + ) from e + except AttributeError as e: + raise AttributeError( + f"Failed to get {attr_name} from {module_name}: {e}" + ) from e + + +def __dir__(): + lazy_attrs = builtins.list(_dynamic_imports.keys()) + return builtins.sorted(lazy_attrs) diff --git a/src/openrouter/models/activityitem.py b/src/openrouter/models/activityitem.py new file mode 100644 index 0000000..12c081f --- /dev/null +++ b/src/openrouter/models/activityitem.py @@ -0,0 +1,66 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel +import pydantic +from typing_extensions import Annotated, TypedDict + + +class ActivityItemTypedDict(TypedDict): + date_: str + r"""Date of the activity (YYYY-MM-DD format)""" + model: str + r"""Model slug (e.g., \"openai/gpt-4.1\")""" + model_permaslug: str + r"""Model permaslug (e.g., \"openai/gpt-4.1-2025-04-14\")""" + endpoint_id: str + r"""Unique identifier for the endpoint""" + provider_name: str + r"""Name of the provider serving this endpoint""" + usage: float + r"""Total cost in USD (OpenRouter credits spent)""" + byok_usage_inference: float + r"""BYOK inference cost in USD (external credits spent)""" + requests: float + r"""Number of requests made""" + prompt_tokens: float + r"""Total prompt tokens used""" + completion_tokens: float + r"""Total completion tokens generated""" + reasoning_tokens: float + r"""Total reasoning tokens used""" + + +class ActivityItem(BaseModel): + date_: Annotated[str, pydantic.Field(alias="date")] + r"""Date of the activity (YYYY-MM-DD format)""" + + model: str + r"""Model slug (e.g., \"openai/gpt-4.1\")""" + + model_permaslug: str + r"""Model permaslug (e.g., \"openai/gpt-4.1-2025-04-14\")""" + + endpoint_id: str + r"""Unique identifier for the endpoint""" + + provider_name: str + r"""Name of the provider serving this endpoint""" + + usage: float + r"""Total cost in USD (OpenRouter credits spent)""" + + byok_usage_inference: float + r"""BYOK inference cost in USD (external credits spent)""" + + requests: float + r"""Number of requests made""" + + prompt_tokens: float + r"""Total prompt tokens used""" + + completion_tokens: float + r"""Total completion tokens generated""" + + reasoning_tokens: float + r"""Total reasoning tokens used""" diff --git a/src/openrouter/models/assistantmessage.py b/src/openrouter/models/assistantmessage.py new file mode 100644 index 0000000..b9a8d68 --- /dev/null +++ b/src/openrouter/models/assistantmessage.py @@ -0,0 +1,88 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .chatmessagecontentitem import ( + ChatMessageContentItem, + ChatMessageContentItemTypedDict, +) +from .chatmessagetoolcall import ChatMessageToolCall, ChatMessageToolCallTypedDict +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from openrouter.utils import validate_const +import pydantic +from pydantic import model_serializer +from pydantic.functional_validators import AfterValidator +from typing import List, Literal, Optional, Union +from typing_extensions import Annotated, NotRequired, TypeAliasType, TypedDict + + +AssistantMessageContentTypedDict = TypeAliasType( + "AssistantMessageContentTypedDict", + Union[str, List[ChatMessageContentItemTypedDict]], +) + + +AssistantMessageContent = TypeAliasType( + "AssistantMessageContent", Union[str, List[ChatMessageContentItem]] +) + + +class AssistantMessageTypedDict(TypedDict): + role: Literal["assistant"] + content: NotRequired[Nullable[AssistantMessageContentTypedDict]] + name: NotRequired[str] + tool_calls: NotRequired[List[ChatMessageToolCallTypedDict]] + refusal: NotRequired[Nullable[str]] + reasoning: NotRequired[Nullable[str]] + + +class AssistantMessage(BaseModel): + ROLE: Annotated[ + Annotated[Literal["assistant"], AfterValidator(validate_const("assistant"))], + pydantic.Field(alias="role"), + ] = "assistant" + + content: OptionalNullable[AssistantMessageContent] = UNSET + + name: Optional[str] = None + + tool_calls: Optional[List[ChatMessageToolCall]] = None + + refusal: OptionalNullable[str] = UNSET + + reasoning: OptionalNullable[str] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["content", "name", "tool_calls", "refusal", "reasoning"] + nullable_fields = ["content", "refusal", "reasoning"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/badgatewayresponseerrordata.py b/src/openrouter/models/badgatewayresponseerrordata.py new file mode 100644 index 0000000..c1740ad --- /dev/null +++ b/src/openrouter/models/badgatewayresponseerrordata.py @@ -0,0 +1,61 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from pydantic import model_serializer +from typing import Any, Dict +from typing_extensions import NotRequired, TypedDict + + +class BadGatewayResponseErrorDataTypedDict(TypedDict): + r"""Error data for BadGatewayResponse""" + + code: int + message: str + metadata: NotRequired[Nullable[Dict[str, Nullable[Any]]]] + + +class BadGatewayResponseErrorData(BaseModel): + r"""Error data for BadGatewayResponse""" + + code: int + + message: str + + metadata: OptionalNullable[Dict[str, Nullable[Any]]] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["metadata"] + nullable_fields = ["metadata"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/badrequestresponseerrordata.py b/src/openrouter/models/badrequestresponseerrordata.py new file mode 100644 index 0000000..caaacbd --- /dev/null +++ b/src/openrouter/models/badrequestresponseerrordata.py @@ -0,0 +1,61 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from pydantic import model_serializer +from typing import Any, Dict +from typing_extensions import NotRequired, TypedDict + + +class BadRequestResponseErrorDataTypedDict(TypedDict): + r"""Error data for BadRequestResponse""" + + code: int + message: str + metadata: NotRequired[Nullable[Dict[str, Nullable[Any]]]] + + +class BadRequestResponseErrorData(BaseModel): + r"""Error data for BadRequestResponse""" + + code: int + + message: str + + metadata: OptionalNullable[Dict[str, Nullable[Any]]] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["metadata"] + nullable_fields = ["metadata"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/chatcompletionfinishreason.py b/src/openrouter/models/chatcompletionfinishreason.py new file mode 100644 index 0000000..686462c --- /dev/null +++ b/src/openrouter/models/chatcompletionfinishreason.py @@ -0,0 +1,17 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import UnrecognizedStr +from typing import Literal, Union + + +ChatCompletionFinishReason = Union[ + Literal[ + "tool_calls", + "stop", + "length", + "content_filter", + "error", + ], + UnrecognizedStr, +] diff --git a/src/openrouter/models/chaterror.py b/src/openrouter/models/chaterror.py new file mode 100644 index 0000000..b0c2d93 --- /dev/null +++ b/src/openrouter/models/chaterror.py @@ -0,0 +1,66 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from pydantic import model_serializer +from typing import Union +from typing_extensions import NotRequired, TypeAliasType, TypedDict + + +CodeTypedDict = TypeAliasType("CodeTypedDict", Union[str, float]) + + +Code = TypeAliasType("Code", Union[str, float]) + + +class ChatErrorErrorTypedDict(TypedDict): + code: Nullable[CodeTypedDict] + message: str + param: NotRequired[Nullable[str]] + type: NotRequired[Nullable[str]] + + +class ChatErrorError(BaseModel): + code: Nullable[Code] + + message: str + + param: OptionalNullable[str] = UNSET + + type: OptionalNullable[str] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["param", "type"] + nullable_fields = ["code", "param", "type"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/chatgenerationparams.py b/src/openrouter/models/chatgenerationparams.py new file mode 100644 index 0000000..7cc6dd7 --- /dev/null +++ b/src/openrouter/models/chatgenerationparams.py @@ -0,0 +1,291 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .chatstreamoptions import ChatStreamOptions, ChatStreamOptionsTypedDict +from .message import Message, MessageTypedDict +from .reasoningsummaryverbosity import ReasoningSummaryVerbosity +from .responseformatjsonschema import ( + ResponseFormatJSONSchema, + ResponseFormatJSONSchemaTypedDict, +) +from .responseformattextgrammar import ( + ResponseFormatTextGrammar, + ResponseFormatTextGrammarTypedDict, +) +from .tooldefinitionjson import ToolDefinitionJSON, ToolDefinitionJSONTypedDict +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, + UnrecognizedStr, +) +from openrouter.utils import validate_const, validate_open_enum +import pydantic +from pydantic import model_serializer +from pydantic.functional_validators import AfterValidator, PlainValidator +from typing import Any, Dict, List, Literal, Optional, Union +from typing_extensions import Annotated, NotRequired, TypeAliasType, TypedDict + + +Effort = Union[ + Literal[ + "minimal", + "low", + "medium", + "high", + ], + UnrecognizedStr, +] + + +class ReasoningTypedDict(TypedDict): + effort: NotRequired[Nullable[Effort]] + summary: NotRequired[Nullable[ReasoningSummaryVerbosity]] + + +class Reasoning(BaseModel): + effort: Annotated[ + OptionalNullable[Effort], PlainValidator(validate_open_enum(False)) + ] = UNSET + + summary: Annotated[ + OptionalNullable[ReasoningSummaryVerbosity], + PlainValidator(validate_open_enum(False)), + ] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["effort", "summary"] + nullable_fields = ["effort", "summary"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m + + +class ChatGenerationParamsResponseFormatPythonTypedDict(TypedDict): + type: Literal["python"] + + +class ChatGenerationParamsResponseFormatPython(BaseModel): + TYPE: Annotated[ + Annotated[Literal["python"], AfterValidator(validate_const("python"))], + pydantic.Field(alias="type"), + ] = "python" + + +class ChatGenerationParamsResponseFormatJSONObjectTypedDict(TypedDict): + type: Literal["json_object"] + + +class ChatGenerationParamsResponseFormatJSONObject(BaseModel): + TYPE: Annotated[ + Annotated[ + Literal["json_object"], AfterValidator(validate_const("json_object")) + ], + pydantic.Field(alias="type"), + ] = "json_object" + + +class ChatGenerationParamsResponseFormatTextTypedDict(TypedDict): + type: Literal["text"] + + +class ChatGenerationParamsResponseFormatText(BaseModel): + TYPE: Annotated[ + Annotated[Literal["text"], AfterValidator(validate_const("text"))], + pydantic.Field(alias="type"), + ] = "text" + + +ChatGenerationParamsResponseFormatUnionTypedDict = TypeAliasType( + "ChatGenerationParamsResponseFormatUnionTypedDict", + Union[ + ChatGenerationParamsResponseFormatTextTypedDict, + ChatGenerationParamsResponseFormatJSONObjectTypedDict, + ChatGenerationParamsResponseFormatPythonTypedDict, + ResponseFormatJSONSchemaTypedDict, + ResponseFormatTextGrammarTypedDict, + ], +) + + +ChatGenerationParamsResponseFormatUnion = TypeAliasType( + "ChatGenerationParamsResponseFormatUnion", + Union[ + ChatGenerationParamsResponseFormatText, + ChatGenerationParamsResponseFormatJSONObject, + ChatGenerationParamsResponseFormatPython, + ResponseFormatJSONSchema, + ResponseFormatTextGrammar, + ], +) + + +ChatGenerationParamsStopTypedDict = TypeAliasType( + "ChatGenerationParamsStopTypedDict", Union[str, List[str]] +) + + +ChatGenerationParamsStop = TypeAliasType( + "ChatGenerationParamsStop", Union[str, List[str]] +) + + +class ChatGenerationParamsTypedDict(TypedDict): + messages: List[MessageTypedDict] + model: NotRequired[str] + models: NotRequired[List[str]] + frequency_penalty: NotRequired[Nullable[float]] + logit_bias: NotRequired[Nullable[Dict[str, float]]] + logprobs: NotRequired[Nullable[bool]] + top_logprobs: NotRequired[Nullable[float]] + max_completion_tokens: NotRequired[Nullable[float]] + max_tokens: NotRequired[Nullable[float]] + metadata: NotRequired[Dict[str, str]] + presence_penalty: NotRequired[Nullable[float]] + reasoning: NotRequired[ReasoningTypedDict] + response_format: NotRequired[ChatGenerationParamsResponseFormatUnionTypedDict] + seed: NotRequired[Nullable[int]] + stop: NotRequired[Nullable[ChatGenerationParamsStopTypedDict]] + stream: NotRequired[bool] + stream_options: NotRequired[Nullable[ChatStreamOptionsTypedDict]] + temperature: NotRequired[Nullable[float]] + tool_choice: NotRequired[Any] + tools: NotRequired[List[ToolDefinitionJSONTypedDict]] + top_p: NotRequired[Nullable[float]] + user: NotRequired[str] + + +class ChatGenerationParams(BaseModel): + messages: List[Message] + + model: Optional[str] = None + + models: Optional[List[str]] = None + + frequency_penalty: OptionalNullable[float] = UNSET + + logit_bias: OptionalNullable[Dict[str, float]] = UNSET + + logprobs: OptionalNullable[bool] = UNSET + + top_logprobs: OptionalNullable[float] = UNSET + + max_completion_tokens: OptionalNullable[float] = UNSET + + max_tokens: OptionalNullable[float] = UNSET + + metadata: Optional[Dict[str, str]] = None + + presence_penalty: OptionalNullable[float] = UNSET + + reasoning: Optional[Reasoning] = None + + response_format: Optional[ChatGenerationParamsResponseFormatUnion] = None + + seed: OptionalNullable[int] = UNSET + + stop: OptionalNullable[ChatGenerationParamsStop] = UNSET + + stream: Optional[bool] = False + + stream_options: OptionalNullable[ChatStreamOptions] = UNSET + + temperature: OptionalNullable[float] = UNSET + + tool_choice: Optional[Any] = None + + tools: Optional[List[ToolDefinitionJSON]] = None + + top_p: OptionalNullable[float] = UNSET + + user: Optional[str] = None + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = [ + "model", + "models", + "frequency_penalty", + "logit_bias", + "logprobs", + "top_logprobs", + "max_completion_tokens", + "max_tokens", + "metadata", + "presence_penalty", + "reasoning", + "response_format", + "seed", + "stop", + "stream", + "stream_options", + "temperature", + "tool_choice", + "tools", + "top_p", + "user", + ] + nullable_fields = [ + "frequency_penalty", + "logit_bias", + "logprobs", + "top_logprobs", + "max_completion_tokens", + "max_tokens", + "presence_penalty", + "seed", + "stop", + "stream_options", + "temperature", + "top_p", + ] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/chatgenerationtokenusage.py b/src/openrouter/models/chatgenerationtokenusage.py new file mode 100644 index 0000000..e8aa115 --- /dev/null +++ b/src/openrouter/models/chatgenerationtokenusage.py @@ -0,0 +1,134 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from pydantic import model_serializer +from typing import Optional +from typing_extensions import NotRequired, TypedDict + + +class CompletionTokensDetailsTypedDict(TypedDict): + reasoning_tokens: NotRequired[Nullable[float]] + audio_tokens: NotRequired[Nullable[float]] + accepted_prediction_tokens: NotRequired[Nullable[float]] + rejected_prediction_tokens: NotRequired[Nullable[float]] + + +class CompletionTokensDetails(BaseModel): + reasoning_tokens: OptionalNullable[float] = UNSET + + audio_tokens: OptionalNullable[float] = UNSET + + accepted_prediction_tokens: OptionalNullable[float] = UNSET + + rejected_prediction_tokens: OptionalNullable[float] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = [ + "reasoning_tokens", + "audio_tokens", + "accepted_prediction_tokens", + "rejected_prediction_tokens", + ] + nullable_fields = [ + "reasoning_tokens", + "audio_tokens", + "accepted_prediction_tokens", + "rejected_prediction_tokens", + ] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m + + +class PromptTokensDetailsTypedDict(TypedDict): + cached_tokens: NotRequired[float] + audio_tokens: NotRequired[float] + video_tokens: NotRequired[float] + + +class PromptTokensDetails(BaseModel): + cached_tokens: Optional[float] = None + + audio_tokens: Optional[float] = None + + video_tokens: Optional[float] = None + + +class ChatGenerationTokenUsageTypedDict(TypedDict): + completion_tokens: float + prompt_tokens: float + total_tokens: float + completion_tokens_details: NotRequired[Nullable[CompletionTokensDetailsTypedDict]] + prompt_tokens_details: NotRequired[Nullable[PromptTokensDetailsTypedDict]] + + +class ChatGenerationTokenUsage(BaseModel): + completion_tokens: float + + prompt_tokens: float + + total_tokens: float + + completion_tokens_details: OptionalNullable[CompletionTokensDetails] = UNSET + + prompt_tokens_details: OptionalNullable[PromptTokensDetails] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["completion_tokens_details", "prompt_tokens_details"] + nullable_fields = ["completion_tokens_details", "prompt_tokens_details"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/chatmessagecontentitem.py b/src/openrouter/models/chatmessagecontentitem.py new file mode 100644 index 0000000..2ebd348 --- /dev/null +++ b/src/openrouter/models/chatmessagecontentitem.py @@ -0,0 +1,45 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .chatmessagecontentitemaudio import ( + ChatMessageContentItemAudio, + ChatMessageContentItemAudioTypedDict, +) +from .chatmessagecontentitemimage import ( + ChatMessageContentItemImage, + ChatMessageContentItemImageTypedDict, +) +from .chatmessagecontentitemtext import ( + ChatMessageContentItemText, + ChatMessageContentItemTextTypedDict, +) +from .chatmessagecontentitemvideo import ( + ChatMessageContentItemVideo, + ChatMessageContentItemVideoTypedDict, +) +from openrouter.utils import get_discriminator +from pydantic import Discriminator, Tag +from typing import Union +from typing_extensions import Annotated, TypeAliasType + + +ChatMessageContentItemTypedDict = TypeAliasType( + "ChatMessageContentItemTypedDict", + Union[ + ChatMessageContentItemTextTypedDict, + ChatMessageContentItemImageTypedDict, + ChatMessageContentItemAudioTypedDict, + ChatMessageContentItemVideoTypedDict, + ], +) + + +ChatMessageContentItem = Annotated[ + Union[ + Annotated[ChatMessageContentItemText, Tag("text")], + Annotated[ChatMessageContentItemImage, Tag("image_url")], + Annotated[ChatMessageContentItemAudio, Tag("input_audio")], + Annotated[ChatMessageContentItemVideo, Tag("input_video")], + ], + Discriminator(lambda m: get_discriminator(m, "type", "type")), +] diff --git a/src/openrouter/models/chatmessagecontentitemaudio.py b/src/openrouter/models/chatmessagecontentitemaudio.py new file mode 100644 index 0000000..21a8803 --- /dev/null +++ b/src/openrouter/models/chatmessagecontentitemaudio.py @@ -0,0 +1,55 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel, UnrecognizedStr +from openrouter.utils import validate_const, validate_open_enum +import pydantic +from pydantic.functional_validators import AfterValidator, PlainValidator +from typing import Literal, Union +from typing_extensions import Annotated, TypedDict + + +ChatMessageContentItemAudioFormat = Union[ + Literal[ + "wav", + "mp3", + "flac", + "m4a", + "ogg", + "pcm16", + "pcm24", + ], + UnrecognizedStr, +] + + +class ChatMessageContentItemAudioInputAudioTypedDict(TypedDict): + data: str + format_: ChatMessageContentItemAudioFormat + + +class ChatMessageContentItemAudioInputAudio(BaseModel): + data: str + + format_: Annotated[ + Annotated[ + ChatMessageContentItemAudioFormat, PlainValidator(validate_open_enum(False)) + ], + pydantic.Field(alias="format"), + ] + + +class ChatMessageContentItemAudioTypedDict(TypedDict): + input_audio: ChatMessageContentItemAudioInputAudioTypedDict + type: Literal["input_audio"] + + +class ChatMessageContentItemAudio(BaseModel): + input_audio: ChatMessageContentItemAudioInputAudio + + TYPE: Annotated[ + Annotated[ + Literal["input_audio"], AfterValidator(validate_const("input_audio")) + ], + pydantic.Field(alias="type"), + ] = "input_audio" diff --git a/src/openrouter/models/chatmessagecontentitemimage.py b/src/openrouter/models/chatmessagecontentitemimage.py new file mode 100644 index 0000000..997f4ef --- /dev/null +++ b/src/openrouter/models/chatmessagecontentitemimage.py @@ -0,0 +1,47 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel, UnrecognizedStr +from openrouter.utils import validate_const, validate_open_enum +import pydantic +from pydantic.functional_validators import AfterValidator, PlainValidator +from typing import Literal, Optional, Union +from typing_extensions import Annotated, NotRequired, TypedDict + + +ChatMessageContentItemImageDetail = Union[ + Literal[ + "auto", + "low", + "high", + ], + UnrecognizedStr, +] + + +class ImageURLTypedDict(TypedDict): + url: str + detail: NotRequired[ChatMessageContentItemImageDetail] + + +class ImageURL(BaseModel): + url: str + + detail: Annotated[ + Optional[ChatMessageContentItemImageDetail], + PlainValidator(validate_open_enum(False)), + ] = None + + +class ChatMessageContentItemImageTypedDict(TypedDict): + image_url: ImageURLTypedDict + type: Literal["image_url"] + + +class ChatMessageContentItemImage(BaseModel): + image_url: ImageURL + + TYPE: Annotated[ + Annotated[Literal["image_url"], AfterValidator(validate_const("image_url"))], + pydantic.Field(alias="type"), + ] = "image_url" diff --git a/src/openrouter/models/chatmessagecontentitemtext.py b/src/openrouter/models/chatmessagecontentitemtext.py new file mode 100644 index 0000000..c791fa9 --- /dev/null +++ b/src/openrouter/models/chatmessagecontentitemtext.py @@ -0,0 +1,23 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel +from openrouter.utils import validate_const +import pydantic +from pydantic.functional_validators import AfterValidator +from typing import Literal +from typing_extensions import Annotated, TypedDict + + +class ChatMessageContentItemTextTypedDict(TypedDict): + text: str + type: Literal["text"] + + +class ChatMessageContentItemText(BaseModel): + text: str + + TYPE: Annotated[ + Annotated[Literal["text"], AfterValidator(validate_const("text"))], + pydantic.Field(alias="type"), + ] = "text" diff --git a/src/openrouter/models/chatmessagecontentitemvideo.py b/src/openrouter/models/chatmessagecontentitemvideo.py new file mode 100644 index 0000000..023ae67 --- /dev/null +++ b/src/openrouter/models/chatmessagecontentitemvideo.py @@ -0,0 +1,33 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel +from openrouter.utils import validate_const +import pydantic +from pydantic.functional_validators import AfterValidator +from typing import Literal +from typing_extensions import Annotated, TypedDict + + +class VideoURLTypedDict(TypedDict): + url: str + + +class VideoURL(BaseModel): + url: str + + +class ChatMessageContentItemVideoTypedDict(TypedDict): + video_url: VideoURLTypedDict + type: Literal["input_video"] + + +class ChatMessageContentItemVideo(BaseModel): + video_url: VideoURL + + TYPE: Annotated[ + Annotated[ + Literal["input_video"], AfterValidator(validate_const("input_video")) + ], + pydantic.Field(alias="type"), + ] = "input_video" diff --git a/src/openrouter/models/chatmessagetokenlogprob.py b/src/openrouter/models/chatmessagetokenlogprob.py new file mode 100644 index 0000000..f752fce --- /dev/null +++ b/src/openrouter/models/chatmessagetokenlogprob.py @@ -0,0 +1,99 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel, Nullable, UNSET_SENTINEL +import pydantic +from pydantic import model_serializer +from typing import List +from typing_extensions import Annotated, TypedDict + + +class TopLogprobTypedDict(TypedDict): + token: str + logprob: float + bytes_: Nullable[List[float]] + + +class TopLogprob(BaseModel): + token: str + + logprob: float + + bytes_: Annotated[Nullable[List[float]], pydantic.Field(alias="bytes")] + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = [] + nullable_fields = ["bytes"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m + + +class ChatMessageTokenLogprobTypedDict(TypedDict): + token: str + logprob: float + bytes_: Nullable[List[float]] + top_logprobs: List[TopLogprobTypedDict] + + +class ChatMessageTokenLogprob(BaseModel): + token: str + + logprob: float + + bytes_: Annotated[Nullable[List[float]], pydantic.Field(alias="bytes")] + + top_logprobs: List[TopLogprob] + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = [] + nullable_fields = ["bytes"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/chatmessagetokenlogprobs.py b/src/openrouter/models/chatmessagetokenlogprobs.py new file mode 100644 index 0000000..fa9e714 --- /dev/null +++ b/src/openrouter/models/chatmessagetokenlogprobs.py @@ -0,0 +1,52 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .chatmessagetokenlogprob import ( + ChatMessageTokenLogprob, + ChatMessageTokenLogprobTypedDict, +) +from openrouter.types import BaseModel, Nullable, UNSET_SENTINEL +from pydantic import model_serializer +from typing import List +from typing_extensions import TypedDict + + +class ChatMessageTokenLogprobsTypedDict(TypedDict): + content: Nullable[List[ChatMessageTokenLogprobTypedDict]] + refusal: Nullable[List[ChatMessageTokenLogprobTypedDict]] + + +class ChatMessageTokenLogprobs(BaseModel): + content: Nullable[List[ChatMessageTokenLogprob]] + + refusal: Nullable[List[ChatMessageTokenLogprob]] + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = [] + nullable_fields = ["content", "refusal"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/chatmessagetoolcall.py b/src/openrouter/models/chatmessagetoolcall.py new file mode 100644 index 0000000..e8890e3 --- /dev/null +++ b/src/openrouter/models/chatmessagetoolcall.py @@ -0,0 +1,37 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel +from openrouter.utils import validate_const +import pydantic +from pydantic.functional_validators import AfterValidator +from typing import Literal +from typing_extensions import Annotated, TypedDict + + +class ChatMessageToolCallFunctionTypedDict(TypedDict): + name: str + arguments: str + + +class ChatMessageToolCallFunction(BaseModel): + name: str + + arguments: str + + +class ChatMessageToolCallTypedDict(TypedDict): + id: str + function: ChatMessageToolCallFunctionTypedDict + type: Literal["function"] + + +class ChatMessageToolCall(BaseModel): + id: str + + function: ChatMessageToolCallFunction + + TYPE: Annotated[ + Annotated[Literal["function"], AfterValidator(validate_const("function"))], + pydantic.Field(alias="type"), + ] = "function" diff --git a/src/openrouter/models/chatresponse.py b/src/openrouter/models/chatresponse.py new file mode 100644 index 0000000..1e993a1 --- /dev/null +++ b/src/openrouter/models/chatresponse.py @@ -0,0 +1,83 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .chatgenerationtokenusage import ( + ChatGenerationTokenUsage, + ChatGenerationTokenUsageTypedDict, +) +from .chatresponsechoice import ChatResponseChoice, ChatResponseChoiceTypedDict +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from openrouter.utils import validate_const +import pydantic +from pydantic import model_serializer +from pydantic.functional_validators import AfterValidator +from typing import List, Literal, Optional +from typing_extensions import Annotated, NotRequired, TypedDict + + +class ChatResponseTypedDict(TypedDict): + id: str + choices: List[ChatResponseChoiceTypedDict] + created: float + model: str + object: Literal["chat.completion"] + system_fingerprint: NotRequired[Nullable[str]] + usage: NotRequired[ChatGenerationTokenUsageTypedDict] + + +class ChatResponse(BaseModel): + id: str + + choices: List[ChatResponseChoice] + + created: float + + model: str + + OBJECT: Annotated[ + Annotated[ + Literal["chat.completion"], + AfterValidator(validate_const("chat.completion")), + ], + pydantic.Field(alias="object"), + ] = "chat.completion" + + system_fingerprint: OptionalNullable[str] = UNSET + + usage: Optional[ChatGenerationTokenUsage] = None + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["system_fingerprint", "usage"] + nullable_fields = ["system_fingerprint"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/chatresponsechoice.py b/src/openrouter/models/chatresponsechoice.py new file mode 100644 index 0000000..9592bf1 --- /dev/null +++ b/src/openrouter/models/chatresponsechoice.py @@ -0,0 +1,69 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .assistantmessage import AssistantMessage, AssistantMessageTypedDict +from .chatcompletionfinishreason import ChatCompletionFinishReason +from .chatmessagetokenlogprobs import ( + ChatMessageTokenLogprobs, + ChatMessageTokenLogprobsTypedDict, +) +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from openrouter.utils import validate_open_enum +from pydantic import model_serializer +from pydantic.functional_validators import PlainValidator +from typing_extensions import Annotated, NotRequired, TypedDict + + +class ChatResponseChoiceTypedDict(TypedDict): + finish_reason: Nullable[ChatCompletionFinishReason] + index: float + message: AssistantMessageTypedDict + logprobs: NotRequired[Nullable[ChatMessageTokenLogprobsTypedDict]] + + +class ChatResponseChoice(BaseModel): + finish_reason: Annotated[ + Nullable[ChatCompletionFinishReason], PlainValidator(validate_open_enum(False)) + ] + + index: float + + message: AssistantMessage + + logprobs: OptionalNullable[ChatMessageTokenLogprobs] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["logprobs"] + nullable_fields = ["finish_reason", "logprobs"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/chatstreamingchoice.py b/src/openrouter/models/chatstreamingchoice.py new file mode 100644 index 0000000..b64b8ff --- /dev/null +++ b/src/openrouter/models/chatstreamingchoice.py @@ -0,0 +1,72 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .chatcompletionfinishreason import ChatCompletionFinishReason +from .chatmessagetokenlogprobs import ( + ChatMessageTokenLogprobs, + ChatMessageTokenLogprobsTypedDict, +) +from .chatstreamingmessagechunk import ( + ChatStreamingMessageChunk, + ChatStreamingMessageChunkTypedDict, +) +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from openrouter.utils import validate_open_enum +from pydantic import model_serializer +from pydantic.functional_validators import PlainValidator +from typing_extensions import Annotated, NotRequired, TypedDict + + +class ChatStreamingChoiceTypedDict(TypedDict): + delta: ChatStreamingMessageChunkTypedDict + finish_reason: Nullable[ChatCompletionFinishReason] + index: float + logprobs: NotRequired[Nullable[ChatMessageTokenLogprobsTypedDict]] + + +class ChatStreamingChoice(BaseModel): + delta: ChatStreamingMessageChunk + + finish_reason: Annotated[ + Nullable[ChatCompletionFinishReason], PlainValidator(validate_open_enum(False)) + ] + + index: float + + logprobs: OptionalNullable[ChatMessageTokenLogprobs] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["logprobs"] + nullable_fields = ["finish_reason", "logprobs"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/chatstreamingmessagechunk.py b/src/openrouter/models/chatstreamingmessagechunk.py new file mode 100644 index 0000000..dec4faf --- /dev/null +++ b/src/openrouter/models/chatstreamingmessagechunk.py @@ -0,0 +1,70 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .chatstreamingmessagetoolcall import ( + ChatStreamingMessageToolCall, + ChatStreamingMessageToolCallTypedDict, +) +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from pydantic import model_serializer +from typing import List, Literal, Optional +from typing_extensions import NotRequired, TypedDict + + +ChatStreamingMessageChunkRole = Literal["assistant",] + + +class ChatStreamingMessageChunkTypedDict(TypedDict): + role: NotRequired[ChatStreamingMessageChunkRole] + content: NotRequired[Nullable[str]] + reasoning: NotRequired[Nullable[str]] + refusal: NotRequired[Nullable[str]] + tool_calls: NotRequired[List[ChatStreamingMessageToolCallTypedDict]] + + +class ChatStreamingMessageChunk(BaseModel): + role: Optional[ChatStreamingMessageChunkRole] = None + + content: OptionalNullable[str] = UNSET + + reasoning: OptionalNullable[str] = UNSET + + refusal: OptionalNullable[str] = UNSET + + tool_calls: Optional[List[ChatStreamingMessageToolCall]] = None + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["role", "content", "reasoning", "refusal", "tool_calls"] + nullable_fields = ["content", "reasoning", "refusal"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/chatstreamingmessagetoolcall.py b/src/openrouter/models/chatstreamingmessagetoolcall.py new file mode 100644 index 0000000..6cab64d --- /dev/null +++ b/src/openrouter/models/chatstreamingmessagetoolcall.py @@ -0,0 +1,42 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel +from openrouter.utils import validate_const +import pydantic +from pydantic.functional_validators import AfterValidator +from typing import Literal, Optional +from typing_extensions import Annotated, NotRequired, TypedDict + + +class ChatStreamingMessageToolCallFunctionTypedDict(TypedDict): + name: NotRequired[str] + arguments: NotRequired[str] + + +class ChatStreamingMessageToolCallFunction(BaseModel): + name: Optional[str] = None + + arguments: Optional[str] = None + + +class ChatStreamingMessageToolCallTypedDict(TypedDict): + index: float + id: NotRequired[str] + type: Literal["function"] + function: NotRequired[ChatStreamingMessageToolCallFunctionTypedDict] + + +class ChatStreamingMessageToolCall(BaseModel): + index: float + + id: Optional[str] = None + + TYPE: Annotated[ + Annotated[ + Optional[Literal["function"]], AfterValidator(validate_const("function")) + ], + pydantic.Field(alias="type"), + ] = "function" + + function: Optional[ChatStreamingMessageToolCallFunction] = None diff --git a/src/openrouter/models/chatstreamingresponsechunk.py b/src/openrouter/models/chatstreamingresponsechunk.py new file mode 100644 index 0000000..7c32481 --- /dev/null +++ b/src/openrouter/models/chatstreamingresponsechunk.py @@ -0,0 +1,105 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .chatgenerationtokenusage import ( + ChatGenerationTokenUsage, + ChatGenerationTokenUsageTypedDict, +) +from .chatstreamingchoice import ChatStreamingChoice, ChatStreamingChoiceTypedDict +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from openrouter.utils import validate_const +import pydantic +from pydantic import model_serializer +from pydantic.functional_validators import AfterValidator +from typing import List, Literal, Optional +from typing_extensions import Annotated, NotRequired, TypedDict + + +class ChatStreamingResponseChunkErrorTypedDict(TypedDict): + message: str + code: float + + +class ChatStreamingResponseChunkError(BaseModel): + message: str + + code: float + + +class ChatStreamingResponseChunkDataTypedDict(TypedDict): + id: str + choices: List[ChatStreamingChoiceTypedDict] + created: float + model: str + object: Literal["chat.completion.chunk"] + system_fingerprint: NotRequired[Nullable[str]] + error: NotRequired[ChatStreamingResponseChunkErrorTypedDict] + usage: NotRequired[ChatGenerationTokenUsageTypedDict] + + +class ChatStreamingResponseChunkData(BaseModel): + id: str + + choices: List[ChatStreamingChoice] + + created: float + + model: str + + OBJECT: Annotated[ + Annotated[ + Literal["chat.completion.chunk"], + AfterValidator(validate_const("chat.completion.chunk")), + ], + pydantic.Field(alias="object"), + ] = "chat.completion.chunk" + + system_fingerprint: OptionalNullable[str] = UNSET + + error: Optional[ChatStreamingResponseChunkError] = None + + usage: Optional[ChatGenerationTokenUsage] = None + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["system_fingerprint", "error", "usage"] + nullable_fields = ["system_fingerprint"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m + + +class ChatStreamingResponseChunkTypedDict(TypedDict): + data: ChatStreamingResponseChunkDataTypedDict + + +class ChatStreamingResponseChunk(BaseModel): + data: ChatStreamingResponseChunkData diff --git a/src/openrouter/models/chatstreamoptions.py b/src/openrouter/models/chatstreamoptions.py new file mode 100644 index 0000000..6e4d94d --- /dev/null +++ b/src/openrouter/models/chatstreamoptions.py @@ -0,0 +1,14 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel +from typing import Optional +from typing_extensions import NotRequired, TypedDict + + +class ChatStreamOptionsTypedDict(TypedDict): + include_usage: NotRequired[bool] + + +class ChatStreamOptions(BaseModel): + include_usage: Optional[bool] = None diff --git a/src/openrouter/models/completionchoice.py b/src/openrouter/models/completionchoice.py new file mode 100644 index 0000000..3e68a00 --- /dev/null +++ b/src/openrouter/models/completionchoice.py @@ -0,0 +1,69 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .completionlogprobs import CompletionLogprobs, CompletionLogprobsTypedDict +from openrouter.types import BaseModel, Nullable, UNSET_SENTINEL, UnrecognizedStr +from openrouter.utils import validate_open_enum +from pydantic import model_serializer +from pydantic.functional_validators import PlainValidator +from typing import Literal, Union +from typing_extensions import Annotated, TypedDict + + +CompletionFinishReason = Union[ + Literal[ + "stop", + "length", + "content_filter", + ], + UnrecognizedStr, +] + + +class CompletionChoiceTypedDict(TypedDict): + text: str + index: float + logprobs: Nullable[CompletionLogprobsTypedDict] + finish_reason: Nullable[CompletionFinishReason] + + +class CompletionChoice(BaseModel): + text: str + + index: float + + logprobs: Nullable[CompletionLogprobs] + + finish_reason: Annotated[ + Nullable[CompletionFinishReason], PlainValidator(validate_open_enum(False)) + ] + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = [] + nullable_fields = ["logprobs", "finish_reason"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/completioncreateparams.py b/src/openrouter/models/completioncreateparams.py new file mode 100644 index 0000000..3a81d2e --- /dev/null +++ b/src/openrouter/models/completioncreateparams.py @@ -0,0 +1,277 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .responseformatjsonschema import ( + ResponseFormatJSONSchema, + ResponseFormatJSONSchemaTypedDict, +) +from .responseformattextgrammar import ( + ResponseFormatTextGrammar, + ResponseFormatTextGrammarTypedDict, +) +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from openrouter.utils import validate_const +import pydantic +from pydantic import model_serializer +from pydantic.functional_validators import AfterValidator +from typing import Dict, List, Literal, Optional, Union +from typing_extensions import Annotated, NotRequired, TypeAliasType, TypedDict + + +PromptTypedDict = TypeAliasType( + "PromptTypedDict", Union[str, List[str], List[float], List[List[float]]] +) + + +Prompt = TypeAliasType("Prompt", Union[str, List[str], List[float], List[List[float]]]) + + +CompletionCreateParamsStopTypedDict = TypeAliasType( + "CompletionCreateParamsStopTypedDict", Union[str, List[str]] +) + + +CompletionCreateParamsStop = TypeAliasType( + "CompletionCreateParamsStop", Union[str, List[str]] +) + + +class StreamOptionsTypedDict(TypedDict): + include_usage: NotRequired[Nullable[bool]] + + +class StreamOptions(BaseModel): + include_usage: OptionalNullable[bool] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["include_usage"] + nullable_fields = ["include_usage"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m + + +class CompletionCreateParamsResponseFormatPythonTypedDict(TypedDict): + type: Literal["python"] + + +class CompletionCreateParamsResponseFormatPython(BaseModel): + TYPE: Annotated[ + Annotated[Literal["python"], AfterValidator(validate_const("python"))], + pydantic.Field(alias="type"), + ] = "python" + + +class CompletionCreateParamsResponseFormatJSONObjectTypedDict(TypedDict): + type: Literal["json_object"] + + +class CompletionCreateParamsResponseFormatJSONObject(BaseModel): + TYPE: Annotated[ + Annotated[ + Literal["json_object"], AfterValidator(validate_const("json_object")) + ], + pydantic.Field(alias="type"), + ] = "json_object" + + +class CompletionCreateParamsResponseFormatTextTypedDict(TypedDict): + type: Literal["text"] + + +class CompletionCreateParamsResponseFormatText(BaseModel): + TYPE: Annotated[ + Annotated[Literal["text"], AfterValidator(validate_const("text"))], + pydantic.Field(alias="type"), + ] = "text" + + +CompletionCreateParamsResponseFormatUnionTypedDict = TypeAliasType( + "CompletionCreateParamsResponseFormatUnionTypedDict", + Union[ + CompletionCreateParamsResponseFormatTextTypedDict, + CompletionCreateParamsResponseFormatJSONObjectTypedDict, + CompletionCreateParamsResponseFormatPythonTypedDict, + ResponseFormatJSONSchemaTypedDict, + ResponseFormatTextGrammarTypedDict, + ], +) + + +CompletionCreateParamsResponseFormatUnion = TypeAliasType( + "CompletionCreateParamsResponseFormatUnion", + Union[ + CompletionCreateParamsResponseFormatText, + CompletionCreateParamsResponseFormatJSONObject, + CompletionCreateParamsResponseFormatPython, + ResponseFormatJSONSchema, + ResponseFormatTextGrammar, + ], +) + + +class CompletionCreateParamsTypedDict(TypedDict): + prompt: PromptTypedDict + model: NotRequired[str] + models: NotRequired[List[str]] + best_of: NotRequired[Nullable[int]] + echo: NotRequired[Nullable[bool]] + frequency_penalty: NotRequired[Nullable[float]] + logit_bias: NotRequired[Nullable[Dict[str, float]]] + logprobs: NotRequired[Nullable[int]] + max_tokens: NotRequired[Nullable[int]] + n: NotRequired[Nullable[int]] + presence_penalty: NotRequired[Nullable[float]] + seed: NotRequired[Nullable[int]] + stop: NotRequired[Nullable[CompletionCreateParamsStopTypedDict]] + stream: NotRequired[bool] + stream_options: NotRequired[Nullable[StreamOptionsTypedDict]] + suffix: NotRequired[Nullable[str]] + temperature: NotRequired[Nullable[float]] + top_p: NotRequired[Nullable[float]] + user: NotRequired[str] + metadata: NotRequired[Nullable[Dict[str, str]]] + response_format: NotRequired[ + Nullable[CompletionCreateParamsResponseFormatUnionTypedDict] + ] + + +class CompletionCreateParams(BaseModel): + prompt: Prompt + + model: Optional[str] = None + + models: Optional[List[str]] = None + + best_of: OptionalNullable[int] = UNSET + + echo: OptionalNullable[bool] = UNSET + + frequency_penalty: OptionalNullable[float] = UNSET + + logit_bias: OptionalNullable[Dict[str, float]] = UNSET + + logprobs: OptionalNullable[int] = UNSET + + max_tokens: OptionalNullable[int] = UNSET + + n: OptionalNullable[int] = UNSET + + presence_penalty: OptionalNullable[float] = UNSET + + seed: OptionalNullable[int] = UNSET + + stop: OptionalNullable[CompletionCreateParamsStop] = UNSET + + stream: Optional[bool] = False + + stream_options: OptionalNullable[StreamOptions] = UNSET + + suffix: OptionalNullable[str] = UNSET + + temperature: OptionalNullable[float] = UNSET + + top_p: OptionalNullable[float] = UNSET + + user: Optional[str] = None + + metadata: OptionalNullable[Dict[str, str]] = UNSET + + response_format: OptionalNullable[CompletionCreateParamsResponseFormatUnion] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = [ + "model", + "models", + "best_of", + "echo", + "frequency_penalty", + "logit_bias", + "logprobs", + "max_tokens", + "n", + "presence_penalty", + "seed", + "stop", + "stream", + "stream_options", + "suffix", + "temperature", + "top_p", + "user", + "metadata", + "response_format", + ] + nullable_fields = [ + "best_of", + "echo", + "frequency_penalty", + "logit_bias", + "logprobs", + "max_tokens", + "n", + "presence_penalty", + "seed", + "stop", + "stream_options", + "suffix", + "temperature", + "top_p", + "metadata", + "response_format", + ] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/completionlogprobs.py b/src/openrouter/models/completionlogprobs.py new file mode 100644 index 0000000..758ccd1 --- /dev/null +++ b/src/openrouter/models/completionlogprobs.py @@ -0,0 +1,54 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel, Nullable, UNSET_SENTINEL +from pydantic import model_serializer +from typing import Dict, List +from typing_extensions import TypedDict + + +class CompletionLogprobsTypedDict(TypedDict): + tokens: List[str] + token_logprobs: List[float] + top_logprobs: Nullable[List[Dict[str, float]]] + text_offset: List[float] + + +class CompletionLogprobs(BaseModel): + tokens: List[str] + + token_logprobs: List[float] + + top_logprobs: Nullable[List[Dict[str, float]]] + + text_offset: List[float] + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = [] + nullable_fields = ["top_logprobs"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/completionresponse.py b/src/openrouter/models/completionresponse.py new file mode 100644 index 0000000..12bde5f --- /dev/null +++ b/src/openrouter/models/completionresponse.py @@ -0,0 +1,43 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .completionchoice import CompletionChoice, CompletionChoiceTypedDict +from .completionusage import CompletionUsage, CompletionUsageTypedDict +from openrouter.types import BaseModel +from openrouter.utils import validate_const +import pydantic +from pydantic.functional_validators import AfterValidator +from typing import List, Literal, Optional +from typing_extensions import Annotated, NotRequired, TypedDict + + +class CompletionResponseTypedDict(TypedDict): + id: str + created: float + model: str + choices: List[CompletionChoiceTypedDict] + object: Literal["text_completion"] + system_fingerprint: NotRequired[str] + usage: NotRequired[CompletionUsageTypedDict] + + +class CompletionResponse(BaseModel): + id: str + + created: float + + model: str + + choices: List[CompletionChoice] + + OBJECT: Annotated[ + Annotated[ + Literal["text_completion"], + AfterValidator(validate_const("text_completion")), + ], + pydantic.Field(alias="object"), + ] = "text_completion" + + system_fingerprint: Optional[str] = None + + usage: Optional[CompletionUsage] = None diff --git a/src/openrouter/models/completionusage.py b/src/openrouter/models/completionusage.py new file mode 100644 index 0000000..80bba78 --- /dev/null +++ b/src/openrouter/models/completionusage.py @@ -0,0 +1,19 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel +from typing_extensions import TypedDict + + +class CompletionUsageTypedDict(TypedDict): + prompt_tokens: float + completion_tokens: float + total_tokens: float + + +class CompletionUsage(BaseModel): + prompt_tokens: float + + completion_tokens: float + + total_tokens: float diff --git a/src/openrouter/models/createauthkeyscodeop.py b/src/openrouter/models/createauthkeyscodeop.py new file mode 100644 index 0000000..5d07bb8 --- /dev/null +++ b/src/openrouter/models/createauthkeyscodeop.py @@ -0,0 +1,133 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from datetime import datetime +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, + UnrecognizedStr, +) +from openrouter.utils import validate_open_enum +from pydantic import model_serializer +from pydantic.functional_validators import PlainValidator +from typing import Literal, Optional, Union +from typing_extensions import Annotated, NotRequired, TypedDict + + +CreateAuthKeysCodeCodeChallengeMethod = Union[ + Literal[ + "S256", + "plain", + ], + UnrecognizedStr, +] +r"""The method used to generate the code challenge""" + + +class CreateAuthKeysCodeRequestTypedDict(TypedDict): + callback_url: str + r"""The callback URL to redirect to after authorization. Note, only https URLs on ports 443 and 3000 are allowed.""" + code_challenge: NotRequired[str] + r"""PKCE code challenge for enhanced security""" + code_challenge_method: NotRequired[CreateAuthKeysCodeCodeChallengeMethod] + r"""The method used to generate the code challenge""" + limit: NotRequired[float] + r"""Credit limit for the API key to be created""" + expires_at: NotRequired[Nullable[datetime]] + r"""Optional expiration time for the API key to be created""" + + +class CreateAuthKeysCodeRequest(BaseModel): + callback_url: str + r"""The callback URL to redirect to after authorization. Note, only https URLs on ports 443 and 3000 are allowed.""" + + code_challenge: Optional[str] = None + r"""PKCE code challenge for enhanced security""" + + code_challenge_method: Annotated[ + Optional[CreateAuthKeysCodeCodeChallengeMethod], + PlainValidator(validate_open_enum(False)), + ] = None + r"""The method used to generate the code challenge""" + + limit: Optional[float] = None + r"""Credit limit for the API key to be created""" + + expires_at: OptionalNullable[datetime] = UNSET + r"""Optional expiration time for the API key to be created""" + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = [ + "code_challenge", + "code_challenge_method", + "limit", + "expires_at", + ] + nullable_fields = ["expires_at"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m + + +class CreateAuthKeysCodeDataTypedDict(TypedDict): + r"""Auth code data""" + + id: str + r"""The authorization code ID to use in the exchange request""" + app_id: float + r"""The application ID associated with this auth code""" + created_at: str + r"""ISO 8601 timestamp of when the auth code was created""" + + +class CreateAuthKeysCodeData(BaseModel): + r"""Auth code data""" + + id: str + r"""The authorization code ID to use in the exchange request""" + + app_id: float + r"""The application ID associated with this auth code""" + + created_at: str + r"""ISO 8601 timestamp of when the auth code was created""" + + +class CreateAuthKeysCodeResponseTypedDict(TypedDict): + r"""Successfully created authorization code""" + + data: CreateAuthKeysCodeDataTypedDict + r"""Auth code data""" + + +class CreateAuthKeysCodeResponse(BaseModel): + r"""Successfully created authorization code""" + + data: CreateAuthKeysCodeData + r"""Auth code data""" diff --git a/src/openrouter/models/createchargerequest.py b/src/openrouter/models/createchargerequest.py new file mode 100644 index 0000000..7fab3ac --- /dev/null +++ b/src/openrouter/models/createchargerequest.py @@ -0,0 +1,36 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel, UnrecognizedInt +from openrouter.utils import validate_open_enum +from pydantic.functional_validators import PlainValidator +from typing import Literal, Union +from typing_extensions import Annotated, TypedDict + + +ChainID = Union[ + Literal[ + 1, + 137, + 8453, + ], + UnrecognizedInt, +] + + +class CreateChargeRequestTypedDict(TypedDict): + r"""Create a Coinbase charge for crypto payment""" + + amount: float + sender: str + chain_id: ChainID + + +class CreateChargeRequest(BaseModel): + r"""Create a Coinbase charge for crypto payment""" + + amount: float + + sender: str + + chain_id: Annotated[ChainID, PlainValidator(validate_open_enum(True))] diff --git a/src/openrouter/models/createcoinbasechargeop.py b/src/openrouter/models/createcoinbasechargeop.py new file mode 100644 index 0000000..dfb2f59 --- /dev/null +++ b/src/openrouter/models/createcoinbasechargeop.py @@ -0,0 +1,121 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel +from openrouter.utils import FieldMetadata, SecurityMetadata +from typing_extensions import Annotated, TypedDict + + +class CreateCoinbaseChargeSecurityTypedDict(TypedDict): + bearer: str + + +class CreateCoinbaseChargeSecurity(BaseModel): + bearer: Annotated[ + str, + FieldMetadata( + security=SecurityMetadata( + scheme=True, + scheme_type="http", + sub_type="bearer", + field_name="Authorization", + ) + ), + ] + + +class CallDataTypedDict(TypedDict): + deadline: str + fee_amount: str + id: str + operator: str + prefix: str + recipient: str + recipient_amount: str + recipient_currency: str + refund_destination: str + signature: str + + +class CallData(BaseModel): + deadline: str + + fee_amount: str + + id: str + + operator: str + + prefix: str + + recipient: str + + recipient_amount: str + + recipient_currency: str + + refund_destination: str + + signature: str + + +class MetadataTypedDict(TypedDict): + chain_id: float + contract_address: str + sender: str + + +class Metadata(BaseModel): + chain_id: float + + contract_address: str + + sender: str + + +class TransferIntentTypedDict(TypedDict): + call_data: CallDataTypedDict + metadata: MetadataTypedDict + + +class TransferIntent(BaseModel): + call_data: CallData + + metadata: Metadata + + +class Web3DataTypedDict(TypedDict): + transfer_intent: TransferIntentTypedDict + + +class Web3Data(BaseModel): + transfer_intent: TransferIntent + + +class CreateCoinbaseChargeDataTypedDict(TypedDict): + id: str + created_at: str + expires_at: str + web3_data: Web3DataTypedDict + + +class CreateCoinbaseChargeData(BaseModel): + id: str + + created_at: str + + expires_at: str + + web3_data: Web3Data + + +class CreateCoinbaseChargeResponseTypedDict(TypedDict): + r"""Returns the calldata to fulfill the transaction""" + + data: CreateCoinbaseChargeDataTypedDict + + +class CreateCoinbaseChargeResponse(BaseModel): + r"""Returns the calldata to fulfill the transaction""" + + data: CreateCoinbaseChargeData diff --git a/src/openrouter/models/createembeddingsop.py b/src/openrouter/models/createembeddingsop.py new file mode 100644 index 0000000..f90d907 --- /dev/null +++ b/src/openrouter/models/createembeddingsop.py @@ -0,0 +1,366 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .providername import ProviderName +from .quantization import Quantization +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, + UnrecognizedStr, +) +from openrouter.utils import validate_open_enum +from pydantic import model_serializer +from pydantic.functional_validators import PlainValidator +from typing import Any, List, Literal, Optional, Union +from typing_extensions import Annotated, NotRequired, TypeAliasType, TypedDict + + +InputTypedDict = TypeAliasType( + "InputTypedDict", Union[str, List[str], List[float], List[List[float]]] +) + + +Input = TypeAliasType("Input", Union[str, List[str], List[float], List[List[float]]]) + + +CreateEmbeddingsDataCollection = Union[ + Literal[ + "deny", + "allow", + ], + UnrecognizedStr, +] +r"""Data collection setting. If no available model provider meets the requirement, your request will return an error. +- allow: (default) allow providers which store user data non-transiently and may train on it +- deny: use only providers which do not collect user data. + +""" + + +CreateEmbeddingsOrderTypedDict = TypeAliasType( + "CreateEmbeddingsOrderTypedDict", Union[ProviderName, str] +) + + +CreateEmbeddingsOrder = TypeAliasType( + "CreateEmbeddingsOrder", + Union[Annotated[ProviderName, PlainValidator(validate_open_enum(False))], str], +) + + +CreateEmbeddingsOnlyTypedDict = TypeAliasType( + "CreateEmbeddingsOnlyTypedDict", Union[ProviderName, str] +) + + +CreateEmbeddingsOnly = TypeAliasType( + "CreateEmbeddingsOnly", + Union[Annotated[ProviderName, PlainValidator(validate_open_enum(False))], str], +) + + +CreateEmbeddingsIgnoreTypedDict = TypeAliasType( + "CreateEmbeddingsIgnoreTypedDict", Union[ProviderName, str] +) + + +CreateEmbeddingsIgnore = TypeAliasType( + "CreateEmbeddingsIgnore", + Union[Annotated[ProviderName, PlainValidator(validate_open_enum(False))], str], +) + + +CreateEmbeddingsSort = Union[ + Literal[ + "price", + "throughput", + "latency", + ], + UnrecognizedStr, +] +r"""The sorting strategy to use for this request, if \"order\" is not specified. When set, no load balancing is performed.""" + + +class CreateEmbeddingsMaxPriceTypedDict(TypedDict): + r"""The object specifying the maximum price you want to pay for this request. USD price per million tokens, for prompt and completion.""" + + prompt: NotRequired[Any] + r"""A value in string or number format that is a large number""" + completion: NotRequired[Any] + r"""A value in string or number format that is a large number""" + image: NotRequired[Any] + r"""A value in string or number format that is a large number""" + audio: NotRequired[Any] + r"""A value in string or number format that is a large number""" + request: NotRequired[Any] + r"""A value in string or number format that is a large number""" + + +class CreateEmbeddingsMaxPrice(BaseModel): + r"""The object specifying the maximum price you want to pay for this request. USD price per million tokens, for prompt and completion.""" + + prompt: Optional[Any] = None + r"""A value in string or number format that is a large number""" + + completion: Optional[Any] = None + r"""A value in string or number format that is a large number""" + + image: Optional[Any] = None + r"""A value in string or number format that is a large number""" + + audio: Optional[Any] = None + r"""A value in string or number format that is a large number""" + + request: Optional[Any] = None + r"""A value in string or number format that is a large number""" + + +class CreateEmbeddingsProviderTypedDict(TypedDict): + allow_fallbacks: NotRequired[Nullable[bool]] + r"""Whether to allow backup providers to serve requests + - true: (default) when the primary provider (or your custom providers in \"order\") is unavailable, use the next best provider. + - false: use only the primary/custom provider, and return the upstream error if it's unavailable. + + """ + require_parameters: NotRequired[Nullable[bool]] + r"""Whether to filter providers to only those that support the parameters you've provided. If this setting is omitted or set to false, then providers will receive only the parameters they support, and ignore the rest.""" + data_collection: NotRequired[Nullable[CreateEmbeddingsDataCollection]] + r"""Data collection setting. If no available model provider meets the requirement, your request will return an error. + - allow: (default) allow providers which store user data non-transiently and may train on it + - deny: use only providers which do not collect user data. + + """ + zdr: NotRequired[Nullable[bool]] + r"""Whether to restrict routing to only ZDR (Zero Data Retention) endpoints. When true, only endpoints that do not retain prompts will be used.""" + enforce_distillable_text: NotRequired[Nullable[bool]] + r"""Whether to restrict routing to only models that allow text distillation. When true, only models where the author has allowed distillation will be used.""" + order: NotRequired[Nullable[List[CreateEmbeddingsOrderTypedDict]]] + r"""An ordered list of provider slugs. The router will attempt to use the first provider in the subset of this list that supports your requested model, and fall back to the next if it is unavailable. If no providers are available, the request will fail with an error message.""" + only: NotRequired[Nullable[List[CreateEmbeddingsOnlyTypedDict]]] + r"""List of provider slugs to allow. If provided, this list is merged with your account-wide allowed provider settings for this request.""" + ignore: NotRequired[Nullable[List[CreateEmbeddingsIgnoreTypedDict]]] + r"""List of provider slugs to ignore. If provided, this list is merged with your account-wide ignored provider settings for this request.""" + quantizations: NotRequired[Nullable[List[Quantization]]] + r"""A list of quantization levels to filter the provider by.""" + sort: NotRequired[Nullable[CreateEmbeddingsSort]] + r"""The sorting strategy to use for this request, if \"order\" is not specified. When set, no load balancing is performed.""" + max_price: NotRequired[CreateEmbeddingsMaxPriceTypedDict] + r"""The object specifying the maximum price you want to pay for this request. USD price per million tokens, for prompt and completion.""" + + +class CreateEmbeddingsProvider(BaseModel): + allow_fallbacks: OptionalNullable[bool] = UNSET + r"""Whether to allow backup providers to serve requests + - true: (default) when the primary provider (or your custom providers in \"order\") is unavailable, use the next best provider. + - false: use only the primary/custom provider, and return the upstream error if it's unavailable. + + """ + + require_parameters: OptionalNullable[bool] = UNSET + r"""Whether to filter providers to only those that support the parameters you've provided. If this setting is omitted or set to false, then providers will receive only the parameters they support, and ignore the rest.""" + + data_collection: Annotated[ + OptionalNullable[CreateEmbeddingsDataCollection], + PlainValidator(validate_open_enum(False)), + ] = UNSET + r"""Data collection setting. If no available model provider meets the requirement, your request will return an error. + - allow: (default) allow providers which store user data non-transiently and may train on it + - deny: use only providers which do not collect user data. + + """ + + zdr: OptionalNullable[bool] = UNSET + r"""Whether to restrict routing to only ZDR (Zero Data Retention) endpoints. When true, only endpoints that do not retain prompts will be used.""" + + enforce_distillable_text: OptionalNullable[bool] = UNSET + r"""Whether to restrict routing to only models that allow text distillation. When true, only models where the author has allowed distillation will be used.""" + + order: OptionalNullable[List[CreateEmbeddingsOrder]] = UNSET + r"""An ordered list of provider slugs. The router will attempt to use the first provider in the subset of this list that supports your requested model, and fall back to the next if it is unavailable. If no providers are available, the request will fail with an error message.""" + + only: OptionalNullable[List[CreateEmbeddingsOnly]] = UNSET + r"""List of provider slugs to allow. If provided, this list is merged with your account-wide allowed provider settings for this request.""" + + ignore: OptionalNullable[List[CreateEmbeddingsIgnore]] = UNSET + r"""List of provider slugs to ignore. If provided, this list is merged with your account-wide ignored provider settings for this request.""" + + quantizations: OptionalNullable[ + List[Annotated[Quantization, PlainValidator(validate_open_enum(False))]] + ] = UNSET + r"""A list of quantization levels to filter the provider by.""" + + sort: Annotated[ + OptionalNullable[CreateEmbeddingsSort], + PlainValidator(validate_open_enum(False)), + ] = UNSET + r"""The sorting strategy to use for this request, if \"order\" is not specified. When set, no load balancing is performed.""" + + max_price: Optional[CreateEmbeddingsMaxPrice] = None + r"""The object specifying the maximum price you want to pay for this request. USD price per million tokens, for prompt and completion.""" + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = [ + "allow_fallbacks", + "require_parameters", + "data_collection", + "zdr", + "enforce_distillable_text", + "order", + "only", + "ignore", + "quantizations", + "sort", + "max_price", + ] + nullable_fields = [ + "allow_fallbacks", + "require_parameters", + "data_collection", + "zdr", + "enforce_distillable_text", + "order", + "only", + "ignore", + "quantizations", + "sort", + ] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m + + +EncodingFormatBase64 = Literal["base64",] + + +EncodingFormatFloat = Literal["float",] + + +EncodingFormatTypedDict = TypeAliasType( + "EncodingFormatTypedDict", Union[EncodingFormatFloat, EncodingFormatBase64] +) + + +EncodingFormat = TypeAliasType( + "EncodingFormat", Union[EncodingFormatFloat, EncodingFormatBase64] +) + + +class CreateEmbeddingsRequestTypedDict(TypedDict): + input: InputTypedDict + model: str + provider: NotRequired[CreateEmbeddingsProviderTypedDict] + encoding_format: NotRequired[EncodingFormatTypedDict] + user: NotRequired[str] + + +class CreateEmbeddingsRequest(BaseModel): + input: Input + + model: str + + provider: Optional[CreateEmbeddingsProvider] = None + + encoding_format: Optional[EncodingFormat] = None + + user: Optional[str] = None + + +CreateEmbeddingsObject = Literal["list",] + + +ObjectEmbedding = Literal["embedding",] + + +EmbeddingTypedDict = TypeAliasType("EmbeddingTypedDict", Union[List[float], str]) + + +Embedding = TypeAliasType("Embedding", Union[List[float], str]) + + +class CreateEmbeddingsDataTypedDict(TypedDict): + object: ObjectEmbedding + embedding: EmbeddingTypedDict + index: NotRequired[float] + + +class CreateEmbeddingsData(BaseModel): + object: ObjectEmbedding + + embedding: Embedding + + index: Optional[float] = None + + +class UsageTypedDict(TypedDict): + prompt_tokens: float + total_tokens: float + cost: NotRequired[float] + + +class Usage(BaseModel): + prompt_tokens: float + + total_tokens: float + + cost: Optional[float] = None + + +class CreateEmbeddingsResponseBodyTypedDict(TypedDict): + r"""Embedding response""" + + object: CreateEmbeddingsObject + data: List[CreateEmbeddingsDataTypedDict] + model: str + id: NotRequired[str] + usage: NotRequired[UsageTypedDict] + + +class CreateEmbeddingsResponseBody(BaseModel): + r"""Embedding response""" + + object: CreateEmbeddingsObject + + data: List[CreateEmbeddingsData] + + model: str + + id: Optional[str] = None + + usage: Optional[Usage] = None + + +CreateEmbeddingsResponseTypedDict = TypeAliasType( + "CreateEmbeddingsResponseTypedDict", + Union[CreateEmbeddingsResponseBodyTypedDict, str], +) + + +CreateEmbeddingsResponse = TypeAliasType( + "CreateEmbeddingsResponse", Union[CreateEmbeddingsResponseBody, str] +) diff --git a/src/openrouter/models/createkeysop.py b/src/openrouter/models/createkeysop.py new file mode 100644 index 0000000..6a4dca6 --- /dev/null +++ b/src/openrouter/models/createkeysop.py @@ -0,0 +1,255 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from datetime import datetime +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, + UnrecognizedStr, +) +from openrouter.utils import validate_open_enum +from pydantic import model_serializer +from pydantic.functional_validators import PlainValidator +from typing import Literal, Optional, Union +from typing_extensions import Annotated, NotRequired, TypedDict + + +CreateKeysLimitReset = Union[ + Literal[ + "daily", + "weekly", + "monthly", + ], + UnrecognizedStr, +] +r"""Type of limit reset for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday.""" + + +class CreateKeysRequestTypedDict(TypedDict): + name: str + r"""Name for the new API key""" + limit: NotRequired[Nullable[float]] + r"""Optional spending limit for the API key in USD""" + limit_reset: NotRequired[Nullable[CreateKeysLimitReset]] + r"""Type of limit reset for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday.""" + include_byok_in_limit: NotRequired[bool] + r"""Whether to include BYOK usage in the limit""" + expires_at: NotRequired[Nullable[datetime]] + r"""Optional ISO 8601 UTC timestamp when the API key should expire. Must be UTC, other timezones will be rejected""" + + +class CreateKeysRequest(BaseModel): + name: str + r"""Name for the new API key""" + + limit: OptionalNullable[float] = UNSET + r"""Optional spending limit for the API key in USD""" + + limit_reset: Annotated[ + OptionalNullable[CreateKeysLimitReset], + PlainValidator(validate_open_enum(False)), + ] = UNSET + r"""Type of limit reset for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday.""" + + include_byok_in_limit: Optional[bool] = None + r"""Whether to include BYOK usage in the limit""" + + expires_at: OptionalNullable[datetime] = UNSET + r"""Optional ISO 8601 UTC timestamp when the API key should expire. Must be UTC, other timezones will be rejected""" + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = [ + "limit", + "limit_reset", + "include_byok_in_limit", + "expires_at", + ] + nullable_fields = ["limit", "limit_reset", "expires_at"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m + + +class CreateKeysDataTypedDict(TypedDict): + r"""The created API key information""" + + hash: str + r"""Unique hash identifier for the API key""" + name: str + r"""Name of the API key""" + label: str + r"""Human-readable label for the API key""" + disabled: bool + r"""Whether the API key is disabled""" + limit: Nullable[float] + r"""Spending limit for the API key in USD""" + limit_remaining: Nullable[float] + r"""Remaining spending limit in USD""" + limit_reset: Nullable[str] + r"""Type of limit reset for the API key""" + include_byok_in_limit: bool + r"""Whether to include external BYOK usage in the credit limit""" + usage: float + r"""Total OpenRouter credit usage (in USD) for the API key""" + usage_daily: float + r"""OpenRouter credit usage (in USD) for the current UTC day""" + usage_weekly: float + r"""OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday)""" + usage_monthly: float + r"""OpenRouter credit usage (in USD) for the current UTC month""" + byok_usage: float + r"""Total external BYOK usage (in USD) for the API key""" + byok_usage_daily: float + r"""External BYOK usage (in USD) for the current UTC day""" + byok_usage_weekly: float + r"""External BYOK usage (in USD) for the current UTC week (Monday-Sunday)""" + byok_usage_monthly: float + r"""External BYOK usage (in USD) for current UTC month""" + created_at: str + r"""ISO 8601 timestamp of when the API key was created""" + updated_at: Nullable[str] + r"""ISO 8601 timestamp of when the API key was last updated""" + expires_at: NotRequired[Nullable[datetime]] + r"""ISO 8601 UTC timestamp when the API key expires, or null if no expiration""" + + +class CreateKeysData(BaseModel): + r"""The created API key information""" + + hash: str + r"""Unique hash identifier for the API key""" + + name: str + r"""Name of the API key""" + + label: str + r"""Human-readable label for the API key""" + + disabled: bool + r"""Whether the API key is disabled""" + + limit: Nullable[float] + r"""Spending limit for the API key in USD""" + + limit_remaining: Nullable[float] + r"""Remaining spending limit in USD""" + + limit_reset: Nullable[str] + r"""Type of limit reset for the API key""" + + include_byok_in_limit: bool + r"""Whether to include external BYOK usage in the credit limit""" + + usage: float + r"""Total OpenRouter credit usage (in USD) for the API key""" + + usage_daily: float + r"""OpenRouter credit usage (in USD) for the current UTC day""" + + usage_weekly: float + r"""OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday)""" + + usage_monthly: float + r"""OpenRouter credit usage (in USD) for the current UTC month""" + + byok_usage: float + r"""Total external BYOK usage (in USD) for the API key""" + + byok_usage_daily: float + r"""External BYOK usage (in USD) for the current UTC day""" + + byok_usage_weekly: float + r"""External BYOK usage (in USD) for the current UTC week (Monday-Sunday)""" + + byok_usage_monthly: float + r"""External BYOK usage (in USD) for current UTC month""" + + created_at: str + r"""ISO 8601 timestamp of when the API key was created""" + + updated_at: Nullable[str] + r"""ISO 8601 timestamp of when the API key was last updated""" + + expires_at: OptionalNullable[datetime] = UNSET + r"""ISO 8601 UTC timestamp when the API key expires, or null if no expiration""" + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["expires_at"] + nullable_fields = [ + "limit", + "limit_remaining", + "limit_reset", + "updated_at", + "expires_at", + ] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m + + +class CreateKeysResponseTypedDict(TypedDict): + r"""API key created successfully""" + + data: CreateKeysDataTypedDict + r"""The created API key information""" + key: str + r"""The actual API key string (only shown once)""" + + +class CreateKeysResponse(BaseModel): + r"""API key created successfully""" + + data: CreateKeysData + r"""The created API key information""" + + key: str + r"""The actual API key string (only shown once)""" diff --git a/src/openrouter/models/createresponsesop.py b/src/openrouter/models/createresponsesop.py new file mode 100644 index 0000000..7b5c85f --- /dev/null +++ b/src/openrouter/models/createresponsesop.py @@ -0,0 +1,53 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .openresponsesnonstreamingresponse import ( + OpenResponsesNonStreamingResponse, + OpenResponsesNonStreamingResponseTypedDict, +) +from .openresponsesstreamevent import ( + OpenResponsesStreamEvent, + OpenResponsesStreamEventTypedDict, +) +from openrouter.types import BaseModel +from openrouter.utils import eventstreaming +from typing import Union +from typing_extensions import TypeAliasType, TypedDict + + +class CreateResponsesResponseBodyTypedDict(TypedDict): + r"""Successful response""" + + data: OpenResponsesStreamEventTypedDict + r"""Union of all possible event types emitted during response streaming""" + + +class CreateResponsesResponseBody(BaseModel): + r"""Successful response""" + + data: OpenResponsesStreamEvent + r"""Union of all possible event types emitted during response streaming""" + + +CreateResponsesResponseTypedDict = TypeAliasType( + "CreateResponsesResponseTypedDict", + Union[ + OpenResponsesNonStreamingResponseTypedDict, + Union[ + eventstreaming.EventStream[CreateResponsesResponseBodyTypedDict], + eventstreaming.EventStreamAsync[CreateResponsesResponseBodyTypedDict], + ], + ], +) + + +CreateResponsesResponse = TypeAliasType( + "CreateResponsesResponse", + Union[ + OpenResponsesNonStreamingResponse, + Union[ + eventstreaming.EventStream[CreateResponsesResponseBody], + eventstreaming.EventStreamAsync[CreateResponsesResponseBody], + ], + ], +) diff --git a/src/openrouter/models/defaultparameters.py b/src/openrouter/models/defaultparameters.py new file mode 100644 index 0000000..b28498a --- /dev/null +++ b/src/openrouter/models/defaultparameters.py @@ -0,0 +1,60 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from pydantic import model_serializer +from typing_extensions import NotRequired, TypedDict + + +class DefaultParametersTypedDict(TypedDict): + r"""Default parameters for this model""" + + temperature: NotRequired[Nullable[float]] + top_p: NotRequired[Nullable[float]] + frequency_penalty: NotRequired[Nullable[float]] + + +class DefaultParameters(BaseModel): + r"""Default parameters for this model""" + + temperature: OptionalNullable[float] = UNSET + + top_p: OptionalNullable[float] = UNSET + + frequency_penalty: OptionalNullable[float] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["temperature", "top_p", "frequency_penalty"] + nullable_fields = ["temperature", "top_p", "frequency_penalty"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/deletekeysop.py b/src/openrouter/models/deletekeysop.py new file mode 100644 index 0000000..97ec94d --- /dev/null +++ b/src/openrouter/models/deletekeysop.py @@ -0,0 +1,38 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel +from openrouter.utils import FieldMetadata, PathParamMetadata, validate_const +import pydantic +from pydantic.functional_validators import AfterValidator +from typing import Literal +from typing_extensions import Annotated, TypedDict + + +class DeleteKeysRequestTypedDict(TypedDict): + hash: str + r"""The hash identifier of the API key to delete""" + + +class DeleteKeysRequest(BaseModel): + hash: Annotated[ + str, FieldMetadata(path=PathParamMetadata(style="simple", explode=False)) + ] + r"""The hash identifier of the API key to delete""" + + +class DeleteKeysResponseTypedDict(TypedDict): + r"""API key deleted successfully""" + + deleted: Literal[True] + r"""Confirmation that the API key was deleted""" + + +class DeleteKeysResponse(BaseModel): + r"""API key deleted successfully""" + + DELETED: Annotated[ + Annotated[Literal[True], AfterValidator(validate_const(True))], + pydantic.Field(alias="deleted"), + ] = True + r"""Confirmation that the API key was deleted""" diff --git a/src/openrouter/models/edgenetworktimeoutresponseerrordata.py b/src/openrouter/models/edgenetworktimeoutresponseerrordata.py new file mode 100644 index 0000000..b44fcaf --- /dev/null +++ b/src/openrouter/models/edgenetworktimeoutresponseerrordata.py @@ -0,0 +1,61 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from pydantic import model_serializer +from typing import Any, Dict +from typing_extensions import NotRequired, TypedDict + + +class EdgeNetworkTimeoutResponseErrorDataTypedDict(TypedDict): + r"""Error data for EdgeNetworkTimeoutResponse""" + + code: int + message: str + metadata: NotRequired[Nullable[Dict[str, Nullable[Any]]]] + + +class EdgeNetworkTimeoutResponseErrorData(BaseModel): + r"""Error data for EdgeNetworkTimeoutResponse""" + + code: int + + message: str + + metadata: OptionalNullable[Dict[str, Nullable[Any]]] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["metadata"] + nullable_fields = ["metadata"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/endpointstatus.py b/src/openrouter/models/endpointstatus.py new file mode 100644 index 0000000..ed5f8af --- /dev/null +++ b/src/openrouter/models/endpointstatus.py @@ -0,0 +1,18 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import UnrecognizedInt +from typing import Literal, Union + + +EndpointStatus = Union[ + Literal[ + 0, + -1, + -2, + -3, + -5, + -10, + ], + UnrecognizedInt, +] diff --git a/src/openrouter/models/exchangeauthcodeforapikeyop.py b/src/openrouter/models/exchangeauthcodeforapikeyop.py new file mode 100644 index 0000000..1f475e5 --- /dev/null +++ b/src/openrouter/models/exchangeauthcodeforapikeyop.py @@ -0,0 +1,130 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, + UnrecognizedStr, +) +from openrouter.utils import validate_open_enum +from pydantic import model_serializer +from pydantic.functional_validators import PlainValidator +from typing import Literal, Optional, Union +from typing_extensions import Annotated, NotRequired, TypedDict + + +ExchangeAuthCodeForAPIKeyCodeChallengeMethod = Union[ + Literal[ + "S256", + "plain", + ], + UnrecognizedStr, +] +r"""The method used to generate the code challenge""" + + +class ExchangeAuthCodeForAPIKeyRequestTypedDict(TypedDict): + code: str + r"""The authorization code received from the OAuth redirect""" + code_verifier: NotRequired[str] + r"""The code verifier if code_challenge was used in the authorization request""" + code_challenge_method: NotRequired[ + Nullable[ExchangeAuthCodeForAPIKeyCodeChallengeMethod] + ] + r"""The method used to generate the code challenge""" + + +class ExchangeAuthCodeForAPIKeyRequest(BaseModel): + code: str + r"""The authorization code received from the OAuth redirect""" + + code_verifier: Optional[str] = None + r"""The code verifier if code_challenge was used in the authorization request""" + + code_challenge_method: Annotated[ + OptionalNullable[ExchangeAuthCodeForAPIKeyCodeChallengeMethod], + PlainValidator(validate_open_enum(False)), + ] = UNSET + r"""The method used to generate the code challenge""" + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["code_verifier", "code_challenge_method"] + nullable_fields = ["code_challenge_method"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m + + +class ExchangeAuthCodeForAPIKeyResponseTypedDict(TypedDict): + r"""Successfully exchanged code for an API key""" + + key: str + r"""The API key to use for OpenRouter requests""" + user_id: Nullable[str] + r"""User ID associated with the API key""" + + +class ExchangeAuthCodeForAPIKeyResponse(BaseModel): + r"""Successfully exchanged code for an API key""" + + key: str + r"""The API key to use for OpenRouter requests""" + + user_id: Nullable[str] + r"""User ID associated with the API key""" + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = [] + nullable_fields = ["user_id"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/filecitation.py b/src/openrouter/models/filecitation.py new file mode 100644 index 0000000..265b6eb --- /dev/null +++ b/src/openrouter/models/filecitation.py @@ -0,0 +1,26 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel +from typing import Literal +from typing_extensions import TypedDict + + +FileCitationType = Literal["file_citation",] + + +class FileCitationTypedDict(TypedDict): + type: FileCitationType + file_id: str + filename: str + index: float + + +class FileCitation(BaseModel): + type: FileCitationType + + file_id: str + + filename: str + + index: float diff --git a/src/openrouter/models/filepath.py b/src/openrouter/models/filepath.py new file mode 100644 index 0000000..3afbce3 --- /dev/null +++ b/src/openrouter/models/filepath.py @@ -0,0 +1,23 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel +from typing import Literal +from typing_extensions import TypedDict + + +FilePathType = Literal["file_path",] + + +class FilePathTypedDict(TypedDict): + type: FilePathType + file_id: str + index: float + + +class FilePath(BaseModel): + type: FilePathType + + file_id: str + + index: float diff --git a/src/openrouter/models/forbiddenresponseerrordata.py b/src/openrouter/models/forbiddenresponseerrordata.py new file mode 100644 index 0000000..a758f01 --- /dev/null +++ b/src/openrouter/models/forbiddenresponseerrordata.py @@ -0,0 +1,61 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from pydantic import model_serializer +from typing import Any, Dict +from typing_extensions import NotRequired, TypedDict + + +class ForbiddenResponseErrorDataTypedDict(TypedDict): + r"""Error data for ForbiddenResponse""" + + code: int + message: str + metadata: NotRequired[Nullable[Dict[str, Nullable[Any]]]] + + +class ForbiddenResponseErrorData(BaseModel): + r"""Error data for ForbiddenResponse""" + + code: int + + message: str + + metadata: OptionalNullable[Dict[str, Nullable[Any]]] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["metadata"] + nullable_fields = ["metadata"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/getcreditsop.py b/src/openrouter/models/getcreditsop.py new file mode 100644 index 0000000..9719016 --- /dev/null +++ b/src/openrouter/models/getcreditsop.py @@ -0,0 +1,13 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel +from typing_extensions import TypedDict + + +class GetCreditsResponseTypedDict(TypedDict): + r"""Total credits purchased and used""" + + +class GetCreditsResponse(BaseModel): + r"""Total credits purchased and used""" diff --git a/src/openrouter/models/getcurrentkeyop.py b/src/openrouter/models/getcurrentkeyop.py new file mode 100644 index 0000000..9bd9931 --- /dev/null +++ b/src/openrouter/models/getcurrentkeyop.py @@ -0,0 +1,187 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from datetime import datetime +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +import pydantic +from pydantic import model_serializer +from typing_extensions import Annotated, NotRequired, TypedDict, deprecated + + +@deprecated( + "warning: ** DEPRECATED ** - This will be removed in a future release, please migrate away from it as soon as possible." +) +class RateLimitTypedDict(TypedDict): + r"""Legacy rate limit information about a key. Will always return -1.""" + + requests: float + r"""Number of requests allowed per interval""" + interval: str + r"""Rate limit interval""" + note: str + r"""Note about the rate limit""" + + +@deprecated( + "warning: ** DEPRECATED ** - This will be removed in a future release, please migrate away from it as soon as possible." +) +class RateLimit(BaseModel): + r"""Legacy rate limit information about a key. Will always return -1.""" + + requests: float + r"""Number of requests allowed per interval""" + + interval: str + r"""Rate limit interval""" + + note: str + r"""Note about the rate limit""" + + +class GetCurrentKeyDataTypedDict(TypedDict): + r"""Current API key information""" + + label: str + r"""Human-readable label for the API key""" + limit: Nullable[float] + r"""Spending limit for the API key in USD""" + usage: float + r"""Total OpenRouter credit usage (in USD) for the API key""" + usage_daily: float + r"""OpenRouter credit usage (in USD) for the current UTC day""" + usage_weekly: float + r"""OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday)""" + usage_monthly: float + r"""OpenRouter credit usage (in USD) for the current UTC month""" + byok_usage: float + r"""Total external BYOK usage (in USD) for the API key""" + byok_usage_daily: float + r"""External BYOK usage (in USD) for the current UTC day""" + byok_usage_weekly: float + r"""External BYOK usage (in USD) for the current UTC week (Monday-Sunday)""" + byok_usage_monthly: float + r"""External BYOK usage (in USD) for current UTC month""" + is_free_tier: bool + r"""Whether this is a free tier API key""" + is_provisioning_key: bool + r"""Whether this is a provisioning key""" + limit_remaining: Nullable[float] + r"""Remaining spending limit in USD""" + limit_reset: Nullable[str] + r"""Type of limit reset for the API key""" + include_byok_in_limit: bool + r"""Whether to include external BYOK usage in the credit limit""" + rate_limit: RateLimitTypedDict + r"""Legacy rate limit information about a key. Will always return -1.""" + expires_at: NotRequired[Nullable[datetime]] + r"""ISO 8601 UTC timestamp when the API key expires, or null if no expiration""" + + +class GetCurrentKeyData(BaseModel): + r"""Current API key information""" + + label: str + r"""Human-readable label for the API key""" + + limit: Nullable[float] + r"""Spending limit for the API key in USD""" + + usage: float + r"""Total OpenRouter credit usage (in USD) for the API key""" + + usage_daily: float + r"""OpenRouter credit usage (in USD) for the current UTC day""" + + usage_weekly: float + r"""OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday)""" + + usage_monthly: float + r"""OpenRouter credit usage (in USD) for the current UTC month""" + + byok_usage: float + r"""Total external BYOK usage (in USD) for the API key""" + + byok_usage_daily: float + r"""External BYOK usage (in USD) for the current UTC day""" + + byok_usage_weekly: float + r"""External BYOK usage (in USD) for the current UTC week (Monday-Sunday)""" + + byok_usage_monthly: float + r"""External BYOK usage (in USD) for current UTC month""" + + is_free_tier: bool + r"""Whether this is a free tier API key""" + + is_provisioning_key: bool + r"""Whether this is a provisioning key""" + + limit_remaining: Nullable[float] + r"""Remaining spending limit in USD""" + + limit_reset: Nullable[str] + r"""Type of limit reset for the API key""" + + include_byok_in_limit: bool + r"""Whether to include external BYOK usage in the credit limit""" + + rate_limit: Annotated[ + RateLimit, + pydantic.Field( + deprecated="warning: ** DEPRECATED ** - This will be removed in a future release, please migrate away from it as soon as possible." + ), + ] + r"""Legacy rate limit information about a key. Will always return -1.""" + + expires_at: OptionalNullable[datetime] = UNSET + r"""ISO 8601 UTC timestamp when the API key expires, or null if no expiration""" + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["expires_at"] + nullable_fields = ["limit", "limit_remaining", "limit_reset", "expires_at"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m + + +class GetCurrentKeyResponseTypedDict(TypedDict): + r"""API key details""" + + data: GetCurrentKeyDataTypedDict + r"""Current API key information""" + + +class GetCurrentKeyResponse(BaseModel): + r"""API key details""" + + data: GetCurrentKeyData + r"""Current API key information""" diff --git a/src/openrouter/models/getgenerationop.py b/src/openrouter/models/getgenerationop.py new file mode 100644 index 0000000..7a9d815 --- /dev/null +++ b/src/openrouter/models/getgenerationop.py @@ -0,0 +1,268 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel, Nullable, UNSET_SENTINEL, UnrecognizedStr +from openrouter.utils import FieldMetadata, QueryParamMetadata, validate_open_enum +from pydantic import model_serializer +from pydantic.functional_validators import PlainValidator +from typing import Literal, Union +from typing_extensions import Annotated, TypedDict + + +class GetGenerationRequestTypedDict(TypedDict): + id: str + + +class GetGenerationRequest(BaseModel): + id: Annotated[ + str, FieldMetadata(query=QueryParamMetadata(style="form", explode=True)) + ] + + +APIType = Union[ + Literal[ + "completions", + "embeddings", + ], + UnrecognizedStr, +] +r"""Type of API used for the generation""" + + +class GetGenerationDataTypedDict(TypedDict): + r"""Generation data""" + + id: str + r"""Unique identifier for the generation""" + upstream_id: Nullable[str] + r"""Upstream provider's identifier for this generation""" + total_cost: float + r"""Total cost of the generation in USD""" + cache_discount: Nullable[float] + r"""Discount applied due to caching""" + upstream_inference_cost: Nullable[float] + r"""Cost charged by the upstream provider""" + created_at: str + r"""ISO 8601 timestamp of when the generation was created""" + model: str + r"""Model used for the generation""" + app_id: Nullable[float] + r"""ID of the app that made the request""" + streamed: Nullable[bool] + r"""Whether the response was streamed""" + cancelled: Nullable[bool] + r"""Whether the generation was cancelled""" + provider_name: Nullable[str] + r"""Name of the provider that served the request""" + latency: Nullable[float] + r"""Total latency in milliseconds""" + moderation_latency: Nullable[float] + r"""Moderation latency in milliseconds""" + generation_time: Nullable[float] + r"""Time taken for generation in milliseconds""" + finish_reason: Nullable[str] + r"""Reason the generation finished""" + tokens_prompt: Nullable[float] + r"""Number of tokens in the prompt""" + tokens_completion: Nullable[float] + r"""Number of tokens in the completion""" + native_tokens_prompt: Nullable[float] + r"""Native prompt tokens as reported by provider""" + native_tokens_completion: Nullable[float] + r"""Native completion tokens as reported by provider""" + native_tokens_completion_images: Nullable[float] + r"""Native completion image tokens as reported by provider""" + native_tokens_reasoning: Nullable[float] + r"""Native reasoning tokens as reported by provider""" + native_tokens_cached: Nullable[float] + r"""Native cached tokens as reported by provider""" + num_media_prompt: Nullable[float] + r"""Number of media items in the prompt""" + num_input_audio_prompt: Nullable[float] + r"""Number of audio inputs in the prompt""" + num_media_completion: Nullable[float] + r"""Number of media items in the completion""" + num_search_results: Nullable[float] + r"""Number of search results included""" + origin: str + r"""Origin URL of the request""" + usage: float + r"""Usage amount in USD""" + is_byok: bool + r"""Whether this used bring-your-own-key""" + native_finish_reason: Nullable[str] + r"""Native finish reason as reported by provider""" + external_user: Nullable[str] + r"""External user identifier""" + api_type: Nullable[APIType] + r"""Type of API used for the generation""" + + +class GetGenerationData(BaseModel): + r"""Generation data""" + + id: str + r"""Unique identifier for the generation""" + + upstream_id: Nullable[str] + r"""Upstream provider's identifier for this generation""" + + total_cost: float + r"""Total cost of the generation in USD""" + + cache_discount: Nullable[float] + r"""Discount applied due to caching""" + + upstream_inference_cost: Nullable[float] + r"""Cost charged by the upstream provider""" + + created_at: str + r"""ISO 8601 timestamp of when the generation was created""" + + model: str + r"""Model used for the generation""" + + app_id: Nullable[float] + r"""ID of the app that made the request""" + + streamed: Nullable[bool] + r"""Whether the response was streamed""" + + cancelled: Nullable[bool] + r"""Whether the generation was cancelled""" + + provider_name: Nullable[str] + r"""Name of the provider that served the request""" + + latency: Nullable[float] + r"""Total latency in milliseconds""" + + moderation_latency: Nullable[float] + r"""Moderation latency in milliseconds""" + + generation_time: Nullable[float] + r"""Time taken for generation in milliseconds""" + + finish_reason: Nullable[str] + r"""Reason the generation finished""" + + tokens_prompt: Nullable[float] + r"""Number of tokens in the prompt""" + + tokens_completion: Nullable[float] + r"""Number of tokens in the completion""" + + native_tokens_prompt: Nullable[float] + r"""Native prompt tokens as reported by provider""" + + native_tokens_completion: Nullable[float] + r"""Native completion tokens as reported by provider""" + + native_tokens_completion_images: Nullable[float] + r"""Native completion image tokens as reported by provider""" + + native_tokens_reasoning: Nullable[float] + r"""Native reasoning tokens as reported by provider""" + + native_tokens_cached: Nullable[float] + r"""Native cached tokens as reported by provider""" + + num_media_prompt: Nullable[float] + r"""Number of media items in the prompt""" + + num_input_audio_prompt: Nullable[float] + r"""Number of audio inputs in the prompt""" + + num_media_completion: Nullable[float] + r"""Number of media items in the completion""" + + num_search_results: Nullable[float] + r"""Number of search results included""" + + origin: str + r"""Origin URL of the request""" + + usage: float + r"""Usage amount in USD""" + + is_byok: bool + r"""Whether this used bring-your-own-key""" + + native_finish_reason: Nullable[str] + r"""Native finish reason as reported by provider""" + + external_user: Nullable[str] + r"""External user identifier""" + + api_type: Annotated[Nullable[APIType], PlainValidator(validate_open_enum(False))] + r"""Type of API used for the generation""" + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = [] + nullable_fields = [ + "upstream_id", + "cache_discount", + "upstream_inference_cost", + "app_id", + "streamed", + "cancelled", + "provider_name", + "latency", + "moderation_latency", + "generation_time", + "finish_reason", + "tokens_prompt", + "tokens_completion", + "native_tokens_prompt", + "native_tokens_completion", + "native_tokens_completion_images", + "native_tokens_reasoning", + "native_tokens_cached", + "num_media_prompt", + "num_input_audio_prompt", + "num_media_completion", + "num_search_results", + "native_finish_reason", + "external_user", + "api_type", + ] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m + + +class GetGenerationResponseTypedDict(TypedDict): + r"""Generation response""" + + data: GetGenerationDataTypedDict + r"""Generation data""" + + +class GetGenerationResponse(BaseModel): + r"""Generation response""" + + data: GetGenerationData + r"""Generation data""" diff --git a/src/openrouter/models/getkeyop.py b/src/openrouter/models/getkeyop.py new file mode 100644 index 0000000..fe774e3 --- /dev/null +++ b/src/openrouter/models/getkeyop.py @@ -0,0 +1,180 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from datetime import datetime +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from openrouter.utils import FieldMetadata, PathParamMetadata +from pydantic import model_serializer +from typing_extensions import Annotated, NotRequired, TypedDict + + +class GetKeyRequestTypedDict(TypedDict): + hash: str + r"""The hash identifier of the API key to retrieve""" + + +class GetKeyRequest(BaseModel): + hash: Annotated[ + str, FieldMetadata(path=PathParamMetadata(style="simple", explode=False)) + ] + r"""The hash identifier of the API key to retrieve""" + + +class GetKeyDataTypedDict(TypedDict): + r"""The API key information""" + + hash: str + r"""Unique hash identifier for the API key""" + name: str + r"""Name of the API key""" + label: str + r"""Human-readable label for the API key""" + disabled: bool + r"""Whether the API key is disabled""" + limit: Nullable[float] + r"""Spending limit for the API key in USD""" + limit_remaining: Nullable[float] + r"""Remaining spending limit in USD""" + limit_reset: Nullable[str] + r"""Type of limit reset for the API key""" + include_byok_in_limit: bool + r"""Whether to include external BYOK usage in the credit limit""" + usage: float + r"""Total OpenRouter credit usage (in USD) for the API key""" + usage_daily: float + r"""OpenRouter credit usage (in USD) for the current UTC day""" + usage_weekly: float + r"""OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday)""" + usage_monthly: float + r"""OpenRouter credit usage (in USD) for the current UTC month""" + byok_usage: float + r"""Total external BYOK usage (in USD) for the API key""" + byok_usage_daily: float + r"""External BYOK usage (in USD) for the current UTC day""" + byok_usage_weekly: float + r"""External BYOK usage (in USD) for the current UTC week (Monday-Sunday)""" + byok_usage_monthly: float + r"""External BYOK usage (in USD) for current UTC month""" + created_at: str + r"""ISO 8601 timestamp of when the API key was created""" + updated_at: Nullable[str] + r"""ISO 8601 timestamp of when the API key was last updated""" + expires_at: NotRequired[Nullable[datetime]] + r"""ISO 8601 UTC timestamp when the API key expires, or null if no expiration""" + + +class GetKeyData(BaseModel): + r"""The API key information""" + + hash: str + r"""Unique hash identifier for the API key""" + + name: str + r"""Name of the API key""" + + label: str + r"""Human-readable label for the API key""" + + disabled: bool + r"""Whether the API key is disabled""" + + limit: Nullable[float] + r"""Spending limit for the API key in USD""" + + limit_remaining: Nullable[float] + r"""Remaining spending limit in USD""" + + limit_reset: Nullable[str] + r"""Type of limit reset for the API key""" + + include_byok_in_limit: bool + r"""Whether to include external BYOK usage in the credit limit""" + + usage: float + r"""Total OpenRouter credit usage (in USD) for the API key""" + + usage_daily: float + r"""OpenRouter credit usage (in USD) for the current UTC day""" + + usage_weekly: float + r"""OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday)""" + + usage_monthly: float + r"""OpenRouter credit usage (in USD) for the current UTC month""" + + byok_usage: float + r"""Total external BYOK usage (in USD) for the API key""" + + byok_usage_daily: float + r"""External BYOK usage (in USD) for the current UTC day""" + + byok_usage_weekly: float + r"""External BYOK usage (in USD) for the current UTC week (Monday-Sunday)""" + + byok_usage_monthly: float + r"""External BYOK usage (in USD) for current UTC month""" + + created_at: str + r"""ISO 8601 timestamp of when the API key was created""" + + updated_at: Nullable[str] + r"""ISO 8601 timestamp of when the API key was last updated""" + + expires_at: OptionalNullable[datetime] = UNSET + r"""ISO 8601 UTC timestamp when the API key expires, or null if no expiration""" + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["expires_at"] + nullable_fields = [ + "limit", + "limit_remaining", + "limit_reset", + "updated_at", + "expires_at", + ] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m + + +class GetKeyResponseTypedDict(TypedDict): + r"""API key details""" + + data: GetKeyDataTypedDict + r"""The API key information""" + + +class GetKeyResponse(BaseModel): + r"""API key details""" + + data: GetKeyData + r"""The API key information""" diff --git a/src/openrouter/models/getmodelsop.py b/src/openrouter/models/getmodelsop.py new file mode 100644 index 0000000..526ed1b --- /dev/null +++ b/src/openrouter/models/getmodelsop.py @@ -0,0 +1,24 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel +from openrouter.utils import FieldMetadata, QueryParamMetadata +from typing import Optional +from typing_extensions import Annotated, NotRequired, TypedDict + + +class GetModelsRequestTypedDict(TypedDict): + category: NotRequired[str] + supported_parameters: NotRequired[str] + + +class GetModelsRequest(BaseModel): + category: Annotated[ + Optional[str], + FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), + ] = None + + supported_parameters: Annotated[ + Optional[str], + FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), + ] = None diff --git a/src/openrouter/models/getparametersop.py b/src/openrouter/models/getparametersop.py new file mode 100644 index 0000000..1a94a21 --- /dev/null +++ b/src/openrouter/models/getparametersop.py @@ -0,0 +1,195 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel, UnrecognizedStr +from openrouter.utils import ( + FieldMetadata, + PathParamMetadata, + QueryParamMetadata, + SecurityMetadata, + validate_open_enum, +) +from pydantic.functional_validators import PlainValidator +from typing import List, Literal, Optional, Union +from typing_extensions import Annotated, NotRequired, TypedDict + + +class GetParametersSecurityTypedDict(TypedDict): + bearer: str + + +class GetParametersSecurity(BaseModel): + bearer: Annotated[ + str, + FieldMetadata( + security=SecurityMetadata( + scheme=True, + scheme_type="http", + sub_type="bearer", + field_name="Authorization", + ) + ), + ] + + +GetParametersProvider = Union[ + Literal[ + "AI21", + "AionLabs", + "Alibaba", + "Amazon Bedrock", + "Anthropic", + "AtlasCloud", + "Atoma", + "Avian", + "Azure", + "BaseTen", + "Cerebras", + "Chutes", + "Cirrascale", + "Clarifai", + "Cloudflare", + "Cohere", + "CrofAI", + "Crusoe", + "DeepInfra", + "DeepSeek", + "Enfer", + "Featherless", + "Fireworks", + "Friendli", + "GMICloud", + "Google", + "Google AI Studio", + "Groq", + "Hyperbolic", + "Inception", + "InferenceNet", + "Infermatic", + "Inflection", + "Kluster", + "Lambda", + "Liquid", + "Mancer 2", + "Meta", + "Minimax", + "ModelRun", + "Mistral", + "Modular", + "Moonshot AI", + "Morph", + "NCompass", + "Nebius", + "NextBit", + "Nineteen", + "Novita", + "Nvidia", + "OpenAI", + "OpenInference", + "Parasail", + "Perplexity", + "Phala", + "Relace", + "SambaNova", + "SiliconFlow", + "Stealth", + "Switchpoint", + "Targon", + "Together", + "Ubicloud", + "Venice", + "WandB", + "xAI", + "Z.AI", + "FakeProvider", + ], + UnrecognizedStr, +] + + +class GetParametersRequestTypedDict(TypedDict): + author: str + slug: str + provider: NotRequired[GetParametersProvider] + + +class GetParametersRequest(BaseModel): + author: Annotated[ + str, FieldMetadata(path=PathParamMetadata(style="simple", explode=False)) + ] + + slug: Annotated[ + str, FieldMetadata(path=PathParamMetadata(style="simple", explode=False)) + ] + + provider: Annotated[ + Annotated[ + Optional[GetParametersProvider], PlainValidator(validate_open_enum(False)) + ], + FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), + ] = None + + +SupportedParameter = Union[ + Literal[ + "temperature", + "top_p", + "top_k", + "min_p", + "top_a", + "frequency_penalty", + "presence_penalty", + "repetition_penalty", + "max_tokens", + "logit_bias", + "logprobs", + "top_logprobs", + "seed", + "response_format", + "structured_outputs", + "stop", + "tools", + "tool_choice", + "parallel_tool_calls", + "include_reasoning", + "reasoning", + "web_search_options", + "verbosity", + ], + UnrecognizedStr, +] + + +class GetParametersDataTypedDict(TypedDict): + r"""Parameter analytics data""" + + model: str + r"""Model identifier""" + supported_parameters: List[SupportedParameter] + r"""List of parameters supported by this model""" + + +class GetParametersData(BaseModel): + r"""Parameter analytics data""" + + model: str + r"""Model identifier""" + + supported_parameters: List[ + Annotated[SupportedParameter, PlainValidator(validate_open_enum(False))] + ] + r"""List of parameters supported by this model""" + + +class GetParametersResponseTypedDict(TypedDict): + r"""Returns the parameters for the specified model""" + + data: GetParametersDataTypedDict + r"""Parameter analytics data""" + + +class GetParametersResponse(BaseModel): + r"""Returns the parameters for the specified model""" + + data: GetParametersData + r"""Parameter analytics data""" diff --git a/src/openrouter/models/getuseractivityop.py b/src/openrouter/models/getuseractivityop.py new file mode 100644 index 0000000..05429e4 --- /dev/null +++ b/src/openrouter/models/getuseractivityop.py @@ -0,0 +1,37 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .activityitem import ActivityItem, ActivityItemTypedDict +from openrouter.types import BaseModel +from openrouter.utils import FieldMetadata, QueryParamMetadata +import pydantic +from typing import List, Optional +from typing_extensions import Annotated, NotRequired, TypedDict + + +class GetUserActivityRequestTypedDict(TypedDict): + date_: NotRequired[str] + r"""Filter by a single UTC date in the last 30 days (YYYY-MM-DD format).""" + + +class GetUserActivityRequest(BaseModel): + date_: Annotated[ + Optional[str], + pydantic.Field(alias="date"), + FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), + ] = None + r"""Filter by a single UTC date in the last 30 days (YYYY-MM-DD format).""" + + +class GetUserActivityResponseTypedDict(TypedDict): + r"""Returns user activity data grouped by endpoint""" + + data: List[ActivityItemTypedDict] + r"""List of activity items""" + + +class GetUserActivityResponse(BaseModel): + r"""Returns user activity data grouped by endpoint""" + + data: List[ActivityItem] + r"""List of activity items""" diff --git a/src/openrouter/models/imagegenerationstatus.py b/src/openrouter/models/imagegenerationstatus.py new file mode 100644 index 0000000..eb59bfd --- /dev/null +++ b/src/openrouter/models/imagegenerationstatus.py @@ -0,0 +1,16 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import UnrecognizedStr +from typing import Literal, Union + + +ImageGenerationStatus = Union[ + Literal[ + "in_progress", + "completed", + "generating", + "failed", + ], + UnrecognizedStr, +] diff --git a/src/openrouter/models/inputmodality.py b/src/openrouter/models/inputmodality.py new file mode 100644 index 0000000..3b0c560 --- /dev/null +++ b/src/openrouter/models/inputmodality.py @@ -0,0 +1,17 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import UnrecognizedStr +from typing import Literal, Union + + +InputModality = Union[ + Literal[ + "text", + "image", + "file", + "audio", + "video", + ], + UnrecognizedStr, +] diff --git a/src/openrouter/models/instructtype.py b/src/openrouter/models/instructtype.py new file mode 100644 index 0000000..4a58daf --- /dev/null +++ b/src/openrouter/models/instructtype.py @@ -0,0 +1,35 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import UnrecognizedStr +from typing import Literal, Union + + +InstructType = Union[ + Literal[ + "none", + "airoboros", + "alpaca", + "alpaca-modif", + "chatml", + "claude", + "code-llama", + "gemma", + "llama2", + "llama3", + "mistral", + "nemotron", + "neural", + "openchat", + "phi3", + "rwkv", + "vicuna", + "zephyr", + "deepseek-r1", + "deepseek-v3.1", + "qwq", + "qwen3", + ], + UnrecognizedStr, +] +r"""Instruction format type""" diff --git a/src/openrouter/models/internalserverresponseerrordata.py b/src/openrouter/models/internalserverresponseerrordata.py new file mode 100644 index 0000000..499f492 --- /dev/null +++ b/src/openrouter/models/internalserverresponseerrordata.py @@ -0,0 +1,61 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from pydantic import model_serializer +from typing import Any, Dict +from typing_extensions import NotRequired, TypedDict + + +class InternalServerResponseErrorDataTypedDict(TypedDict): + r"""Error data for InternalServerResponse""" + + code: int + message: str + metadata: NotRequired[Nullable[Dict[str, Nullable[Any]]]] + + +class InternalServerResponseErrorData(BaseModel): + r"""Error data for InternalServerResponse""" + + code: int + + message: str + + metadata: OptionalNullable[Dict[str, Nullable[Any]]] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["metadata"] + nullable_fields = ["metadata"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/jsonschemaconfig.py b/src/openrouter/models/jsonschemaconfig.py new file mode 100644 index 0000000..44ae090 --- /dev/null +++ b/src/openrouter/models/jsonschemaconfig.py @@ -0,0 +1,61 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +import pydantic +from pydantic import model_serializer +from typing import Any, Dict, Optional +from typing_extensions import Annotated, NotRequired, TypedDict + + +class JSONSchemaConfigTypedDict(TypedDict): + name: str + description: NotRequired[str] + schema_: NotRequired[Dict[str, Any]] + strict: NotRequired[Nullable[bool]] + + +class JSONSchemaConfig(BaseModel): + name: str + + description: Optional[str] = None + + schema_: Annotated[Optional[Dict[str, Any]], pydantic.Field(alias="schema")] = None + + strict: OptionalNullable[bool] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["description", "schema", "strict"] + nullable_fields = ["strict"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/listendpointsop.py b/src/openrouter/models/listendpointsop.py new file mode 100644 index 0000000..152ca6d --- /dev/null +++ b/src/openrouter/models/listendpointsop.py @@ -0,0 +1,36 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .listendpointsresponse import ListEndpointsResponse, ListEndpointsResponseTypedDict +from openrouter.types import BaseModel +from openrouter.utils import FieldMetadata, PathParamMetadata +from typing_extensions import Annotated, TypedDict + + +class ListEndpointsRequestTypedDict(TypedDict): + author: str + slug: str + + +class ListEndpointsRequest(BaseModel): + author: Annotated[ + str, FieldMetadata(path=PathParamMetadata(style="simple", explode=False)) + ] + + slug: Annotated[ + str, FieldMetadata(path=PathParamMetadata(style="simple", explode=False)) + ] + + +class EndpointsListEndpointsResponseTypedDict(TypedDict): + r"""Returns a list of endpoints""" + + data: ListEndpointsResponseTypedDict + r"""List of available endpoints for a model""" + + +class EndpointsListEndpointsResponse(BaseModel): + r"""Returns a list of endpoints""" + + data: ListEndpointsResponse + r"""List of available endpoints for a model""" diff --git a/src/openrouter/models/listendpointsresponse.py b/src/openrouter/models/listendpointsresponse.py new file mode 100644 index 0000000..f4f947a --- /dev/null +++ b/src/openrouter/models/listendpointsresponse.py @@ -0,0 +1,145 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .inputmodality import InputModality +from .instructtype import InstructType +from .outputmodality import OutputModality +from .publicendpoint import PublicEndpoint, PublicEndpointTypedDict +from openrouter.types import BaseModel, Nullable, UNSET_SENTINEL, UnrecognizedStr +from openrouter.utils import validate_open_enum +from pydantic import model_serializer +from pydantic.functional_validators import PlainValidator +from typing import List, Literal, Union +from typing_extensions import Annotated, TypedDict + + +Tokenizer = Union[ + Literal[ + "Router", + "Media", + "Other", + "GPT", + "Claude", + "Gemini", + "Grok", + "Cohere", + "Nova", + "Qwen", + "Yi", + "DeepSeek", + "Mistral", + "Llama2", + "Llama3", + "Llama4", + "PaLM", + "RWKV", + "Qwen3", + ], + UnrecognizedStr, +] +r"""Tokenizer type used by the model""" + + +class ArchitectureTypedDict(TypedDict): + r"""Model architecture information""" + + tokenizer: Nullable[Tokenizer] + instruct_type: Nullable[InstructType] + r"""Instruction format type""" + modality: Nullable[str] + r"""Primary modality of the model""" + input_modalities: List[InputModality] + r"""Supported input modalities""" + output_modalities: List[OutputModality] + r"""Supported output modalities""" + + +class Architecture(BaseModel): + r"""Model architecture information""" + + tokenizer: Annotated[Nullable[Tokenizer], PlainValidator(validate_open_enum(False))] + + instruct_type: Annotated[ + Nullable[InstructType], PlainValidator(validate_open_enum(False)) + ] + r"""Instruction format type""" + + modality: Nullable[str] + r"""Primary modality of the model""" + + input_modalities: List[ + Annotated[InputModality, PlainValidator(validate_open_enum(False))] + ] + r"""Supported input modalities""" + + output_modalities: List[ + Annotated[OutputModality, PlainValidator(validate_open_enum(False))] + ] + r"""Supported output modalities""" + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = [] + nullable_fields = ["tokenizer", "instruct_type", "modality"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m + + +class ListEndpointsResponseTypedDict(TypedDict): + r"""List of available endpoints for a model""" + + id: str + r"""Unique identifier for the model""" + name: str + r"""Display name of the model""" + created: float + r"""Unix timestamp of when the model was created""" + description: str + r"""Description of the model""" + architecture: ArchitectureTypedDict + endpoints: List[PublicEndpointTypedDict] + r"""List of available endpoints for this model""" + + +class ListEndpointsResponse(BaseModel): + r"""List of available endpoints for a model""" + + id: str + r"""Unique identifier for the model""" + + name: str + r"""Display name of the model""" + + created: float + r"""Unix timestamp of when the model was created""" + + description: str + r"""Description of the model""" + + architecture: Architecture + + endpoints: List[PublicEndpoint] + r"""List of available endpoints for this model""" diff --git a/src/openrouter/models/listendpointszdrop.py b/src/openrouter/models/listendpointszdrop.py new file mode 100644 index 0000000..0f31004 --- /dev/null +++ b/src/openrouter/models/listendpointszdrop.py @@ -0,0 +1,19 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .publicendpoint import PublicEndpoint, PublicEndpointTypedDict +from openrouter.types import BaseModel +from typing import List +from typing_extensions import TypedDict + + +class ListEndpointsZdrResponseTypedDict(TypedDict): + r"""Returns a list of endpoints""" + + data: List[PublicEndpointTypedDict] + + +class ListEndpointsZdrResponse(BaseModel): + r"""Returns a list of endpoints""" + + data: List[PublicEndpoint] diff --git a/src/openrouter/models/listmodelsuserop.py b/src/openrouter/models/listmodelsuserop.py new file mode 100644 index 0000000..bf66ce3 --- /dev/null +++ b/src/openrouter/models/listmodelsuserop.py @@ -0,0 +1,24 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel +from openrouter.utils import FieldMetadata, SecurityMetadata +from typing_extensions import Annotated, TypedDict + + +class ListModelsUserSecurityTypedDict(TypedDict): + bearer: str + + +class ListModelsUserSecurity(BaseModel): + bearer: Annotated[ + str, + FieldMetadata( + security=SecurityMetadata( + scheme=True, + scheme_type="http", + sub_type="bearer", + field_name="Authorization", + ) + ), + ] diff --git a/src/openrouter/models/listop.py b/src/openrouter/models/listop.py new file mode 100644 index 0000000..d4f87f7 --- /dev/null +++ b/src/openrouter/models/listop.py @@ -0,0 +1,186 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from datetime import datetime +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from openrouter.utils import FieldMetadata, QueryParamMetadata +from pydantic import model_serializer +from typing import List, Optional +from typing_extensions import Annotated, NotRequired, TypedDict + + +class ListRequestTypedDict(TypedDict): + include_disabled: NotRequired[str] + r"""Whether to include disabled API keys in the response""" + offset: NotRequired[str] + r"""Number of API keys to skip for pagination""" + + +class ListRequest(BaseModel): + include_disabled: Annotated[ + Optional[str], + FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), + ] = None + r"""Whether to include disabled API keys in the response""" + + offset: Annotated[ + Optional[str], + FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), + ] = None + r"""Number of API keys to skip for pagination""" + + +class ListDataTypedDict(TypedDict): + hash: str + r"""Unique hash identifier for the API key""" + name: str + r"""Name of the API key""" + label: str + r"""Human-readable label for the API key""" + disabled: bool + r"""Whether the API key is disabled""" + limit: Nullable[float] + r"""Spending limit for the API key in USD""" + limit_remaining: Nullable[float] + r"""Remaining spending limit in USD""" + limit_reset: Nullable[str] + r"""Type of limit reset for the API key""" + include_byok_in_limit: bool + r"""Whether to include external BYOK usage in the credit limit""" + usage: float + r"""Total OpenRouter credit usage (in USD) for the API key""" + usage_daily: float + r"""OpenRouter credit usage (in USD) for the current UTC day""" + usage_weekly: float + r"""OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday)""" + usage_monthly: float + r"""OpenRouter credit usage (in USD) for the current UTC month""" + byok_usage: float + r"""Total external BYOK usage (in USD) for the API key""" + byok_usage_daily: float + r"""External BYOK usage (in USD) for the current UTC day""" + byok_usage_weekly: float + r"""External BYOK usage (in USD) for the current UTC week (Monday-Sunday)""" + byok_usage_monthly: float + r"""External BYOK usage (in USD) for current UTC month""" + created_at: str + r"""ISO 8601 timestamp of when the API key was created""" + updated_at: Nullable[str] + r"""ISO 8601 timestamp of when the API key was last updated""" + expires_at: NotRequired[Nullable[datetime]] + r"""ISO 8601 UTC timestamp when the API key expires, or null if no expiration""" + + +class ListData(BaseModel): + hash: str + r"""Unique hash identifier for the API key""" + + name: str + r"""Name of the API key""" + + label: str + r"""Human-readable label for the API key""" + + disabled: bool + r"""Whether the API key is disabled""" + + limit: Nullable[float] + r"""Spending limit for the API key in USD""" + + limit_remaining: Nullable[float] + r"""Remaining spending limit in USD""" + + limit_reset: Nullable[str] + r"""Type of limit reset for the API key""" + + include_byok_in_limit: bool + r"""Whether to include external BYOK usage in the credit limit""" + + usage: float + r"""Total OpenRouter credit usage (in USD) for the API key""" + + usage_daily: float + r"""OpenRouter credit usage (in USD) for the current UTC day""" + + usage_weekly: float + r"""OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday)""" + + usage_monthly: float + r"""OpenRouter credit usage (in USD) for the current UTC month""" + + byok_usage: float + r"""Total external BYOK usage (in USD) for the API key""" + + byok_usage_daily: float + r"""External BYOK usage (in USD) for the current UTC day""" + + byok_usage_weekly: float + r"""External BYOK usage (in USD) for the current UTC week (Monday-Sunday)""" + + byok_usage_monthly: float + r"""External BYOK usage (in USD) for current UTC month""" + + created_at: str + r"""ISO 8601 timestamp of when the API key was created""" + + updated_at: Nullable[str] + r"""ISO 8601 timestamp of when the API key was last updated""" + + expires_at: OptionalNullable[datetime] = UNSET + r"""ISO 8601 UTC timestamp when the API key expires, or null if no expiration""" + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["expires_at"] + nullable_fields = [ + "limit", + "limit_remaining", + "limit_reset", + "updated_at", + "expires_at", + ] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m + + +class ListResponseTypedDict(TypedDict): + r"""List of API keys""" + + data: List[ListDataTypedDict] + r"""List of API keys""" + + +class ListResponse(BaseModel): + r"""List of API keys""" + + data: List[ListData] + r"""List of API keys""" diff --git a/src/openrouter/models/listprovidersop.py b/src/openrouter/models/listprovidersop.py new file mode 100644 index 0000000..4ff3f60 --- /dev/null +++ b/src/openrouter/models/listprovidersop.py @@ -0,0 +1,89 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from pydantic import model_serializer +from typing import List +from typing_extensions import NotRequired, TypedDict + + +class ListProvidersDataTypedDict(TypedDict): + name: str + r"""Display name of the provider""" + slug: str + r"""URL-friendly identifier for the provider""" + privacy_policy_url: Nullable[str] + r"""URL to the provider's privacy policy""" + terms_of_service_url: NotRequired[Nullable[str]] + r"""URL to the provider's terms of service""" + status_page_url: NotRequired[Nullable[str]] + r"""URL to the provider's status page""" + + +class ListProvidersData(BaseModel): + name: str + r"""Display name of the provider""" + + slug: str + r"""URL-friendly identifier for the provider""" + + privacy_policy_url: Nullable[str] + r"""URL to the provider's privacy policy""" + + terms_of_service_url: OptionalNullable[str] = UNSET + r"""URL to the provider's terms of service""" + + status_page_url: OptionalNullable[str] = UNSET + r"""URL to the provider's status page""" + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["terms_of_service_url", "status_page_url"] + nullable_fields = [ + "privacy_policy_url", + "terms_of_service_url", + "status_page_url", + ] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m + + +class ListProvidersResponseTypedDict(TypedDict): + r"""Returns a list of providers""" + + data: List[ListProvidersDataTypedDict] + + +class ListProvidersResponse(BaseModel): + r"""Returns a list of providers""" + + data: List[ListProvidersData] diff --git a/src/openrouter/models/message.py b/src/openrouter/models/message.py new file mode 100644 index 0000000..676b497 --- /dev/null +++ b/src/openrouter/models/message.py @@ -0,0 +1,68 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .assistantmessage import AssistantMessage, AssistantMessageTypedDict +from .chatmessagecontentitemtext import ( + ChatMessageContentItemText, + ChatMessageContentItemTextTypedDict, +) +from .systemmessage import SystemMessage, SystemMessageTypedDict +from .toolresponsemessage import ToolResponseMessage, ToolResponseMessageTypedDict +from .usermessage import UserMessage, UserMessageTypedDict +from openrouter.types import BaseModel +from openrouter.utils import validate_const +import pydantic +from pydantic.functional_validators import AfterValidator +from typing import List, Literal, Optional, Union +from typing_extensions import Annotated, NotRequired, TypeAliasType, TypedDict + + +MessageContentTypedDict = TypeAliasType( + "MessageContentTypedDict", Union[str, List[ChatMessageContentItemTextTypedDict]] +) + + +MessageContent = TypeAliasType( + "MessageContent", Union[str, List[ChatMessageContentItemText]] +) + + +class MessageDeveloperTypedDict(TypedDict): + content: MessageContentTypedDict + role: Literal["developer"] + name: NotRequired[str] + + +class MessageDeveloper(BaseModel): + content: MessageContent + + ROLE: Annotated[ + Annotated[Literal["developer"], AfterValidator(validate_const("developer"))], + pydantic.Field(alias="role"), + ] = "developer" + + name: Optional[str] = None + + +MessageTypedDict = TypeAliasType( + "MessageTypedDict", + Union[ + SystemMessageTypedDict, + UserMessageTypedDict, + MessageDeveloperTypedDict, + ToolResponseMessageTypedDict, + AssistantMessageTypedDict, + ], +) + + +Message = TypeAliasType( + "Message", + Union[ + SystemMessage, + UserMessage, + MessageDeveloper, + ToolResponseMessage, + AssistantMessage, + ], +) diff --git a/src/openrouter/models/model.py b/src/openrouter/models/model.py new file mode 100644 index 0000000..16f1a88 --- /dev/null +++ b/src/openrouter/models/model.py @@ -0,0 +1,132 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .defaultparameters import DefaultParameters, DefaultParametersTypedDict +from .modelarchitecture import ModelArchitecture, ModelArchitectureTypedDict +from .parameter import Parameter +from .perrequestlimits import PerRequestLimits, PerRequestLimitsTypedDict +from .publicpricing import PublicPricing, PublicPricingTypedDict +from .topproviderinfo import TopProviderInfo, TopProviderInfoTypedDict +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from openrouter.utils import validate_open_enum +from pydantic import model_serializer +from pydantic.functional_validators import PlainValidator +from typing import List, Optional +from typing_extensions import Annotated, NotRequired, TypedDict + + +class ModelTypedDict(TypedDict): + r"""Information about an AI model available on OpenRouter""" + + id: str + r"""Unique identifier for the model""" + canonical_slug: str + r"""Canonical slug for the model""" + name: str + r"""Display name of the model""" + created: float + r"""Unix timestamp of when the model was created""" + pricing: PublicPricingTypedDict + r"""Pricing information for the model""" + context_length: Nullable[float] + r"""Maximum context length in tokens""" + architecture: ModelArchitectureTypedDict + r"""Model architecture information""" + top_provider: TopProviderInfoTypedDict + r"""Information about the top provider for this model""" + per_request_limits: Nullable[PerRequestLimitsTypedDict] + r"""Per-request token limits""" + supported_parameters: List[Parameter] + r"""List of supported parameters for this model""" + default_parameters: Nullable[DefaultParametersTypedDict] + r"""Default parameters for this model""" + hugging_face_id: NotRequired[Nullable[str]] + r"""Hugging Face model identifier, if applicable""" + description: NotRequired[str] + r"""Description of the model""" + + +class Model(BaseModel): + r"""Information about an AI model available on OpenRouter""" + + id: str + r"""Unique identifier for the model""" + + canonical_slug: str + r"""Canonical slug for the model""" + + name: str + r"""Display name of the model""" + + created: float + r"""Unix timestamp of when the model was created""" + + pricing: PublicPricing + r"""Pricing information for the model""" + + context_length: Nullable[float] + r"""Maximum context length in tokens""" + + architecture: ModelArchitecture + r"""Model architecture information""" + + top_provider: TopProviderInfo + r"""Information about the top provider for this model""" + + per_request_limits: Nullable[PerRequestLimits] + r"""Per-request token limits""" + + supported_parameters: List[ + Annotated[Parameter, PlainValidator(validate_open_enum(False))] + ] + r"""List of supported parameters for this model""" + + default_parameters: Nullable[DefaultParameters] + r"""Default parameters for this model""" + + hugging_face_id: OptionalNullable[str] = UNSET + r"""Hugging Face model identifier, if applicable""" + + description: Optional[str] = None + r"""Description of the model""" + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["hugging_face_id", "description"] + nullable_fields = [ + "hugging_face_id", + "context_length", + "per_request_limits", + "default_parameters", + ] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/modelarchitecture.py b/src/openrouter/models/modelarchitecture.py new file mode 100644 index 0000000..656f0c0 --- /dev/null +++ b/src/openrouter/models/modelarchitecture.py @@ -0,0 +1,122 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .inputmodality import InputModality +from .modelgroup import ModelGroup +from .outputmodality import OutputModality +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, + UnrecognizedStr, +) +from openrouter.utils import validate_open_enum +from pydantic import model_serializer +from pydantic.functional_validators import PlainValidator +from typing import List, Literal, Optional, Union +from typing_extensions import Annotated, NotRequired, TypedDict + + +ModelArchitectureInstructType = Union[ + Literal[ + "none", + "airoboros", + "alpaca", + "alpaca-modif", + "chatml", + "claude", + "code-llama", + "gemma", + "llama2", + "llama3", + "mistral", + "nemotron", + "neural", + "openchat", + "phi3", + "rwkv", + "vicuna", + "zephyr", + "deepseek-r1", + "deepseek-v3.1", + "qwq", + "qwen3", + ], + UnrecognizedStr, +] +r"""Instruction format type""" + + +class ModelArchitectureTypedDict(TypedDict): + r"""Model architecture information""" + + modality: Nullable[str] + r"""Primary modality of the model""" + input_modalities: List[InputModality] + r"""Supported input modalities""" + output_modalities: List[OutputModality] + r"""Supported output modalities""" + tokenizer: NotRequired[ModelGroup] + r"""Tokenizer type used by the model""" + instruct_type: NotRequired[Nullable[ModelArchitectureInstructType]] + r"""Instruction format type""" + + +class ModelArchitecture(BaseModel): + r"""Model architecture information""" + + modality: Nullable[str] + r"""Primary modality of the model""" + + input_modalities: List[ + Annotated[InputModality, PlainValidator(validate_open_enum(False))] + ] + r"""Supported input modalities""" + + output_modalities: List[ + Annotated[OutputModality, PlainValidator(validate_open_enum(False))] + ] + r"""Supported output modalities""" + + tokenizer: Annotated[ + Optional[ModelGroup], PlainValidator(validate_open_enum(False)) + ] = None + r"""Tokenizer type used by the model""" + + instruct_type: Annotated[ + OptionalNullable[ModelArchitectureInstructType], + PlainValidator(validate_open_enum(False)), + ] = UNSET + r"""Instruction format type""" + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["tokenizer", "instruct_type"] + nullable_fields = ["instruct_type", "modality"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/modelgroup.py b/src/openrouter/models/modelgroup.py new file mode 100644 index 0000000..ae6ee9e --- /dev/null +++ b/src/openrouter/models/modelgroup.py @@ -0,0 +1,32 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import UnrecognizedStr +from typing import Literal, Union + + +ModelGroup = Union[ + Literal[ + "Router", + "Media", + "Other", + "GPT", + "Claude", + "Gemini", + "Grok", + "Cohere", + "Nova", + "Qwen", + "Yi", + "DeepSeek", + "Mistral", + "Llama2", + "Llama3", + "Llama4", + "PaLM", + "RWKV", + "Qwen3", + ], + UnrecognizedStr, +] +r"""Tokenizer type used by the model""" diff --git a/src/openrouter/models/modelscountresponse.py b/src/openrouter/models/modelscountresponse.py new file mode 100644 index 0000000..698420e --- /dev/null +++ b/src/openrouter/models/modelscountresponse.py @@ -0,0 +1,33 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel +from typing_extensions import TypedDict + + +class ModelsCountResponseDataTypedDict(TypedDict): + r"""Model count data""" + + count: float + r"""Total number of available models""" + + +class ModelsCountResponseData(BaseModel): + r"""Model count data""" + + count: float + r"""Total number of available models""" + + +class ModelsCountResponseTypedDict(TypedDict): + r"""Model count data""" + + data: ModelsCountResponseDataTypedDict + r"""Model count data""" + + +class ModelsCountResponse(BaseModel): + r"""Model count data""" + + data: ModelsCountResponseData + r"""Model count data""" diff --git a/src/openrouter/models/modelslistresponse.py b/src/openrouter/models/modelslistresponse.py new file mode 100644 index 0000000..8497c58 --- /dev/null +++ b/src/openrouter/models/modelslistresponse.py @@ -0,0 +1,21 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .model import Model, ModelTypedDict +from openrouter.types import BaseModel +from typing import List +from typing_extensions import TypedDict + + +class ModelsListResponseTypedDict(TypedDict): + r"""List of available models""" + + data: List[ModelTypedDict] + r"""List of available models""" + + +class ModelsListResponse(BaseModel): + r"""List of available models""" + + data: List[Model] + r"""List of available models""" diff --git a/src/openrouter/models/namedtoolchoice.py b/src/openrouter/models/namedtoolchoice.py new file mode 100644 index 0000000..ac7d345 --- /dev/null +++ b/src/openrouter/models/namedtoolchoice.py @@ -0,0 +1,31 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel +from openrouter.utils import validate_const +import pydantic +from pydantic.functional_validators import AfterValidator +from typing import Literal +from typing_extensions import Annotated, TypedDict + + +class NamedToolChoiceFunctionTypedDict(TypedDict): + name: str + + +class NamedToolChoiceFunction(BaseModel): + name: str + + +class NamedToolChoiceTypedDict(TypedDict): + function: NamedToolChoiceFunctionTypedDict + type: Literal["function"] + + +class NamedToolChoice(BaseModel): + function: NamedToolChoiceFunction + + TYPE: Annotated[ + Annotated[Literal["function"], AfterValidator(validate_const("function"))], + pydantic.Field(alias="type"), + ] = "function" diff --git a/src/openrouter/models/notfoundresponseerrordata.py b/src/openrouter/models/notfoundresponseerrordata.py new file mode 100644 index 0000000..5b8ca0c --- /dev/null +++ b/src/openrouter/models/notfoundresponseerrordata.py @@ -0,0 +1,61 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from pydantic import model_serializer +from typing import Any, Dict +from typing_extensions import NotRequired, TypedDict + + +class NotFoundResponseErrorDataTypedDict(TypedDict): + r"""Error data for NotFoundResponse""" + + code: int + message: str + metadata: NotRequired[Nullable[Dict[str, Nullable[Any]]]] + + +class NotFoundResponseErrorData(BaseModel): + r"""Error data for NotFoundResponse""" + + code: int + + message: str + + metadata: OptionalNullable[Dict[str, Nullable[Any]]] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["metadata"] + nullable_fields = ["metadata"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/openairesponsesannotation.py b/src/openrouter/models/openairesponsesannotation.py new file mode 100644 index 0000000..315df01 --- /dev/null +++ b/src/openrouter/models/openairesponsesannotation.py @@ -0,0 +1,19 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .filecitation import FileCitation, FileCitationTypedDict +from .filepath import FilePath, FilePathTypedDict +from .urlcitation import URLCitation, URLCitationTypedDict +from typing import Union +from typing_extensions import TypeAliasType + + +OpenAIResponsesAnnotationTypedDict = TypeAliasType( + "OpenAIResponsesAnnotationTypedDict", + Union[FilePathTypedDict, FileCitationTypedDict, URLCitationTypedDict], +) + + +OpenAIResponsesAnnotation = TypeAliasType( + "OpenAIResponsesAnnotation", Union[FilePath, FileCitation, URLCitation] +) diff --git a/src/openrouter/models/openairesponsesincludable.py b/src/openrouter/models/openairesponsesincludable.py new file mode 100644 index 0000000..49903b8 --- /dev/null +++ b/src/openrouter/models/openairesponsesincludable.py @@ -0,0 +1,17 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import UnrecognizedStr +from typing import Literal, Union + + +OpenAIResponsesIncludable = Union[ + Literal[ + "file_search_call.results", + "message.input_image.image_url", + "computer_call_output.output.image_url", + "reasoning.encrypted_content", + "code_interpreter_call.outputs", + ], + UnrecognizedStr, +] diff --git a/src/openrouter/models/openairesponsesincompletedetails.py b/src/openrouter/models/openairesponsesincompletedetails.py new file mode 100644 index 0000000..3a87455 --- /dev/null +++ b/src/openrouter/models/openairesponsesincompletedetails.py @@ -0,0 +1,27 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel, UnrecognizedStr +from openrouter.utils import validate_open_enum +from pydantic.functional_validators import PlainValidator +from typing import Literal, Optional, Union +from typing_extensions import Annotated, NotRequired, TypedDict + + +Reason = Union[ + Literal[ + "max_output_tokens", + "content_filter", + ], + UnrecognizedStr, +] + + +class OpenAIResponsesIncompleteDetailsTypedDict(TypedDict): + reason: NotRequired[Reason] + + +class OpenAIResponsesIncompleteDetails(BaseModel): + reason: Annotated[Optional[Reason], PlainValidator(validate_open_enum(False))] = ( + None + ) diff --git a/src/openrouter/models/openairesponsesinput_union.py b/src/openrouter/models/openairesponsesinput_union.py new file mode 100644 index 0000000..aab3daf --- /dev/null +++ b/src/openrouter/models/openairesponsesinput_union.py @@ -0,0 +1,330 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .outputitemimagegenerationcall import ( + OutputItemImageGenerationCall, + OutputItemImageGenerationCallTypedDict, +) +from .outputmessage import OutputMessage, OutputMessageTypedDict +from .responseinputaudio import ResponseInputAudio, ResponseInputAudioTypedDict +from .responseinputfile import ResponseInputFile, ResponseInputFileTypedDict +from .responseinputimage import ResponseInputImage, ResponseInputImageTypedDict +from .responseinputtext import ResponseInputText, ResponseInputTextTypedDict +from .toolcallstatus import ToolCallStatus +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from openrouter.utils import get_discriminator, validate_open_enum +from pydantic import Discriminator, Tag, model_serializer +from pydantic.functional_validators import PlainValidator +from typing import Any, List, Literal, Optional, Union +from typing_extensions import Annotated, NotRequired, TypeAliasType, TypedDict + + +OpenAIResponsesInputTypeFunctionCall = Literal["function_call",] + + +class OpenAIResponsesInputFunctionCallTypedDict(TypedDict): + type: OpenAIResponsesInputTypeFunctionCall + call_id: str + name: str + arguments: str + id: NotRequired[str] + status: NotRequired[Nullable[ToolCallStatus]] + + +class OpenAIResponsesInputFunctionCall(BaseModel): + type: OpenAIResponsesInputTypeFunctionCall + + call_id: str + + name: str + + arguments: str + + id: Optional[str] = None + + status: Annotated[ + OptionalNullable[ToolCallStatus], PlainValidator(validate_open_enum(False)) + ] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["id", "status"] + nullable_fields = ["status"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m + + +OpenAIResponsesInputTypeFunctionCallOutput = Literal["function_call_output",] + + +class OpenAIResponsesInputFunctionCallOutputTypedDict(TypedDict): + type: OpenAIResponsesInputTypeFunctionCallOutput + call_id: str + output: str + id: NotRequired[Nullable[str]] + status: NotRequired[Nullable[ToolCallStatus]] + + +class OpenAIResponsesInputFunctionCallOutput(BaseModel): + type: OpenAIResponsesInputTypeFunctionCallOutput + + call_id: str + + output: str + + id: OptionalNullable[str] = UNSET + + status: Annotated[ + OptionalNullable[ToolCallStatus], PlainValidator(validate_open_enum(False)) + ] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["id", "status"] + nullable_fields = ["id", "status"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m + + +OpenAIResponsesInputTypeMessage2 = Literal["message",] + + +OpenAIResponsesInputRoleDeveloper2 = Literal["developer",] + + +OpenAIResponsesInputRoleSystem2 = Literal["system",] + + +OpenAIResponsesInputRoleUser2 = Literal["user",] + + +OpenAIResponsesInputRoleUnion2TypedDict = TypeAliasType( + "OpenAIResponsesInputRoleUnion2TypedDict", + Union[ + OpenAIResponsesInputRoleUser2, + OpenAIResponsesInputRoleSystem2, + OpenAIResponsesInputRoleDeveloper2, + ], +) + + +OpenAIResponsesInputRoleUnion2 = TypeAliasType( + "OpenAIResponsesInputRoleUnion2", + Union[ + OpenAIResponsesInputRoleUser2, + OpenAIResponsesInputRoleSystem2, + OpenAIResponsesInputRoleDeveloper2, + ], +) + + +OpenAIResponsesInputContent3TypedDict = TypeAliasType( + "OpenAIResponsesInputContent3TypedDict", + Union[ + ResponseInputTextTypedDict, + ResponseInputAudioTypedDict, + ResponseInputImageTypedDict, + ResponseInputFileTypedDict, + ], +) + + +OpenAIResponsesInputContent3 = Annotated[ + Union[ + Annotated[ResponseInputText, Tag("input_text")], + Annotated[ResponseInputImage, Tag("input_image")], + Annotated[ResponseInputFile, Tag("input_file")], + Annotated[ResponseInputAudio, Tag("input_audio")], + ], + Discriminator(lambda m: get_discriminator(m, "type", "type")), +] + + +class OpenAIResponsesInputMessage2TypedDict(TypedDict): + id: str + role: OpenAIResponsesInputRoleUnion2TypedDict + content: List[OpenAIResponsesInputContent3TypedDict] + type: NotRequired[OpenAIResponsesInputTypeMessage2] + + +class OpenAIResponsesInputMessage2(BaseModel): + id: str + + role: OpenAIResponsesInputRoleUnion2 + + content: List[OpenAIResponsesInputContent3] + + type: Optional[OpenAIResponsesInputTypeMessage2] = None + + +OpenAIResponsesInputTypeMessage1 = Literal["message",] + + +OpenAIResponsesInputRoleDeveloper1 = Literal["developer",] + + +OpenAIResponsesInputRoleAssistant = Literal["assistant",] + + +OpenAIResponsesInputRoleSystem1 = Literal["system",] + + +OpenAIResponsesInputRoleUser1 = Literal["user",] + + +OpenAIResponsesInputRoleUnion1TypedDict = TypeAliasType( + "OpenAIResponsesInputRoleUnion1TypedDict", + Union[ + OpenAIResponsesInputRoleUser1, + OpenAIResponsesInputRoleSystem1, + OpenAIResponsesInputRoleAssistant, + OpenAIResponsesInputRoleDeveloper1, + ], +) + + +OpenAIResponsesInputRoleUnion1 = TypeAliasType( + "OpenAIResponsesInputRoleUnion1", + Union[ + OpenAIResponsesInputRoleUser1, + OpenAIResponsesInputRoleSystem1, + OpenAIResponsesInputRoleAssistant, + OpenAIResponsesInputRoleDeveloper1, + ], +) + + +OpenAIResponsesInputContent1TypedDict = TypeAliasType( + "OpenAIResponsesInputContent1TypedDict", + Union[ + ResponseInputTextTypedDict, + ResponseInputAudioTypedDict, + ResponseInputImageTypedDict, + ResponseInputFileTypedDict, + ], +) + + +OpenAIResponsesInputContent1 = Annotated[ + Union[ + Annotated[ResponseInputText, Tag("input_text")], + Annotated[ResponseInputImage, Tag("input_image")], + Annotated[ResponseInputFile, Tag("input_file")], + Annotated[ResponseInputAudio, Tag("input_audio")], + ], + Discriminator(lambda m: get_discriminator(m, "type", "type")), +] + + +OpenAIResponsesInputContent2TypedDict = TypeAliasType( + "OpenAIResponsesInputContent2TypedDict", + Union[List[OpenAIResponsesInputContent1TypedDict], str], +) + + +OpenAIResponsesInputContent2 = TypeAliasType( + "OpenAIResponsesInputContent2", Union[List[OpenAIResponsesInputContent1], str] +) + + +class OpenAIResponsesInputMessage1TypedDict(TypedDict): + role: OpenAIResponsesInputRoleUnion1TypedDict + content: OpenAIResponsesInputContent2TypedDict + type: NotRequired[OpenAIResponsesInputTypeMessage1] + + +class OpenAIResponsesInputMessage1(BaseModel): + role: OpenAIResponsesInputRoleUnion1 + + content: OpenAIResponsesInputContent2 + + type: Optional[OpenAIResponsesInputTypeMessage1] = None + + +OpenAIResponsesInputUnion1TypedDict = TypeAliasType( + "OpenAIResponsesInputUnion1TypedDict", + Union[ + OpenAIResponsesInputMessage1TypedDict, + OpenAIResponsesInputMessage2TypedDict, + OutputItemImageGenerationCallTypedDict, + OpenAIResponsesInputFunctionCallOutputTypedDict, + OutputMessageTypedDict, + OpenAIResponsesInputFunctionCallTypedDict, + ], +) + + +OpenAIResponsesInputUnion1 = TypeAliasType( + "OpenAIResponsesInputUnion1", + Union[ + OpenAIResponsesInputMessage1, + OpenAIResponsesInputMessage2, + OutputItemImageGenerationCall, + OpenAIResponsesInputFunctionCallOutput, + OutputMessage, + OpenAIResponsesInputFunctionCall, + ], +) + + +OpenAIResponsesInputUnionTypedDict = TypeAliasType( + "OpenAIResponsesInputUnionTypedDict", + Union[str, List[OpenAIResponsesInputUnion1TypedDict], Any], +) + + +OpenAIResponsesInputUnion = TypeAliasType( + "OpenAIResponsesInputUnion", Union[str, List[OpenAIResponsesInputUnion1], Any] +) diff --git a/src/openrouter/models/openairesponsesprompt.py b/src/openrouter/models/openairesponsesprompt.py new file mode 100644 index 0000000..f938d7a --- /dev/null +++ b/src/openrouter/models/openairesponsesprompt.py @@ -0,0 +1,73 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .responseinputfile import ResponseInputFile, ResponseInputFileTypedDict +from .responseinputimage import ResponseInputImage, ResponseInputImageTypedDict +from .responseinputtext import ResponseInputText, ResponseInputTextTypedDict +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from pydantic import model_serializer +from typing import Dict, Union +from typing_extensions import NotRequired, TypeAliasType, TypedDict + + +VariablesTypedDict = TypeAliasType( + "VariablesTypedDict", + Union[ + ResponseInputTextTypedDict, + ResponseInputImageTypedDict, + ResponseInputFileTypedDict, + str, + ], +) + + +Variables = TypeAliasType( + "Variables", Union[ResponseInputText, ResponseInputImage, ResponseInputFile, str] +) + + +class OpenAIResponsesPromptTypedDict(TypedDict): + id: str + variables: NotRequired[Nullable[Dict[str, VariablesTypedDict]]] + + +class OpenAIResponsesPrompt(BaseModel): + id: str + + variables: OptionalNullable[Dict[str, Variables]] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["variables"] + nullable_fields = ["variables"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/openairesponsesreasoningconfig.py b/src/openrouter/models/openairesponsesreasoningconfig.py new file mode 100644 index 0000000..5c4d6da --- /dev/null +++ b/src/openrouter/models/openairesponsesreasoningconfig.py @@ -0,0 +1,63 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .openairesponsesreasoningeffort import OpenAIResponsesReasoningEffort +from .reasoningsummaryverbosity import ReasoningSummaryVerbosity +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from openrouter.utils import validate_open_enum +from pydantic import model_serializer +from pydantic.functional_validators import PlainValidator +from typing import Optional +from typing_extensions import Annotated, NotRequired, TypedDict + + +class OpenAIResponsesReasoningConfigTypedDict(TypedDict): + effort: NotRequired[Nullable[OpenAIResponsesReasoningEffort]] + summary: NotRequired[ReasoningSummaryVerbosity] + + +class OpenAIResponsesReasoningConfig(BaseModel): + effort: Annotated[ + OptionalNullable[OpenAIResponsesReasoningEffort], + PlainValidator(validate_open_enum(False)), + ] = UNSET + + summary: Annotated[ + Optional[ReasoningSummaryVerbosity], PlainValidator(validate_open_enum(False)) + ] = None + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["effort", "summary"] + nullable_fields = ["effort"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/openairesponsesreasoningeffort.py b/src/openrouter/models/openairesponsesreasoningeffort.py new file mode 100644 index 0000000..34d2cf0 --- /dev/null +++ b/src/openrouter/models/openairesponsesreasoningeffort.py @@ -0,0 +1,16 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import UnrecognizedStr +from typing import Literal, Union + + +OpenAIResponsesReasoningEffort = Union[ + Literal[ + "high", + "medium", + "low", + "minimal", + ], + UnrecognizedStr, +] diff --git a/src/openrouter/models/openairesponsesrefusalcontent.py b/src/openrouter/models/openairesponsesrefusalcontent.py new file mode 100644 index 0000000..9500782 --- /dev/null +++ b/src/openrouter/models/openairesponsesrefusalcontent.py @@ -0,0 +1,20 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel +from typing import Literal +from typing_extensions import TypedDict + + +OpenAIResponsesRefusalContentType = Literal["refusal",] + + +class OpenAIResponsesRefusalContentTypedDict(TypedDict): + type: OpenAIResponsesRefusalContentType + refusal: str + + +class OpenAIResponsesRefusalContent(BaseModel): + type: OpenAIResponsesRefusalContentType + + refusal: str diff --git a/src/openrouter/models/openairesponsesresponsestatus.py b/src/openrouter/models/openairesponsesresponsestatus.py new file mode 100644 index 0000000..cd39bad --- /dev/null +++ b/src/openrouter/models/openairesponsesresponsestatus.py @@ -0,0 +1,18 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import UnrecognizedStr +from typing import Literal, Union + + +OpenAIResponsesResponseStatus = Union[ + Literal[ + "completed", + "incomplete", + "in_progress", + "failed", + "cancelled", + "queued", + ], + UnrecognizedStr, +] diff --git a/src/openrouter/models/openairesponsesservicetier.py b/src/openrouter/models/openairesponsesservicetier.py new file mode 100644 index 0000000..8c682e8 --- /dev/null +++ b/src/openrouter/models/openairesponsesservicetier.py @@ -0,0 +1,17 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import UnrecognizedStr +from typing import Literal, Union + + +OpenAIResponsesServiceTier = Union[ + Literal[ + "auto", + "default", + "flex", + "priority", + "scale", + ], + UnrecognizedStr, +] diff --git a/src/openrouter/models/openairesponsestoolchoice_union.py b/src/openrouter/models/openairesponsestoolchoice_union.py new file mode 100644 index 0000000..5db29bb --- /dev/null +++ b/src/openrouter/models/openairesponsestoolchoice_union.py @@ -0,0 +1,87 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel +from typing import Literal, Union +from typing_extensions import TypeAliasType, TypedDict + + +OpenAIResponsesToolChoiceTypeWebSearchPreview = Literal["web_search_preview",] + + +OpenAIResponsesToolChoiceTypeWebSearchPreview20250311 = Literal[ + "web_search_preview_2025_03_11", +] + + +TypeTypedDict = TypeAliasType( + "TypeTypedDict", + Union[ + OpenAIResponsesToolChoiceTypeWebSearchPreview20250311, + OpenAIResponsesToolChoiceTypeWebSearchPreview, + ], +) + + +Type = TypeAliasType( + "Type", + Union[ + OpenAIResponsesToolChoiceTypeWebSearchPreview20250311, + OpenAIResponsesToolChoiceTypeWebSearchPreview, + ], +) + + +class OpenAIResponsesToolChoiceTypedDict(TypedDict): + type: TypeTypedDict + + +class OpenAIResponsesToolChoice(BaseModel): + type: Type + + +OpenAIResponsesToolChoiceTypeFunction = Literal["function",] + + +class OpenAIResponsesToolChoiceFunctionTypedDict(TypedDict): + type: OpenAIResponsesToolChoiceTypeFunction + name: str + + +class OpenAIResponsesToolChoiceFunction(BaseModel): + type: OpenAIResponsesToolChoiceTypeFunction + + name: str + + +OpenAIResponsesToolChoiceRequired = Literal["required",] + + +OpenAIResponsesToolChoiceNone = Literal["none",] + + +OpenAIResponsesToolChoiceAuto = Literal["auto",] + + +OpenAIResponsesToolChoiceUnionTypedDict = TypeAliasType( + "OpenAIResponsesToolChoiceUnionTypedDict", + Union[ + OpenAIResponsesToolChoiceTypedDict, + OpenAIResponsesToolChoiceFunctionTypedDict, + OpenAIResponsesToolChoiceAuto, + OpenAIResponsesToolChoiceNone, + OpenAIResponsesToolChoiceRequired, + ], +) + + +OpenAIResponsesToolChoiceUnion = TypeAliasType( + "OpenAIResponsesToolChoiceUnion", + Union[ + OpenAIResponsesToolChoice, + OpenAIResponsesToolChoiceFunction, + OpenAIResponsesToolChoiceAuto, + OpenAIResponsesToolChoiceNone, + OpenAIResponsesToolChoiceRequired, + ], +) diff --git a/src/openrouter/models/openairesponsestruncation.py b/src/openrouter/models/openairesponsestruncation.py new file mode 100644 index 0000000..c481d06 --- /dev/null +++ b/src/openrouter/models/openairesponsestruncation.py @@ -0,0 +1,14 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import UnrecognizedStr +from typing import Literal, Union + + +OpenAIResponsesTruncation = Union[ + Literal[ + "auto", + "disabled", + ], + UnrecognizedStr, +] diff --git a/src/openrouter/models/openresponseseasyinputmessage.py b/src/openrouter/models/openresponseseasyinputmessage.py new file mode 100644 index 0000000..8065a96 --- /dev/null +++ b/src/openrouter/models/openresponseseasyinputmessage.py @@ -0,0 +1,97 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .responseinputaudio import ResponseInputAudio, ResponseInputAudioTypedDict +from .responseinputfile import ResponseInputFile, ResponseInputFileTypedDict +from .responseinputimage import ResponseInputImage, ResponseInputImageTypedDict +from .responseinputtext import ResponseInputText, ResponseInputTextTypedDict +from openrouter.types import BaseModel +from openrouter.utils import get_discriminator +from pydantic import Discriminator, Tag +from typing import List, Literal, Optional, Union +from typing_extensions import Annotated, NotRequired, TypeAliasType, TypedDict + + +OpenResponsesEasyInputMessageType = Literal["message",] + + +OpenResponsesEasyInputMessageRoleDeveloper = Literal["developer",] + + +OpenResponsesEasyInputMessageRoleAssistant = Literal["assistant",] + + +OpenResponsesEasyInputMessageRoleSystem = Literal["system",] + + +OpenResponsesEasyInputMessageRoleUser = Literal["user",] + + +OpenResponsesEasyInputMessageRoleUnionTypedDict = TypeAliasType( + "OpenResponsesEasyInputMessageRoleUnionTypedDict", + Union[ + OpenResponsesEasyInputMessageRoleUser, + OpenResponsesEasyInputMessageRoleSystem, + OpenResponsesEasyInputMessageRoleAssistant, + OpenResponsesEasyInputMessageRoleDeveloper, + ], +) + + +OpenResponsesEasyInputMessageRoleUnion = TypeAliasType( + "OpenResponsesEasyInputMessageRoleUnion", + Union[ + OpenResponsesEasyInputMessageRoleUser, + OpenResponsesEasyInputMessageRoleSystem, + OpenResponsesEasyInputMessageRoleAssistant, + OpenResponsesEasyInputMessageRoleDeveloper, + ], +) + + +OpenResponsesEasyInputMessageContent1TypedDict = TypeAliasType( + "OpenResponsesEasyInputMessageContent1TypedDict", + Union[ + ResponseInputTextTypedDict, + ResponseInputAudioTypedDict, + ResponseInputImageTypedDict, + ResponseInputFileTypedDict, + ], +) + + +OpenResponsesEasyInputMessageContent1 = Annotated[ + Union[ + Annotated[ResponseInputText, Tag("input_text")], + Annotated[ResponseInputImage, Tag("input_image")], + Annotated[ResponseInputFile, Tag("input_file")], + Annotated[ResponseInputAudio, Tag("input_audio")], + ], + Discriminator(lambda m: get_discriminator(m, "type", "type")), +] + + +OpenResponsesEasyInputMessageContent2TypedDict = TypeAliasType( + "OpenResponsesEasyInputMessageContent2TypedDict", + Union[List[OpenResponsesEasyInputMessageContent1TypedDict], str], +) + + +OpenResponsesEasyInputMessageContent2 = TypeAliasType( + "OpenResponsesEasyInputMessageContent2", + Union[List[OpenResponsesEasyInputMessageContent1], str], +) + + +class OpenResponsesEasyInputMessageTypedDict(TypedDict): + role: OpenResponsesEasyInputMessageRoleUnionTypedDict + content: OpenResponsesEasyInputMessageContent2TypedDict + type: NotRequired[OpenResponsesEasyInputMessageType] + + +class OpenResponsesEasyInputMessage(BaseModel): + role: OpenResponsesEasyInputMessageRoleUnion + + content: OpenResponsesEasyInputMessageContent2 + + type: Optional[OpenResponsesEasyInputMessageType] = None diff --git a/src/openrouter/models/openresponseserrorevent.py b/src/openrouter/models/openresponseserrorevent.py new file mode 100644 index 0000000..f392bb7 --- /dev/null +++ b/src/openrouter/models/openresponseserrorevent.py @@ -0,0 +1,64 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel, Nullable, UNSET_SENTINEL +from pydantic import model_serializer +from typing import Literal +from typing_extensions import TypedDict + + +OpenResponsesErrorEventType = Literal["error",] + + +class OpenResponsesErrorEventTypedDict(TypedDict): + r"""Event emitted when an error occurs during streaming""" + + type: OpenResponsesErrorEventType + code: Nullable[str] + message: str + param: Nullable[str] + sequence_number: float + + +class OpenResponsesErrorEvent(BaseModel): + r"""Event emitted when an error occurs during streaming""" + + type: OpenResponsesErrorEventType + + code: Nullable[str] + + message: str + + param: Nullable[str] + + sequence_number: float + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = [] + nullable_fields = ["code", "param"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/openresponsesfunctioncalloutput.py b/src/openrouter/models/openresponsesfunctioncalloutput.py new file mode 100644 index 0000000..d033081 --- /dev/null +++ b/src/openrouter/models/openresponsesfunctioncalloutput.py @@ -0,0 +1,75 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .toolcallstatus import ToolCallStatus +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from openrouter.utils import validate_open_enum +from pydantic import model_serializer +from pydantic.functional_validators import PlainValidator +from typing import Literal +from typing_extensions import Annotated, NotRequired, TypedDict + + +OpenResponsesFunctionCallOutputType = Literal["function_call_output",] + + +class OpenResponsesFunctionCallOutputTypedDict(TypedDict): + r"""The output from a function call execution""" + + type: OpenResponsesFunctionCallOutputType + call_id: str + output: str + id: NotRequired[Nullable[str]] + status: NotRequired[Nullable[ToolCallStatus]] + + +class OpenResponsesFunctionCallOutput(BaseModel): + r"""The output from a function call execution""" + + type: OpenResponsesFunctionCallOutputType + + call_id: str + + output: str + + id: OptionalNullable[str] = UNSET + + status: Annotated[ + OptionalNullable[ToolCallStatus], PlainValidator(validate_open_enum(False)) + ] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["id", "status"] + nullable_fields = ["id", "status"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/openresponsesfunctiontoolcall.py b/src/openrouter/models/openresponsesfunctiontoolcall.py new file mode 100644 index 0000000..f61957c --- /dev/null +++ b/src/openrouter/models/openresponsesfunctiontoolcall.py @@ -0,0 +1,78 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .toolcallstatus import ToolCallStatus +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from openrouter.utils import validate_open_enum +from pydantic import model_serializer +from pydantic.functional_validators import PlainValidator +from typing import Literal +from typing_extensions import Annotated, NotRequired, TypedDict + + +OpenResponsesFunctionToolCallType = Literal["function_call",] + + +class OpenResponsesFunctionToolCallTypedDict(TypedDict): + r"""A function call initiated by the model""" + + type: OpenResponsesFunctionToolCallType + call_id: str + name: str + arguments: str + id: str + status: NotRequired[Nullable[ToolCallStatus]] + + +class OpenResponsesFunctionToolCall(BaseModel): + r"""A function call initiated by the model""" + + type: OpenResponsesFunctionToolCallType + + call_id: str + + name: str + + arguments: str + + id: str + + status: Annotated[ + OptionalNullable[ToolCallStatus], PlainValidator(validate_open_enum(False)) + ] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["status"] + nullable_fields = ["status"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/openresponsesimagegencallcompleted.py b/src/openrouter/models/openresponsesimagegencallcompleted.py new file mode 100644 index 0000000..bff9ec1 --- /dev/null +++ b/src/openrouter/models/openresponsesimagegencallcompleted.py @@ -0,0 +1,32 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel +from typing import Literal +from typing_extensions import TypedDict + + +OpenResponsesImageGenCallCompletedType = Literal[ + "response.image_generation_call.completed", +] + + +class OpenResponsesImageGenCallCompletedTypedDict(TypedDict): + r"""Image generation call completed""" + + type: OpenResponsesImageGenCallCompletedType + item_id: str + output_index: float + sequence_number: float + + +class OpenResponsesImageGenCallCompleted(BaseModel): + r"""Image generation call completed""" + + type: OpenResponsesImageGenCallCompletedType + + item_id: str + + output_index: float + + sequence_number: float diff --git a/src/openrouter/models/openresponsesimagegencallgenerating.py b/src/openrouter/models/openresponsesimagegencallgenerating.py new file mode 100644 index 0000000..86b5791 --- /dev/null +++ b/src/openrouter/models/openresponsesimagegencallgenerating.py @@ -0,0 +1,32 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel +from typing import Literal +from typing_extensions import TypedDict + + +OpenResponsesImageGenCallGeneratingType = Literal[ + "response.image_generation_call.generating", +] + + +class OpenResponsesImageGenCallGeneratingTypedDict(TypedDict): + r"""Image generation call is generating""" + + type: OpenResponsesImageGenCallGeneratingType + item_id: str + output_index: float + sequence_number: float + + +class OpenResponsesImageGenCallGenerating(BaseModel): + r"""Image generation call is generating""" + + type: OpenResponsesImageGenCallGeneratingType + + item_id: str + + output_index: float + + sequence_number: float diff --git a/src/openrouter/models/openresponsesimagegencallinprogress.py b/src/openrouter/models/openresponsesimagegencallinprogress.py new file mode 100644 index 0000000..08e78ac --- /dev/null +++ b/src/openrouter/models/openresponsesimagegencallinprogress.py @@ -0,0 +1,32 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel +from typing import Literal +from typing_extensions import TypedDict + + +OpenResponsesImageGenCallInProgressType = Literal[ + "response.image_generation_call.in_progress", +] + + +class OpenResponsesImageGenCallInProgressTypedDict(TypedDict): + r"""Image generation call in progress""" + + type: OpenResponsesImageGenCallInProgressType + item_id: str + output_index: float + sequence_number: float + + +class OpenResponsesImageGenCallInProgress(BaseModel): + r"""Image generation call in progress""" + + type: OpenResponsesImageGenCallInProgressType + + item_id: str + + output_index: float + + sequence_number: float diff --git a/src/openrouter/models/openresponsesimagegencallpartialimage.py b/src/openrouter/models/openresponsesimagegencallpartialimage.py new file mode 100644 index 0000000..712ecac --- /dev/null +++ b/src/openrouter/models/openresponsesimagegencallpartialimage.py @@ -0,0 +1,38 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel +from typing import Literal +from typing_extensions import TypedDict + + +OpenResponsesImageGenCallPartialImageType = Literal[ + "response.image_generation_call.partial_image", +] + + +class OpenResponsesImageGenCallPartialImageTypedDict(TypedDict): + r"""Image generation call with partial image""" + + type: OpenResponsesImageGenCallPartialImageType + item_id: str + output_index: float + sequence_number: float + partial_image_b64: str + partial_image_index: float + + +class OpenResponsesImageGenCallPartialImage(BaseModel): + r"""Image generation call with partial image""" + + type: OpenResponsesImageGenCallPartialImageType + + item_id: str + + output_index: float + + sequence_number: float + + partial_image_b64: str + + partial_image_index: float diff --git a/src/openrouter/models/openresponsesinput.py b/src/openrouter/models/openresponsesinput.py new file mode 100644 index 0000000..af37abe --- /dev/null +++ b/src/openrouter/models/openresponsesinput.py @@ -0,0 +1,97 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .openresponseseasyinputmessage import ( + OpenResponsesEasyInputMessage, + OpenResponsesEasyInputMessageTypedDict, +) +from .openresponsesfunctioncalloutput import ( + OpenResponsesFunctionCallOutput, + OpenResponsesFunctionCallOutputTypedDict, +) +from .openresponsesfunctiontoolcall import ( + OpenResponsesFunctionToolCall, + OpenResponsesFunctionToolCallTypedDict, +) +from .openresponsesinputmessageitem import ( + OpenResponsesInputMessageItem, + OpenResponsesInputMessageItemTypedDict, +) +from .openresponsesreasoning import ( + OpenResponsesReasoning, + OpenResponsesReasoningTypedDict, +) +from .responsesimagegenerationcall import ( + ResponsesImageGenerationCall, + ResponsesImageGenerationCallTypedDict, +) +from .responsesoutputitemfilesearchcall import ( + ResponsesOutputItemFileSearchCall, + ResponsesOutputItemFileSearchCallTypedDict, +) +from .responsesoutputitemfunctioncall import ( + ResponsesOutputItemFunctionCall, + ResponsesOutputItemFunctionCallTypedDict, +) +from .responsesoutputitemreasoning import ( + ResponsesOutputItemReasoning, + ResponsesOutputItemReasoningTypedDict, +) +from .responsesoutputmessage import ( + ResponsesOutputMessage, + ResponsesOutputMessageTypedDict, +) +from .responseswebsearchcalloutput import ( + ResponsesWebSearchCallOutput, + ResponsesWebSearchCallOutputTypedDict, +) +from typing import List, Union +from typing_extensions import TypeAliasType + + +OpenResponsesInput1TypedDict = TypeAliasType( + "OpenResponsesInput1TypedDict", + Union[ + OpenResponsesEasyInputMessageTypedDict, + ResponsesWebSearchCallOutputTypedDict, + OpenResponsesInputMessageItemTypedDict, + ResponsesOutputItemFileSearchCallTypedDict, + ResponsesImageGenerationCallTypedDict, + OpenResponsesFunctionCallOutputTypedDict, + ResponsesOutputMessageTypedDict, + OpenResponsesFunctionToolCallTypedDict, + ResponsesOutputItemReasoningTypedDict, + ResponsesOutputItemFunctionCallTypedDict, + OpenResponsesReasoningTypedDict, + ], +) + + +OpenResponsesInput1 = TypeAliasType( + "OpenResponsesInput1", + Union[ + OpenResponsesEasyInputMessage, + ResponsesWebSearchCallOutput, + OpenResponsesInputMessageItem, + ResponsesOutputItemFileSearchCall, + ResponsesImageGenerationCall, + OpenResponsesFunctionCallOutput, + ResponsesOutputMessage, + OpenResponsesFunctionToolCall, + ResponsesOutputItemReasoning, + ResponsesOutputItemFunctionCall, + OpenResponsesReasoning, + ], +) + + +OpenResponsesInputTypedDict = TypeAliasType( + "OpenResponsesInputTypedDict", Union[str, List[OpenResponsesInput1TypedDict]] +) +r"""Input for a response request - can be a string or array of items""" + + +OpenResponsesInput = TypeAliasType( + "OpenResponsesInput", Union[str, List[OpenResponsesInput1]] +) +r"""Input for a response request - can be a string or array of items""" diff --git a/src/openrouter/models/openresponsesinputmessageitem.py b/src/openrouter/models/openresponsesinputmessageitem.py new file mode 100644 index 0000000..1a2b95a --- /dev/null +++ b/src/openrouter/models/openresponsesinputmessageitem.py @@ -0,0 +1,83 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .responseinputaudio import ResponseInputAudio, ResponseInputAudioTypedDict +from .responseinputfile import ResponseInputFile, ResponseInputFileTypedDict +from .responseinputimage import ResponseInputImage, ResponseInputImageTypedDict +from .responseinputtext import ResponseInputText, ResponseInputTextTypedDict +from openrouter.types import BaseModel +from openrouter.utils import get_discriminator +from pydantic import Discriminator, Tag +from typing import List, Literal, Optional, Union +from typing_extensions import Annotated, NotRequired, TypeAliasType, TypedDict + + +OpenResponsesInputMessageItemType = Literal["message",] + + +OpenResponsesInputMessageItemRoleDeveloper = Literal["developer",] + + +OpenResponsesInputMessageItemRoleSystem = Literal["system",] + + +OpenResponsesInputMessageItemRoleUser = Literal["user",] + + +OpenResponsesInputMessageItemRoleUnionTypedDict = TypeAliasType( + "OpenResponsesInputMessageItemRoleUnionTypedDict", + Union[ + OpenResponsesInputMessageItemRoleUser, + OpenResponsesInputMessageItemRoleSystem, + OpenResponsesInputMessageItemRoleDeveloper, + ], +) + + +OpenResponsesInputMessageItemRoleUnion = TypeAliasType( + "OpenResponsesInputMessageItemRoleUnion", + Union[ + OpenResponsesInputMessageItemRoleUser, + OpenResponsesInputMessageItemRoleSystem, + OpenResponsesInputMessageItemRoleDeveloper, + ], +) + + +OpenResponsesInputMessageItemContentTypedDict = TypeAliasType( + "OpenResponsesInputMessageItemContentTypedDict", + Union[ + ResponseInputTextTypedDict, + ResponseInputAudioTypedDict, + ResponseInputImageTypedDict, + ResponseInputFileTypedDict, + ], +) + + +OpenResponsesInputMessageItemContent = Annotated[ + Union[ + Annotated[ResponseInputText, Tag("input_text")], + Annotated[ResponseInputImage, Tag("input_image")], + Annotated[ResponseInputFile, Tag("input_file")], + Annotated[ResponseInputAudio, Tag("input_audio")], + ], + Discriminator(lambda m: get_discriminator(m, "type", "type")), +] + + +class OpenResponsesInputMessageItemTypedDict(TypedDict): + role: OpenResponsesInputMessageItemRoleUnionTypedDict + content: List[OpenResponsesInputMessageItemContentTypedDict] + id: NotRequired[str] + type: NotRequired[OpenResponsesInputMessageItemType] + + +class OpenResponsesInputMessageItem(BaseModel): + role: OpenResponsesInputMessageItemRoleUnion + + content: List[OpenResponsesInputMessageItemContent] + + id: Optional[str] = None + + type: Optional[OpenResponsesInputMessageItemType] = None diff --git a/src/openrouter/models/openresponseslogprobs.py b/src/openrouter/models/openresponseslogprobs.py new file mode 100644 index 0000000..78b6a1c --- /dev/null +++ b/src/openrouter/models/openresponseslogprobs.py @@ -0,0 +1,28 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .openresponsestoplogprobs import ( + OpenResponsesTopLogprobs, + OpenResponsesTopLogprobsTypedDict, +) +from openrouter.types import BaseModel +from typing import List, Optional +from typing_extensions import NotRequired, TypedDict + + +class OpenResponsesLogProbsTypedDict(TypedDict): + r"""Log probability information for a token""" + + logprob: float + token: str + top_logprobs: NotRequired[List[OpenResponsesTopLogprobsTypedDict]] + + +class OpenResponsesLogProbs(BaseModel): + r"""Log probability information for a token""" + + logprob: float + + token: str + + top_logprobs: Optional[List[OpenResponsesTopLogprobs]] = None diff --git a/src/openrouter/models/openresponsesnonstreamingresponse.py b/src/openrouter/models/openresponsesnonstreamingresponse.py new file mode 100644 index 0000000..6051f4e --- /dev/null +++ b/src/openrouter/models/openresponsesnonstreamingresponse.py @@ -0,0 +1,324 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .openairesponsesincompletedetails import ( + OpenAIResponsesIncompleteDetails, + OpenAIResponsesIncompleteDetailsTypedDict, +) +from .openairesponsesinput_union import ( + OpenAIResponsesInputUnion, + OpenAIResponsesInputUnionTypedDict, +) +from .openairesponsesprompt import OpenAIResponsesPrompt, OpenAIResponsesPromptTypedDict +from .openairesponsesreasoningconfig import ( + OpenAIResponsesReasoningConfig, + OpenAIResponsesReasoningConfigTypedDict, +) +from .openairesponsesresponsestatus import OpenAIResponsesResponseStatus +from .openairesponsesservicetier import OpenAIResponsesServiceTier +from .openairesponsestoolchoice_union import ( + OpenAIResponsesToolChoiceUnion, + OpenAIResponsesToolChoiceUnionTypedDict, +) +from .openairesponsestruncation import OpenAIResponsesTruncation +from .openresponsesusage import OpenResponsesUsage, OpenResponsesUsageTypedDict +from .openresponseswebsearch20250826tool import ( + OpenResponsesWebSearch20250826Tool, + OpenResponsesWebSearch20250826ToolTypedDict, +) +from .openresponseswebsearchpreview20250311tool import ( + OpenResponsesWebSearchPreview20250311Tool, + OpenResponsesWebSearchPreview20250311ToolTypedDict, +) +from .openresponseswebsearchpreviewtool import ( + OpenResponsesWebSearchPreviewTool, + OpenResponsesWebSearchPreviewToolTypedDict, +) +from .openresponseswebsearchtool import ( + OpenResponsesWebSearchTool, + OpenResponsesWebSearchToolTypedDict, +) +from .responseserrorfield import ResponsesErrorField, ResponsesErrorFieldTypedDict +from .responsesoutputitem import ResponsesOutputItem, ResponsesOutputItemTypedDict +from .responsetextconfig import ResponseTextConfig, ResponseTextConfigTypedDict +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from openrouter.utils import validate_open_enum +from pydantic import model_serializer +from pydantic.functional_validators import PlainValidator +from typing import Any, Dict, List, Literal, Optional, Union +from typing_extensions import Annotated, NotRequired, TypeAliasType, TypedDict + + +Object = Literal["response",] + + +OpenResponsesNonStreamingResponseType = Literal["function",] + + +class OpenResponsesNonStreamingResponseToolFunctionTypedDict(TypedDict): + r"""Function tool definition""" + + type: OpenResponsesNonStreamingResponseType + name: str + parameters: Nullable[Dict[str, Nullable[Any]]] + description: NotRequired[Nullable[str]] + strict: NotRequired[Nullable[bool]] + + +class OpenResponsesNonStreamingResponseToolFunction(BaseModel): + r"""Function tool definition""" + + type: OpenResponsesNonStreamingResponseType + + name: str + + parameters: Nullable[Dict[str, Nullable[Any]]] + + description: OptionalNullable[str] = UNSET + + strict: OptionalNullable[bool] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["description", "strict"] + nullable_fields = ["description", "strict", "parameters"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m + + +OpenResponsesNonStreamingResponseToolUnionTypedDict = TypeAliasType( + "OpenResponsesNonStreamingResponseToolUnionTypedDict", + Union[ + OpenResponsesWebSearchPreviewToolTypedDict, + OpenResponsesWebSearchPreview20250311ToolTypedDict, + OpenResponsesWebSearchToolTypedDict, + OpenResponsesWebSearch20250826ToolTypedDict, + OpenResponsesNonStreamingResponseToolFunctionTypedDict, + ], +) + + +OpenResponsesNonStreamingResponseToolUnion = TypeAliasType( + "OpenResponsesNonStreamingResponseToolUnion", + Union[ + OpenResponsesWebSearchPreviewTool, + OpenResponsesWebSearchPreview20250311Tool, + OpenResponsesWebSearchTool, + OpenResponsesWebSearch20250826Tool, + OpenResponsesNonStreamingResponseToolFunction, + ], +) + + +class OpenResponsesNonStreamingResponseTypedDict(TypedDict): + r"""Complete non-streaming response from the Responses API""" + + id: str + object: Object + created_at: float + model: str + output: List[ResponsesOutputItemTypedDict] + error: Nullable[ResponsesErrorFieldTypedDict] + r"""Error information returned from the API""" + incomplete_details: Nullable[OpenAIResponsesIncompleteDetailsTypedDict] + temperature: Nullable[float] + top_p: Nullable[float] + instructions: Nullable[OpenAIResponsesInputUnionTypedDict] + metadata: Nullable[Dict[str, str]] + r"""Metadata key-value pairs for the request. Keys must be ≤64 characters and cannot contain brackets. Values must be ≤512 characters. Maximum 16 pairs allowed.""" + tools: List[OpenResponsesNonStreamingResponseToolUnionTypedDict] + tool_choice: OpenAIResponsesToolChoiceUnionTypedDict + parallel_tool_calls: bool + status: NotRequired[OpenAIResponsesResponseStatus] + user: NotRequired[Nullable[str]] + output_text: NotRequired[str] + prompt_cache_key: NotRequired[Nullable[str]] + safety_identifier: NotRequired[Nullable[str]] + usage: NotRequired[OpenResponsesUsageTypedDict] + r"""Token usage information for the response""" + max_tool_calls: NotRequired[Nullable[float]] + top_logprobs: NotRequired[float] + max_output_tokens: NotRequired[Nullable[float]] + prompt: NotRequired[Nullable[OpenAIResponsesPromptTypedDict]] + background: NotRequired[Nullable[bool]] + previous_response_id: NotRequired[Nullable[str]] + reasoning: NotRequired[Nullable[OpenAIResponsesReasoningConfigTypedDict]] + service_tier: NotRequired[Nullable[OpenAIResponsesServiceTier]] + store: NotRequired[bool] + truncation: NotRequired[Nullable[OpenAIResponsesTruncation]] + text: NotRequired[ResponseTextConfigTypedDict] + r"""Text output configuration including format and verbosity""" + + +class OpenResponsesNonStreamingResponse(BaseModel): + r"""Complete non-streaming response from the Responses API""" + + id: str + + object: Object + + created_at: float + + model: str + + output: List[ResponsesOutputItem] + + error: Nullable[ResponsesErrorField] + r"""Error information returned from the API""" + + incomplete_details: Nullable[OpenAIResponsesIncompleteDetails] + + temperature: Nullable[float] + + top_p: Nullable[float] + + instructions: Nullable[OpenAIResponsesInputUnion] + + metadata: Nullable[Dict[str, str]] + r"""Metadata key-value pairs for the request. Keys must be ≤64 characters and cannot contain brackets. Values must be ≤512 characters. Maximum 16 pairs allowed.""" + + tools: List[OpenResponsesNonStreamingResponseToolUnion] + + tool_choice: OpenAIResponsesToolChoiceUnion + + parallel_tool_calls: bool + + status: Annotated[ + Optional[OpenAIResponsesResponseStatus], + PlainValidator(validate_open_enum(False)), + ] = None + + user: OptionalNullable[str] = UNSET + + output_text: Optional[str] = None + + prompt_cache_key: OptionalNullable[str] = UNSET + + safety_identifier: OptionalNullable[str] = UNSET + + usage: Optional[OpenResponsesUsage] = None + r"""Token usage information for the response""" + + max_tool_calls: OptionalNullable[float] = UNSET + + top_logprobs: Optional[float] = None + + max_output_tokens: OptionalNullable[float] = UNSET + + prompt: OptionalNullable[OpenAIResponsesPrompt] = UNSET + + background: OptionalNullable[bool] = UNSET + + previous_response_id: OptionalNullable[str] = UNSET + + reasoning: OptionalNullable[OpenAIResponsesReasoningConfig] = UNSET + + service_tier: Annotated[ + OptionalNullable[OpenAIResponsesServiceTier], + PlainValidator(validate_open_enum(False)), + ] = UNSET + + store: Optional[bool] = None + + truncation: Annotated[ + OptionalNullable[OpenAIResponsesTruncation], + PlainValidator(validate_open_enum(False)), + ] = UNSET + + text: Optional[ResponseTextConfig] = None + r"""Text output configuration including format and verbosity""" + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = [ + "status", + "user", + "output_text", + "prompt_cache_key", + "safety_identifier", + "usage", + "max_tool_calls", + "top_logprobs", + "max_output_tokens", + "prompt", + "background", + "previous_response_id", + "reasoning", + "service_tier", + "store", + "truncation", + "text", + ] + nullable_fields = [ + "user", + "prompt_cache_key", + "safety_identifier", + "error", + "incomplete_details", + "max_tool_calls", + "max_output_tokens", + "temperature", + "top_p", + "instructions", + "metadata", + "prompt", + "background", + "previous_response_id", + "reasoning", + "service_tier", + "truncation", + ] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/openresponsesreasoning.py b/src/openrouter/models/openresponsesreasoning.py new file mode 100644 index 0000000..f115e26 --- /dev/null +++ b/src/openrouter/models/openresponsesreasoning.py @@ -0,0 +1,137 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .reasoningsummarytext import ReasoningSummaryText, ReasoningSummaryTextTypedDict +from .reasoningtextcontent import ReasoningTextContent, ReasoningTextContentTypedDict +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, + UnrecognizedStr, +) +from openrouter.utils import validate_open_enum +import pydantic +from pydantic import model_serializer +from pydantic.functional_validators import PlainValidator +from typing import List, Literal, Optional, Union +from typing_extensions import Annotated, NotRequired, TypeAliasType, TypedDict + + +OpenResponsesReasoningType = Literal["reasoning",] + + +OpenResponsesReasoningStatusInProgress = Literal["in_progress",] + + +OpenResponsesReasoningStatusIncomplete = Literal["incomplete",] + + +OpenResponsesReasoningStatusCompleted = Literal["completed",] + + +OpenResponsesReasoningStatusUnionTypedDict = TypeAliasType( + "OpenResponsesReasoningStatusUnionTypedDict", + Union[ + OpenResponsesReasoningStatusCompleted, + OpenResponsesReasoningStatusIncomplete, + OpenResponsesReasoningStatusInProgress, + ], +) + + +OpenResponsesReasoningStatusUnion = TypeAliasType( + "OpenResponsesReasoningStatusUnion", + Union[ + OpenResponsesReasoningStatusCompleted, + OpenResponsesReasoningStatusIncomplete, + OpenResponsesReasoningStatusInProgress, + ], +) + + +OpenResponsesReasoningFormat = Union[ + Literal[ + "unknown", + "openai-responses-v1", + "xai-responses-v1", + "anthropic-claude-v1", + ], + UnrecognizedStr, +] + + +class OpenResponsesReasoningTypedDict(TypedDict): + r"""Reasoning output item with signature and format extensions""" + + type: OpenResponsesReasoningType + id: str + summary: List[ReasoningSummaryTextTypedDict] + content: NotRequired[List[ReasoningTextContentTypedDict]] + encrypted_content: NotRequired[Nullable[str]] + status: NotRequired[OpenResponsesReasoningStatusUnionTypedDict] + signature: NotRequired[Nullable[str]] + format_: NotRequired[Nullable[OpenResponsesReasoningFormat]] + + +class OpenResponsesReasoning(BaseModel): + r"""Reasoning output item with signature and format extensions""" + + type: OpenResponsesReasoningType + + id: str + + summary: List[ReasoningSummaryText] + + content: Optional[List[ReasoningTextContent]] = None + + encrypted_content: OptionalNullable[str] = UNSET + + status: Optional[OpenResponsesReasoningStatusUnion] = None + + signature: OptionalNullable[str] = UNSET + + format_: Annotated[ + Annotated[ + OptionalNullable[OpenResponsesReasoningFormat], + PlainValidator(validate_open_enum(False)), + ], + pydantic.Field(alias="format"), + ] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = [ + "content", + "encrypted_content", + "status", + "signature", + "format", + ] + nullable_fields = ["encrypted_content", "signature", "format"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/openresponsesreasoningconfig.py b/src/openrouter/models/openresponsesreasoningconfig.py new file mode 100644 index 0000000..f909558 --- /dev/null +++ b/src/openrouter/models/openresponsesreasoningconfig.py @@ -0,0 +1,73 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .openairesponsesreasoningeffort import OpenAIResponsesReasoningEffort +from .reasoningsummaryverbosity import ReasoningSummaryVerbosity +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from openrouter.utils import validate_open_enum +from pydantic import model_serializer +from pydantic.functional_validators import PlainValidator +from typing import Optional +from typing_extensions import Annotated, NotRequired, TypedDict + + +class OpenResponsesReasoningConfigTypedDict(TypedDict): + r"""Configuration for reasoning mode in the response""" + + effort: NotRequired[Nullable[OpenAIResponsesReasoningEffort]] + summary: NotRequired[ReasoningSummaryVerbosity] + max_tokens: NotRequired[Nullable[float]] + enabled: NotRequired[Nullable[bool]] + + +class OpenResponsesReasoningConfig(BaseModel): + r"""Configuration for reasoning mode in the response""" + + effort: Annotated[ + OptionalNullable[OpenAIResponsesReasoningEffort], + PlainValidator(validate_open_enum(False)), + ] = UNSET + + summary: Annotated[ + Optional[ReasoningSummaryVerbosity], PlainValidator(validate_open_enum(False)) + ] = None + + max_tokens: OptionalNullable[float] = UNSET + + enabled: OptionalNullable[bool] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["effort", "summary", "max_tokens", "enabled"] + nullable_fields = ["effort", "max_tokens", "enabled"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/openresponsesreasoningdeltaevent.py b/src/openrouter/models/openresponsesreasoningdeltaevent.py new file mode 100644 index 0000000..b9b6ea4 --- /dev/null +++ b/src/openrouter/models/openresponsesreasoningdeltaevent.py @@ -0,0 +1,36 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel +from typing import Literal +from typing_extensions import TypedDict + + +OpenResponsesReasoningDeltaEventType = Literal["response.reasoning_text.delta",] + + +class OpenResponsesReasoningDeltaEventTypedDict(TypedDict): + r"""Event emitted when reasoning text delta is streamed""" + + type: OpenResponsesReasoningDeltaEventType + output_index: float + item_id: str + content_index: float + delta: str + sequence_number: float + + +class OpenResponsesReasoningDeltaEvent(BaseModel): + r"""Event emitted when reasoning text delta is streamed""" + + type: OpenResponsesReasoningDeltaEventType + + output_index: float + + item_id: str + + content_index: float + + delta: str + + sequence_number: float diff --git a/src/openrouter/models/openresponsesreasoningdoneevent.py b/src/openrouter/models/openresponsesreasoningdoneevent.py new file mode 100644 index 0000000..4614314 --- /dev/null +++ b/src/openrouter/models/openresponsesreasoningdoneevent.py @@ -0,0 +1,36 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel +from typing import Literal +from typing_extensions import TypedDict + + +OpenResponsesReasoningDoneEventType = Literal["response.reasoning_text.done",] + + +class OpenResponsesReasoningDoneEventTypedDict(TypedDict): + r"""Event emitted when reasoning text streaming is complete""" + + type: OpenResponsesReasoningDoneEventType + output_index: float + item_id: str + content_index: float + text: str + sequence_number: float + + +class OpenResponsesReasoningDoneEvent(BaseModel): + r"""Event emitted when reasoning text streaming is complete""" + + type: OpenResponsesReasoningDoneEventType + + output_index: float + + item_id: str + + content_index: float + + text: str + + sequence_number: float diff --git a/src/openrouter/models/openresponsesreasoningsummarypartaddedevent.py b/src/openrouter/models/openresponsesreasoningsummarypartaddedevent.py new file mode 100644 index 0000000..11425bb --- /dev/null +++ b/src/openrouter/models/openresponsesreasoningsummarypartaddedevent.py @@ -0,0 +1,39 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .reasoningsummarytext import ReasoningSummaryText, ReasoningSummaryTextTypedDict +from openrouter.types import BaseModel +from typing import Literal +from typing_extensions import TypedDict + + +OpenResponsesReasoningSummaryPartAddedEventType = Literal[ + "response.reasoning_summary_part.added", +] + + +class OpenResponsesReasoningSummaryPartAddedEventTypedDict(TypedDict): + r"""Event emitted when a reasoning summary part is added""" + + type: OpenResponsesReasoningSummaryPartAddedEventType + output_index: float + item_id: str + summary_index: float + part: ReasoningSummaryTextTypedDict + sequence_number: float + + +class OpenResponsesReasoningSummaryPartAddedEvent(BaseModel): + r"""Event emitted when a reasoning summary part is added""" + + type: OpenResponsesReasoningSummaryPartAddedEventType + + output_index: float + + item_id: str + + summary_index: float + + part: ReasoningSummaryText + + sequence_number: float diff --git a/src/openrouter/models/openresponsesreasoningsummarytextdeltaevent.py b/src/openrouter/models/openresponsesreasoningsummarytextdeltaevent.py new file mode 100644 index 0000000..dc51eda --- /dev/null +++ b/src/openrouter/models/openresponsesreasoningsummarytextdeltaevent.py @@ -0,0 +1,38 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel +from typing import Literal +from typing_extensions import TypedDict + + +OpenResponsesReasoningSummaryTextDeltaEventType = Literal[ + "response.reasoning_summary_text.delta", +] + + +class OpenResponsesReasoningSummaryTextDeltaEventTypedDict(TypedDict): + r"""Event emitted when reasoning summary text delta is streamed""" + + type: OpenResponsesReasoningSummaryTextDeltaEventType + item_id: str + output_index: float + summary_index: float + delta: str + sequence_number: float + + +class OpenResponsesReasoningSummaryTextDeltaEvent(BaseModel): + r"""Event emitted when reasoning summary text delta is streamed""" + + type: OpenResponsesReasoningSummaryTextDeltaEventType + + item_id: str + + output_index: float + + summary_index: float + + delta: str + + sequence_number: float diff --git a/src/openrouter/models/openresponsesreasoningsummarytextdoneevent.py b/src/openrouter/models/openresponsesreasoningsummarytextdoneevent.py new file mode 100644 index 0000000..f2f5302 --- /dev/null +++ b/src/openrouter/models/openresponsesreasoningsummarytextdoneevent.py @@ -0,0 +1,38 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel +from typing import Literal +from typing_extensions import TypedDict + + +OpenResponsesReasoningSummaryTextDoneEventType = Literal[ + "response.reasoning_summary_text.done", +] + + +class OpenResponsesReasoningSummaryTextDoneEventTypedDict(TypedDict): + r"""Event emitted when reasoning summary text streaming is complete""" + + type: OpenResponsesReasoningSummaryTextDoneEventType + item_id: str + output_index: float + summary_index: float + text: str + sequence_number: float + + +class OpenResponsesReasoningSummaryTextDoneEvent(BaseModel): + r"""Event emitted when reasoning summary text streaming is complete""" + + type: OpenResponsesReasoningSummaryTextDoneEventType + + item_id: str + + output_index: float + + summary_index: float + + text: str + + sequence_number: float diff --git a/src/openrouter/models/openresponsesrequest.py b/src/openrouter/models/openresponsesrequest.py new file mode 100644 index 0000000..706716f --- /dev/null +++ b/src/openrouter/models/openresponsesrequest.py @@ -0,0 +1,654 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .openairesponsesincludable import OpenAIResponsesIncludable +from .openairesponsesprompt import OpenAIResponsesPrompt, OpenAIResponsesPromptTypedDict +from .openairesponsestoolchoice_union import ( + OpenAIResponsesToolChoiceUnion, + OpenAIResponsesToolChoiceUnionTypedDict, +) +from .openresponsesinput import OpenResponsesInput, OpenResponsesInputTypedDict +from .openresponsesreasoningconfig import ( + OpenResponsesReasoningConfig, + OpenResponsesReasoningConfigTypedDict, +) +from .openresponsesresponsetext import ( + OpenResponsesResponseText, + OpenResponsesResponseTextTypedDict, +) +from .openresponseswebsearch20250826tool import ( + OpenResponsesWebSearch20250826Tool, + OpenResponsesWebSearch20250826ToolTypedDict, +) +from .openresponseswebsearchpreview20250311tool import ( + OpenResponsesWebSearchPreview20250311Tool, + OpenResponsesWebSearchPreview20250311ToolTypedDict, +) +from .openresponseswebsearchpreviewtool import ( + OpenResponsesWebSearchPreviewTool, + OpenResponsesWebSearchPreviewToolTypedDict, +) +from .openresponseswebsearchtool import ( + OpenResponsesWebSearchTool, + OpenResponsesWebSearchToolTypedDict, +) +from .providername import ProviderName +from .quantization import Quantization +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, + UnrecognizedStr, +) +from openrouter.utils import validate_open_enum +from pydantic import model_serializer +from pydantic.functional_validators import PlainValidator +from typing import Any, Dict, List, Literal, Optional, Union +from typing_extensions import Annotated, NotRequired, TypeAliasType, TypedDict + + +OpenResponsesRequestType = Literal["function",] + + +class OpenResponsesRequestToolFunctionTypedDict(TypedDict): + r"""Function tool definition""" + + type: OpenResponsesRequestType + name: str + parameters: Nullable[Dict[str, Nullable[Any]]] + description: NotRequired[Nullable[str]] + strict: NotRequired[Nullable[bool]] + + +class OpenResponsesRequestToolFunction(BaseModel): + r"""Function tool definition""" + + type: OpenResponsesRequestType + + name: str + + parameters: Nullable[Dict[str, Nullable[Any]]] + + description: OptionalNullable[str] = UNSET + + strict: OptionalNullable[bool] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["description", "strict"] + nullable_fields = ["description", "strict", "parameters"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m + + +OpenResponsesRequestToolUnionTypedDict = TypeAliasType( + "OpenResponsesRequestToolUnionTypedDict", + Union[ + OpenResponsesWebSearchPreviewToolTypedDict, + OpenResponsesWebSearchPreview20250311ToolTypedDict, + OpenResponsesWebSearchToolTypedDict, + OpenResponsesWebSearch20250826ToolTypedDict, + OpenResponsesRequestToolFunctionTypedDict, + ], +) + + +OpenResponsesRequestToolUnion = TypeAliasType( + "OpenResponsesRequestToolUnion", + Union[ + OpenResponsesWebSearchPreviewTool, + OpenResponsesWebSearchPreview20250311Tool, + OpenResponsesWebSearchTool, + OpenResponsesWebSearch20250826Tool, + OpenResponsesRequestToolFunction, + ], +) + + +ServiceTier = Union[ + Literal[ + "auto", + "default", + "flex", + "priority", + "scale", + ], + UnrecognizedStr, +] + + +Truncation = Union[ + Literal[ + "auto", + "disabled", + ], + UnrecognizedStr, +] + + +DataCollection = Union[ + Literal[ + "deny", + "allow", + ], + UnrecognizedStr, +] +r"""Data collection setting. If no available model provider meets the requirement, your request will return an error. +- allow: (default) allow providers which store user data non-transiently and may train on it +- deny: use only providers which do not collect user data. + +""" + + +OrderTypedDict = TypeAliasType("OrderTypedDict", Union[ProviderName, str]) + + +Order = TypeAliasType( + "Order", + Union[Annotated[ProviderName, PlainValidator(validate_open_enum(False))], str], +) + + +OnlyTypedDict = TypeAliasType("OnlyTypedDict", Union[ProviderName, str]) + + +Only = TypeAliasType( + "Only", + Union[Annotated[ProviderName, PlainValidator(validate_open_enum(False))], str], +) + + +IgnoreTypedDict = TypeAliasType("IgnoreTypedDict", Union[ProviderName, str]) + + +Ignore = TypeAliasType( + "Ignore", + Union[Annotated[ProviderName, PlainValidator(validate_open_enum(False))], str], +) + + +Sort = Union[ + Literal[ + "price", + "throughput", + "latency", + ], + UnrecognizedStr, +] +r"""The sorting strategy to use for this request, if \"order\" is not specified. When set, no load balancing is performed.""" + + +class MaxPriceTypedDict(TypedDict): + r"""The object specifying the maximum price you want to pay for this request. USD price per million tokens, for prompt and completion.""" + + prompt: NotRequired[Any] + r"""A value in string or number format that is a large number""" + completion: NotRequired[Any] + r"""A value in string or number format that is a large number""" + image: NotRequired[Any] + r"""A value in string or number format that is a large number""" + audio: NotRequired[Any] + r"""A value in string or number format that is a large number""" + request: NotRequired[Any] + r"""A value in string or number format that is a large number""" + + +class MaxPrice(BaseModel): + r"""The object specifying the maximum price you want to pay for this request. USD price per million tokens, for prompt and completion.""" + + prompt: Optional[Any] = None + r"""A value in string or number format that is a large number""" + + completion: Optional[Any] = None + r"""A value in string or number format that is a large number""" + + image: Optional[Any] = None + r"""A value in string or number format that is a large number""" + + audio: Optional[Any] = None + r"""A value in string or number format that is a large number""" + + request: Optional[Any] = None + r"""A value in string or number format that is a large number""" + + +class ProviderTypedDict(TypedDict): + r"""When multiple model providers are available, optionally indicate your routing preference.""" + + allow_fallbacks: NotRequired[Nullable[bool]] + r"""Whether to allow backup providers to serve requests + - true: (default) when the primary provider (or your custom providers in \"order\") is unavailable, use the next best provider. + - false: use only the primary/custom provider, and return the upstream error if it's unavailable. + + """ + require_parameters: NotRequired[Nullable[bool]] + r"""Whether to filter providers to only those that support the parameters you've provided. If this setting is omitted or set to false, then providers will receive only the parameters they support, and ignore the rest.""" + data_collection: NotRequired[Nullable[DataCollection]] + r"""Data collection setting. If no available model provider meets the requirement, your request will return an error. + - allow: (default) allow providers which store user data non-transiently and may train on it + - deny: use only providers which do not collect user data. + + """ + zdr: NotRequired[Nullable[bool]] + r"""Whether to restrict routing to only ZDR (Zero Data Retention) endpoints. When true, only endpoints that do not retain prompts will be used.""" + enforce_distillable_text: NotRequired[Nullable[bool]] + r"""Whether to restrict routing to only models that allow text distillation. When true, only models where the author has allowed distillation will be used.""" + order: NotRequired[Nullable[List[OrderTypedDict]]] + r"""An ordered list of provider slugs. The router will attempt to use the first provider in the subset of this list that supports your requested model, and fall back to the next if it is unavailable. If no providers are available, the request will fail with an error message.""" + only: NotRequired[Nullable[List[OnlyTypedDict]]] + r"""List of provider slugs to allow. If provided, this list is merged with your account-wide allowed provider settings for this request.""" + ignore: NotRequired[Nullable[List[IgnoreTypedDict]]] + r"""List of provider slugs to ignore. If provided, this list is merged with your account-wide ignored provider settings for this request.""" + quantizations: NotRequired[Nullable[List[Quantization]]] + r"""A list of quantization levels to filter the provider by.""" + sort: NotRequired[Nullable[Sort]] + r"""The sorting strategy to use for this request, if \"order\" is not specified. When set, no load balancing is performed.""" + max_price: NotRequired[MaxPriceTypedDict] + r"""The object specifying the maximum price you want to pay for this request. USD price per million tokens, for prompt and completion.""" + + +class Provider(BaseModel): + r"""When multiple model providers are available, optionally indicate your routing preference.""" + + allow_fallbacks: OptionalNullable[bool] = UNSET + r"""Whether to allow backup providers to serve requests + - true: (default) when the primary provider (or your custom providers in \"order\") is unavailable, use the next best provider. + - false: use only the primary/custom provider, and return the upstream error if it's unavailable. + + """ + + require_parameters: OptionalNullable[bool] = UNSET + r"""Whether to filter providers to only those that support the parameters you've provided. If this setting is omitted or set to false, then providers will receive only the parameters they support, and ignore the rest.""" + + data_collection: Annotated[ + OptionalNullable[DataCollection], PlainValidator(validate_open_enum(False)) + ] = UNSET + r"""Data collection setting. If no available model provider meets the requirement, your request will return an error. + - allow: (default) allow providers which store user data non-transiently and may train on it + - deny: use only providers which do not collect user data. + + """ + + zdr: OptionalNullable[bool] = UNSET + r"""Whether to restrict routing to only ZDR (Zero Data Retention) endpoints. When true, only endpoints that do not retain prompts will be used.""" + + enforce_distillable_text: OptionalNullable[bool] = UNSET + r"""Whether to restrict routing to only models that allow text distillation. When true, only models where the author has allowed distillation will be used.""" + + order: OptionalNullable[List[Order]] = UNSET + r"""An ordered list of provider slugs. The router will attempt to use the first provider in the subset of this list that supports your requested model, and fall back to the next if it is unavailable. If no providers are available, the request will fail with an error message.""" + + only: OptionalNullable[List[Only]] = UNSET + r"""List of provider slugs to allow. If provided, this list is merged with your account-wide allowed provider settings for this request.""" + + ignore: OptionalNullable[List[Ignore]] = UNSET + r"""List of provider slugs to ignore. If provided, this list is merged with your account-wide ignored provider settings for this request.""" + + quantizations: OptionalNullable[ + List[Annotated[Quantization, PlainValidator(validate_open_enum(False))]] + ] = UNSET + r"""A list of quantization levels to filter the provider by.""" + + sort: Annotated[ + OptionalNullable[Sort], PlainValidator(validate_open_enum(False)) + ] = UNSET + r"""The sorting strategy to use for this request, if \"order\" is not specified. When set, no load balancing is performed.""" + + max_price: Optional[MaxPrice] = None + r"""The object specifying the maximum price you want to pay for this request. USD price per million tokens, for prompt and completion.""" + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = [ + "allow_fallbacks", + "require_parameters", + "data_collection", + "zdr", + "enforce_distillable_text", + "order", + "only", + "ignore", + "quantizations", + "sort", + "max_price", + ] + nullable_fields = [ + "allow_fallbacks", + "require_parameters", + "data_collection", + "zdr", + "enforce_distillable_text", + "order", + "only", + "ignore", + "quantizations", + "sort", + ] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m + + +IDFileParser = Literal["file-parser",] + + +PdfEngine = Union[ + Literal[ + "mistral-ocr", + "pdf-text", + "native", + ], + UnrecognizedStr, +] + + +class PdfTypedDict(TypedDict): + engine: NotRequired[PdfEngine] + + +class Pdf(BaseModel): + engine: Annotated[ + Optional[PdfEngine], PlainValidator(validate_open_enum(False)) + ] = None + + +class PluginFileParserTypedDict(TypedDict): + id: IDFileParser + max_files: NotRequired[float] + pdf: NotRequired[PdfTypedDict] + + +class PluginFileParser(BaseModel): + id: IDFileParser + + max_files: Optional[float] = None + + pdf: Optional[Pdf] = None + + +IDWeb = Literal["web",] + + +Engine = Union[ + Literal[ + "native", + "exa", + ], + UnrecognizedStr, +] + + +class PluginWebTypedDict(TypedDict): + id: IDWeb + max_results: NotRequired[float] + search_prompt: NotRequired[str] + engine: NotRequired[Engine] + + +class PluginWeb(BaseModel): + id: IDWeb + + max_results: Optional[float] = None + + search_prompt: Optional[str] = None + + engine: Annotated[Optional[Engine], PlainValidator(validate_open_enum(False))] = ( + None + ) + + +IDModeration = Literal["moderation",] + + +class PluginModerationTypedDict(TypedDict): + id: IDModeration + + +class PluginModeration(BaseModel): + id: IDModeration + + +PluginTypedDict = TypeAliasType( + "PluginTypedDict", + Union[PluginModerationTypedDict, PluginFileParserTypedDict, PluginWebTypedDict], +) + + +Plugin = TypeAliasType("Plugin", Union[PluginModeration, PluginFileParser, PluginWeb]) + + +class OpenResponsesRequestTypedDict(TypedDict): + r"""Request schema for Responses endpoint""" + + input: NotRequired[OpenResponsesInputTypedDict] + r"""Input for a response request - can be a string or array of items""" + instructions: NotRequired[Nullable[str]] + metadata: NotRequired[Nullable[Dict[str, str]]] + r"""Metadata key-value pairs for the request. Keys must be ≤64 characters and cannot contain brackets. Values must be ≤512 characters. Maximum 16 pairs allowed.""" + tools: NotRequired[List[OpenResponsesRequestToolUnionTypedDict]] + tool_choice: NotRequired[OpenAIResponsesToolChoiceUnionTypedDict] + parallel_tool_calls: NotRequired[Nullable[bool]] + model: NotRequired[str] + models: NotRequired[List[str]] + text: NotRequired[OpenResponsesResponseTextTypedDict] + r"""Text output configuration including format and verbosity""" + reasoning: NotRequired[Nullable[OpenResponsesReasoningConfigTypedDict]] + r"""Configuration for reasoning mode in the response""" + max_output_tokens: NotRequired[Nullable[float]] + temperature: NotRequired[Nullable[float]] + top_p: NotRequired[Nullable[float]] + top_k: NotRequired[float] + prompt_cache_key: NotRequired[Nullable[str]] + previous_response_id: NotRequired[Nullable[str]] + prompt: NotRequired[Nullable[OpenAIResponsesPromptTypedDict]] + include: NotRequired[Nullable[List[OpenAIResponsesIncludable]]] + background: NotRequired[Nullable[bool]] + safety_identifier: NotRequired[Nullable[str]] + store: NotRequired[Nullable[bool]] + service_tier: NotRequired[Nullable[ServiceTier]] + truncation: NotRequired[Nullable[Truncation]] + stream: NotRequired[bool] + provider: NotRequired[Nullable[ProviderTypedDict]] + r"""When multiple model providers are available, optionally indicate your routing preference.""" + plugins: NotRequired[List[PluginTypedDict]] + r"""Plugins you want to enable for this request, including their settings.""" + user: NotRequired[str] + r"""A unique identifier representing your end-user, which helps distinguish between different users of your app. This allows your app to identify specific users in case of abuse reports, preventing your entire app from being affected by the actions of individual users. Maximum of 128 characters.""" + + +class OpenResponsesRequest(BaseModel): + r"""Request schema for Responses endpoint""" + + input: Optional[OpenResponsesInput] = None + r"""Input for a response request - can be a string or array of items""" + + instructions: OptionalNullable[str] = UNSET + + metadata: OptionalNullable[Dict[str, str]] = UNSET + r"""Metadata key-value pairs for the request. Keys must be ≤64 characters and cannot contain brackets. Values must be ≤512 characters. Maximum 16 pairs allowed.""" + + tools: Optional[List[OpenResponsesRequestToolUnion]] = None + + tool_choice: Optional[OpenAIResponsesToolChoiceUnion] = None + + parallel_tool_calls: OptionalNullable[bool] = UNSET + + model: Optional[str] = None + + models: Optional[List[str]] = None + + text: Optional[OpenResponsesResponseText] = None + r"""Text output configuration including format and verbosity""" + + reasoning: OptionalNullable[OpenResponsesReasoningConfig] = UNSET + r"""Configuration for reasoning mode in the response""" + + max_output_tokens: OptionalNullable[float] = UNSET + + temperature: OptionalNullable[float] = UNSET + + top_p: OptionalNullable[float] = UNSET + + top_k: Optional[float] = None + + prompt_cache_key: OptionalNullable[str] = UNSET + + previous_response_id: OptionalNullable[str] = UNSET + + prompt: OptionalNullable[OpenAIResponsesPrompt] = UNSET + + include: OptionalNullable[ + List[ + Annotated[ + OpenAIResponsesIncludable, PlainValidator(validate_open_enum(False)) + ] + ] + ] = UNSET + + background: OptionalNullable[bool] = UNSET + + safety_identifier: OptionalNullable[str] = UNSET + + store: OptionalNullable[bool] = UNSET + + service_tier: Annotated[ + OptionalNullable[ServiceTier], PlainValidator(validate_open_enum(False)) + ] = UNSET + + truncation: Annotated[ + OptionalNullable[Truncation], PlainValidator(validate_open_enum(False)) + ] = UNSET + + stream: Optional[bool] = False + + provider: OptionalNullable[Provider] = UNSET + r"""When multiple model providers are available, optionally indicate your routing preference.""" + + plugins: Optional[List[Plugin]] = None + r"""Plugins you want to enable for this request, including their settings.""" + + user: Optional[str] = None + r"""A unique identifier representing your end-user, which helps distinguish between different users of your app. This allows your app to identify specific users in case of abuse reports, preventing your entire app from being affected by the actions of individual users. Maximum of 128 characters.""" + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = [ + "input", + "instructions", + "metadata", + "tools", + "tool_choice", + "parallel_tool_calls", + "model", + "models", + "text", + "reasoning", + "max_output_tokens", + "temperature", + "top_p", + "top_k", + "prompt_cache_key", + "previous_response_id", + "prompt", + "include", + "background", + "safety_identifier", + "store", + "service_tier", + "truncation", + "stream", + "provider", + "plugins", + "user", + ] + nullable_fields = [ + "instructions", + "metadata", + "parallel_tool_calls", + "reasoning", + "max_output_tokens", + "temperature", + "top_p", + "prompt_cache_key", + "previous_response_id", + "prompt", + "include", + "background", + "safety_identifier", + "store", + "service_tier", + "truncation", + "provider", + ] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/openresponsesresponsetext.py b/src/openrouter/models/openresponsesresponsetext.py new file mode 100644 index 0000000..c8baa8c --- /dev/null +++ b/src/openrouter/models/openresponsesresponsetext.py @@ -0,0 +1,83 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .responseformattextconfig import ( + ResponseFormatTextConfig, + ResponseFormatTextConfigTypedDict, +) +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, + UnrecognizedStr, +) +from openrouter.utils import validate_open_enum +import pydantic +from pydantic import model_serializer +from pydantic.functional_validators import PlainValidator +from typing import Literal, Optional, Union +from typing_extensions import Annotated, NotRequired, TypedDict + + +OpenResponsesResponseTextVerbosity = Union[ + Literal[ + "high", + "low", + "medium", + ], + UnrecognizedStr, +] + + +class OpenResponsesResponseTextTypedDict(TypedDict): + r"""Text output configuration including format and verbosity""" + + format_: NotRequired[ResponseFormatTextConfigTypedDict] + r"""Text response format configuration""" + verbosity: NotRequired[Nullable[OpenResponsesResponseTextVerbosity]] + + +class OpenResponsesResponseText(BaseModel): + r"""Text output configuration including format and verbosity""" + + format_: Annotated[ + Optional[ResponseFormatTextConfig], pydantic.Field(alias="format") + ] = None + r"""Text response format configuration""" + + verbosity: Annotated[ + OptionalNullable[OpenResponsesResponseTextVerbosity], + PlainValidator(validate_open_enum(False)), + ] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["format", "verbosity"] + nullable_fields = ["verbosity"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/openresponsesstreamevent.py b/src/openrouter/models/openresponsesstreamevent.py new file mode 100644 index 0000000..6e423d8 --- /dev/null +++ b/src/openrouter/models/openresponsesstreamevent.py @@ -0,0 +1,644 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .openairesponsesannotation import ( + OpenAIResponsesAnnotation, + OpenAIResponsesAnnotationTypedDict, +) +from .openairesponsesrefusalcontent import ( + OpenAIResponsesRefusalContent, + OpenAIResponsesRefusalContentTypedDict, +) +from .openresponseserrorevent import ( + OpenResponsesErrorEvent, + OpenResponsesErrorEventTypedDict, +) +from .openresponsesimagegencallcompleted import ( + OpenResponsesImageGenCallCompleted, + OpenResponsesImageGenCallCompletedTypedDict, +) +from .openresponsesimagegencallgenerating import ( + OpenResponsesImageGenCallGenerating, + OpenResponsesImageGenCallGeneratingTypedDict, +) +from .openresponsesimagegencallinprogress import ( + OpenResponsesImageGenCallInProgress, + OpenResponsesImageGenCallInProgressTypedDict, +) +from .openresponsesimagegencallpartialimage import ( + OpenResponsesImageGenCallPartialImage, + OpenResponsesImageGenCallPartialImageTypedDict, +) +from .openresponseslogprobs import OpenResponsesLogProbs, OpenResponsesLogProbsTypedDict +from .openresponsesnonstreamingresponse import ( + OpenResponsesNonStreamingResponse, + OpenResponsesNonStreamingResponseTypedDict, +) +from .openresponsesreasoningdeltaevent import ( + OpenResponsesReasoningDeltaEvent, + OpenResponsesReasoningDeltaEventTypedDict, +) +from .openresponsesreasoningdoneevent import ( + OpenResponsesReasoningDoneEvent, + OpenResponsesReasoningDoneEventTypedDict, +) +from .openresponsesreasoningsummarypartaddedevent import ( + OpenResponsesReasoningSummaryPartAddedEvent, + OpenResponsesReasoningSummaryPartAddedEventTypedDict, +) +from .openresponsesreasoningsummarytextdeltaevent import ( + OpenResponsesReasoningSummaryTextDeltaEvent, + OpenResponsesReasoningSummaryTextDeltaEventTypedDict, +) +from .openresponsesreasoningsummarytextdoneevent import ( + OpenResponsesReasoningSummaryTextDoneEvent, + OpenResponsesReasoningSummaryTextDoneEventTypedDict, +) +from .reasoningsummarytext import ReasoningSummaryText, ReasoningSummaryTextTypedDict +from .reasoningtextcontent import ReasoningTextContent, ReasoningTextContentTypedDict +from .responseoutputtext import ResponseOutputText, ResponseOutputTextTypedDict +from .responsesoutputitem import ResponsesOutputItem, ResponsesOutputItemTypedDict +from openrouter.types import BaseModel +from typing import List, Literal, Union +from typing_extensions import TypeAliasType, TypedDict + + +TypeResponseReasoningSummaryPartDone = Literal["response.reasoning_summary_part.done",] + + +class OpenResponsesStreamEventResponseReasoningSummaryPartDoneTypedDict(TypedDict): + r"""Event emitted when a reasoning summary part is complete""" + + type: TypeResponseReasoningSummaryPartDone + output_index: float + item_id: str + summary_index: float + part: ReasoningSummaryTextTypedDict + sequence_number: float + + +class OpenResponsesStreamEventResponseReasoningSummaryPartDone(BaseModel): + r"""Event emitted when a reasoning summary part is complete""" + + type: TypeResponseReasoningSummaryPartDone + + output_index: float + + item_id: str + + summary_index: float + + part: ReasoningSummaryText + + sequence_number: float + + +TypeResponseFunctionCallArgumentsDone = Literal[ + "response.function_call_arguments.done", +] + + +class OpenResponsesStreamEventResponseFunctionCallArgumentsDoneTypedDict(TypedDict): + r"""Event emitted when function call arguments streaming is complete""" + + type: TypeResponseFunctionCallArgumentsDone + item_id: str + output_index: float + name: str + arguments: str + sequence_number: float + + +class OpenResponsesStreamEventResponseFunctionCallArgumentsDone(BaseModel): + r"""Event emitted when function call arguments streaming is complete""" + + type: TypeResponseFunctionCallArgumentsDone + + item_id: str + + output_index: float + + name: str + + arguments: str + + sequence_number: float + + +TypeResponseFunctionCallArgumentsDelta = Literal[ + "response.function_call_arguments.delta", +] + + +class OpenResponsesStreamEventResponseFunctionCallArgumentsDeltaTypedDict(TypedDict): + r"""Event emitted when function call arguments are being streamed""" + + type: TypeResponseFunctionCallArgumentsDelta + item_id: str + output_index: float + delta: str + sequence_number: float + + +class OpenResponsesStreamEventResponseFunctionCallArgumentsDelta(BaseModel): + r"""Event emitted when function call arguments are being streamed""" + + type: TypeResponseFunctionCallArgumentsDelta + + item_id: str + + output_index: float + + delta: str + + sequence_number: float + + +TypeResponseOutputTextAnnotationAdded = Literal[ + "response.output_text.annotation.added", +] + + +class OpenResponsesStreamEventResponseOutputTextAnnotationAddedTypedDict(TypedDict): + r"""Event emitted when a text annotation is added to output""" + + type: TypeResponseOutputTextAnnotationAdded + output_index: float + item_id: str + content_index: float + sequence_number: float + annotation_index: float + annotation: OpenAIResponsesAnnotationTypedDict + + +class OpenResponsesStreamEventResponseOutputTextAnnotationAdded(BaseModel): + r"""Event emitted when a text annotation is added to output""" + + type: TypeResponseOutputTextAnnotationAdded + + output_index: float + + item_id: str + + content_index: float + + sequence_number: float + + annotation_index: float + + annotation: OpenAIResponsesAnnotation + + +TypeResponseRefusalDone = Literal["response.refusal.done",] + + +class OpenResponsesStreamEventResponseRefusalDoneTypedDict(TypedDict): + r"""Event emitted when refusal streaming is complete""" + + type: TypeResponseRefusalDone + output_index: float + item_id: str + content_index: float + refusal: str + sequence_number: float + + +class OpenResponsesStreamEventResponseRefusalDone(BaseModel): + r"""Event emitted when refusal streaming is complete""" + + type: TypeResponseRefusalDone + + output_index: float + + item_id: str + + content_index: float + + refusal: str + + sequence_number: float + + +TypeResponseRefusalDelta = Literal["response.refusal.delta",] + + +class OpenResponsesStreamEventResponseRefusalDeltaTypedDict(TypedDict): + r"""Event emitted when a refusal delta is streamed""" + + type: TypeResponseRefusalDelta + output_index: float + item_id: str + content_index: float + delta: str + sequence_number: float + + +class OpenResponsesStreamEventResponseRefusalDelta(BaseModel): + r"""Event emitted when a refusal delta is streamed""" + + type: TypeResponseRefusalDelta + + output_index: float + + item_id: str + + content_index: float + + delta: str + + sequence_number: float + + +TypeResponseOutputTextDone = Literal["response.output_text.done",] + + +class OpenResponsesStreamEventResponseOutputTextDoneTypedDict(TypedDict): + r"""Event emitted when text streaming is complete""" + + type: TypeResponseOutputTextDone + output_index: float + item_id: str + content_index: float + text: str + sequence_number: float + logprobs: List[OpenResponsesLogProbsTypedDict] + + +class OpenResponsesStreamEventResponseOutputTextDone(BaseModel): + r"""Event emitted when text streaming is complete""" + + type: TypeResponseOutputTextDone + + output_index: float + + item_id: str + + content_index: float + + text: str + + sequence_number: float + + logprobs: List[OpenResponsesLogProbs] + + +TypeResponseOutputTextDelta = Literal["response.output_text.delta",] + + +class OpenResponsesStreamEventResponseOutputTextDeltaTypedDict(TypedDict): + r"""Event emitted when a text delta is streamed""" + + type: TypeResponseOutputTextDelta + logprobs: List[OpenResponsesLogProbsTypedDict] + output_index: float + item_id: str + content_index: float + delta: str + sequence_number: float + + +class OpenResponsesStreamEventResponseOutputTextDelta(BaseModel): + r"""Event emitted when a text delta is streamed""" + + type: TypeResponseOutputTextDelta + + logprobs: List[OpenResponsesLogProbs] + + output_index: float + + item_id: str + + content_index: float + + delta: str + + sequence_number: float + + +TypeResponseContentPartDone = Literal["response.content_part.done",] + + +Part2TypedDict = TypeAliasType( + "Part2TypedDict", + Union[ + ReasoningTextContentTypedDict, + OpenAIResponsesRefusalContentTypedDict, + ResponseOutputTextTypedDict, + ], +) + + +Part2 = TypeAliasType( + "Part2", + Union[ReasoningTextContent, OpenAIResponsesRefusalContent, ResponseOutputText], +) + + +class OpenResponsesStreamEventResponseContentPartDoneTypedDict(TypedDict): + r"""Event emitted when a content part is complete""" + + type: TypeResponseContentPartDone + output_index: float + item_id: str + content_index: float + part: Part2TypedDict + sequence_number: float + + +class OpenResponsesStreamEventResponseContentPartDone(BaseModel): + r"""Event emitted when a content part is complete""" + + type: TypeResponseContentPartDone + + output_index: float + + item_id: str + + content_index: float + + part: Part2 + + sequence_number: float + + +TypeResponseContentPartAdded = Literal["response.content_part.added",] + + +Part1TypedDict = TypeAliasType( + "Part1TypedDict", + Union[ + ReasoningTextContentTypedDict, + OpenAIResponsesRefusalContentTypedDict, + ResponseOutputTextTypedDict, + ], +) + + +Part1 = TypeAliasType( + "Part1", + Union[ReasoningTextContent, OpenAIResponsesRefusalContent, ResponseOutputText], +) + + +class OpenResponsesStreamEventResponseContentPartAddedTypedDict(TypedDict): + r"""Event emitted when a new content part is added to an output item""" + + type: TypeResponseContentPartAdded + output_index: float + item_id: str + content_index: float + part: Part1TypedDict + sequence_number: float + + +class OpenResponsesStreamEventResponseContentPartAdded(BaseModel): + r"""Event emitted when a new content part is added to an output item""" + + type: TypeResponseContentPartAdded + + output_index: float + + item_id: str + + content_index: float + + part: Part1 + + sequence_number: float + + +TypeResponseOutputItemDone = Literal["response.output_item.done",] + + +class OpenResponsesStreamEventResponseOutputItemDoneTypedDict(TypedDict): + r"""Event emitted when an output item is complete""" + + type: TypeResponseOutputItemDone + output_index: float + item: ResponsesOutputItemTypedDict + r"""An output item from the response""" + sequence_number: float + + +class OpenResponsesStreamEventResponseOutputItemDone(BaseModel): + r"""Event emitted when an output item is complete""" + + type: TypeResponseOutputItemDone + + output_index: float + + item: ResponsesOutputItem + r"""An output item from the response""" + + sequence_number: float + + +TypeResponseOutputItemAdded = Literal["response.output_item.added",] + + +class OpenResponsesStreamEventResponseOutputItemAddedTypedDict(TypedDict): + r"""Event emitted when a new output item is added to the response""" + + type: TypeResponseOutputItemAdded + output_index: float + item: ResponsesOutputItemTypedDict + r"""An output item from the response""" + sequence_number: float + + +class OpenResponsesStreamEventResponseOutputItemAdded(BaseModel): + r"""Event emitted when a new output item is added to the response""" + + type: TypeResponseOutputItemAdded + + output_index: float + + item: ResponsesOutputItem + r"""An output item from the response""" + + sequence_number: float + + +TypeResponseFailed = Literal["response.failed",] + + +class OpenResponsesStreamEventResponseFailedTypedDict(TypedDict): + r"""Event emitted when a response has failed""" + + type: TypeResponseFailed + response: OpenResponsesNonStreamingResponseTypedDict + r"""Complete non-streaming response from the Responses API""" + sequence_number: float + + +class OpenResponsesStreamEventResponseFailed(BaseModel): + r"""Event emitted when a response has failed""" + + type: TypeResponseFailed + + response: OpenResponsesNonStreamingResponse + r"""Complete non-streaming response from the Responses API""" + + sequence_number: float + + +TypeResponseIncomplete = Literal["response.incomplete",] + + +class OpenResponsesStreamEventResponseIncompleteTypedDict(TypedDict): + r"""Event emitted when a response is incomplete""" + + type: TypeResponseIncomplete + response: OpenResponsesNonStreamingResponseTypedDict + r"""Complete non-streaming response from the Responses API""" + sequence_number: float + + +class OpenResponsesStreamEventResponseIncomplete(BaseModel): + r"""Event emitted when a response is incomplete""" + + type: TypeResponseIncomplete + + response: OpenResponsesNonStreamingResponse + r"""Complete non-streaming response from the Responses API""" + + sequence_number: float + + +TypeResponseCompleted = Literal["response.completed",] + + +class OpenResponsesStreamEventResponseCompletedTypedDict(TypedDict): + r"""Event emitted when a response has completed successfully""" + + type: TypeResponseCompleted + response: OpenResponsesNonStreamingResponseTypedDict + r"""Complete non-streaming response from the Responses API""" + sequence_number: float + + +class OpenResponsesStreamEventResponseCompleted(BaseModel): + r"""Event emitted when a response has completed successfully""" + + type: TypeResponseCompleted + + response: OpenResponsesNonStreamingResponse + r"""Complete non-streaming response from the Responses API""" + + sequence_number: float + + +TypeResponseInProgress = Literal["response.in_progress",] + + +class OpenResponsesStreamEventResponseInProgressTypedDict(TypedDict): + r"""Event emitted when a response is in progress""" + + type: TypeResponseInProgress + response: OpenResponsesNonStreamingResponseTypedDict + r"""Complete non-streaming response from the Responses API""" + sequence_number: float + + +class OpenResponsesStreamEventResponseInProgress(BaseModel): + r"""Event emitted when a response is in progress""" + + type: TypeResponseInProgress + + response: OpenResponsesNonStreamingResponse + r"""Complete non-streaming response from the Responses API""" + + sequence_number: float + + +TypeResponseCreated = Literal["response.created",] + + +class OpenResponsesStreamEventResponseCreatedTypedDict(TypedDict): + r"""Event emitted when a response is created""" + + type: TypeResponseCreated + response: OpenResponsesNonStreamingResponseTypedDict + r"""Complete non-streaming response from the Responses API""" + sequence_number: float + + +class OpenResponsesStreamEventResponseCreated(BaseModel): + r"""Event emitted when a response is created""" + + type: TypeResponseCreated + + response: OpenResponsesNonStreamingResponse + r"""Complete non-streaming response from the Responses API""" + + sequence_number: float + + +OpenResponsesStreamEventTypedDict = TypeAliasType( + "OpenResponsesStreamEventTypedDict", + Union[ + OpenResponsesStreamEventResponseCreatedTypedDict, + OpenResponsesStreamEventResponseInProgressTypedDict, + OpenResponsesStreamEventResponseCompletedTypedDict, + OpenResponsesStreamEventResponseIncompleteTypedDict, + OpenResponsesStreamEventResponseFailedTypedDict, + OpenResponsesStreamEventResponseOutputItemAddedTypedDict, + OpenResponsesStreamEventResponseOutputItemDoneTypedDict, + OpenResponsesImageGenCallCompletedTypedDict, + OpenResponsesImageGenCallGeneratingTypedDict, + OpenResponsesImageGenCallInProgressTypedDict, + OpenResponsesErrorEventTypedDict, + OpenResponsesStreamEventResponseFunctionCallArgumentsDeltaTypedDict, + OpenResponsesStreamEventResponseRefusalDeltaTypedDict, + OpenResponsesReasoningSummaryPartAddedEventTypedDict, + OpenResponsesStreamEventResponseContentPartAddedTypedDict, + OpenResponsesImageGenCallPartialImageTypedDict, + OpenResponsesStreamEventResponseFunctionCallArgumentsDoneTypedDict, + OpenResponsesReasoningDeltaEventTypedDict, + OpenResponsesReasoningDoneEventTypedDict, + OpenResponsesStreamEventResponseRefusalDoneTypedDict, + OpenResponsesStreamEventResponseReasoningSummaryPartDoneTypedDict, + OpenResponsesReasoningSummaryTextDeltaEventTypedDict, + OpenResponsesReasoningSummaryTextDoneEventTypedDict, + OpenResponsesStreamEventResponseContentPartDoneTypedDict, + OpenResponsesStreamEventResponseOutputTextDeltaTypedDict, + OpenResponsesStreamEventResponseOutputTextDoneTypedDict, + OpenResponsesStreamEventResponseOutputTextAnnotationAddedTypedDict, + ], +) +r"""Union of all possible event types emitted during response streaming""" + + +OpenResponsesStreamEvent = TypeAliasType( + "OpenResponsesStreamEvent", + Union[ + OpenResponsesStreamEventResponseCreated, + OpenResponsesStreamEventResponseInProgress, + OpenResponsesStreamEventResponseCompleted, + OpenResponsesStreamEventResponseIncomplete, + OpenResponsesStreamEventResponseFailed, + OpenResponsesStreamEventResponseOutputItemAdded, + OpenResponsesStreamEventResponseOutputItemDone, + OpenResponsesImageGenCallCompleted, + OpenResponsesImageGenCallGenerating, + OpenResponsesImageGenCallInProgress, + OpenResponsesErrorEvent, + OpenResponsesStreamEventResponseFunctionCallArgumentsDelta, + OpenResponsesStreamEventResponseRefusalDelta, + OpenResponsesReasoningSummaryPartAddedEvent, + OpenResponsesStreamEventResponseContentPartAdded, + OpenResponsesImageGenCallPartialImage, + OpenResponsesStreamEventResponseFunctionCallArgumentsDone, + OpenResponsesReasoningDeltaEvent, + OpenResponsesReasoningDoneEvent, + OpenResponsesStreamEventResponseRefusalDone, + OpenResponsesStreamEventResponseReasoningSummaryPartDone, + OpenResponsesReasoningSummaryTextDeltaEvent, + OpenResponsesReasoningSummaryTextDoneEvent, + OpenResponsesStreamEventResponseContentPartDone, + OpenResponsesStreamEventResponseOutputTextDelta, + OpenResponsesStreamEventResponseOutputTextDone, + OpenResponsesStreamEventResponseOutputTextAnnotationAdded, + ], +) +r"""Union of all possible event types emitted during response streaming""" diff --git a/src/openrouter/models/openresponsestoplogprobs.py b/src/openrouter/models/openresponsestoplogprobs.py new file mode 100644 index 0000000..5e27a3d --- /dev/null +++ b/src/openrouter/models/openresponsestoplogprobs.py @@ -0,0 +1,21 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel +from typing import Optional +from typing_extensions import NotRequired, TypedDict + + +class OpenResponsesTopLogprobsTypedDict(TypedDict): + r"""Alternative token with its log probability""" + + token: NotRequired[str] + logprob: NotRequired[float] + + +class OpenResponsesTopLogprobs(BaseModel): + r"""Alternative token with its log probability""" + + token: Optional[str] = None + + logprob: Optional[float] = None diff --git a/src/openrouter/models/openresponsesusage.py b/src/openrouter/models/openresponsesusage.py new file mode 100644 index 0000000..084e1c4 --- /dev/null +++ b/src/openrouter/models/openresponsesusage.py @@ -0,0 +1,140 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from pydantic import model_serializer +from typing import Optional +from typing_extensions import NotRequired, TypedDict + + +class InputTokensDetailsTypedDict(TypedDict): + cached_tokens: float + + +class InputTokensDetails(BaseModel): + cached_tokens: float + + +class OutputTokensDetailsTypedDict(TypedDict): + reasoning_tokens: float + + +class OutputTokensDetails(BaseModel): + reasoning_tokens: float + + +class CostDetailsTypedDict(TypedDict): + upstream_inference_input_cost: float + upstream_inference_output_cost: float + upstream_inference_cost: NotRequired[Nullable[float]] + + +class CostDetails(BaseModel): + upstream_inference_input_cost: float + + upstream_inference_output_cost: float + + upstream_inference_cost: OptionalNullable[float] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["upstream_inference_cost"] + nullable_fields = ["upstream_inference_cost"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m + + +class OpenResponsesUsageTypedDict(TypedDict): + r"""Token usage information for the response""" + + input_tokens: float + input_tokens_details: InputTokensDetailsTypedDict + output_tokens: float + output_tokens_details: OutputTokensDetailsTypedDict + total_tokens: float + cost: NotRequired[Nullable[float]] + r"""Cost of the completion""" + is_byok: NotRequired[bool] + r"""Whether a request was made using a Bring Your Own Key configuration""" + cost_details: NotRequired[CostDetailsTypedDict] + + +class OpenResponsesUsage(BaseModel): + r"""Token usage information for the response""" + + input_tokens: float + + input_tokens_details: InputTokensDetails + + output_tokens: float + + output_tokens_details: OutputTokensDetails + + total_tokens: float + + cost: OptionalNullable[float] = UNSET + r"""Cost of the completion""" + + is_byok: Optional[bool] = None + r"""Whether a request was made using a Bring Your Own Key configuration""" + + cost_details: Optional[CostDetails] = None + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["cost", "is_byok", "cost_details"] + nullable_fields = ["cost"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/openresponseswebsearch20250826tool.py b/src/openrouter/models/openresponseswebsearch20250826tool.py new file mode 100644 index 0000000..671afdf --- /dev/null +++ b/src/openrouter/models/openresponseswebsearch20250826tool.py @@ -0,0 +1,118 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .responsessearchcontextsize import ResponsesSearchContextSize +from .responseswebsearchuserlocation import ( + ResponsesWebSearchUserLocation, + ResponsesWebSearchUserLocationTypedDict, +) +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from openrouter.utils import validate_open_enum +from pydantic import model_serializer +from pydantic.functional_validators import PlainValidator +from typing import List, Literal, Optional +from typing_extensions import Annotated, NotRequired, TypedDict + + +OpenResponsesWebSearch20250826ToolType = Literal["web_search_2025_08_26",] + + +class OpenResponsesWebSearch20250826ToolFiltersTypedDict(TypedDict): + allowed_domains: NotRequired[Nullable[List[str]]] + + +class OpenResponsesWebSearch20250826ToolFilters(BaseModel): + allowed_domains: OptionalNullable[List[str]] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["allowed_domains"] + nullable_fields = ["allowed_domains"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m + + +class OpenResponsesWebSearch20250826ToolTypedDict(TypedDict): + r"""Web search tool configuration (2025-08-26 version)""" + + type: OpenResponsesWebSearch20250826ToolType + filters: NotRequired[Nullable[OpenResponsesWebSearch20250826ToolFiltersTypedDict]] + search_context_size: NotRequired[ResponsesSearchContextSize] + r"""Size of the search context for web search tools""" + user_location: NotRequired[Nullable[ResponsesWebSearchUserLocationTypedDict]] + r"""User location information for web search""" + + +class OpenResponsesWebSearch20250826Tool(BaseModel): + r"""Web search tool configuration (2025-08-26 version)""" + + type: OpenResponsesWebSearch20250826ToolType + + filters: OptionalNullable[OpenResponsesWebSearch20250826ToolFilters] = UNSET + + search_context_size: Annotated[ + Optional[ResponsesSearchContextSize], PlainValidator(validate_open_enum(False)) + ] = None + r"""Size of the search context for web search tools""" + + user_location: OptionalNullable[ResponsesWebSearchUserLocation] = UNSET + r"""User location information for web search""" + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["filters", "search_context_size", "user_location"] + nullable_fields = ["filters", "user_location"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/openresponseswebsearchpreview20250311tool.py b/src/openrouter/models/openresponseswebsearchpreview20250311tool.py new file mode 100644 index 0000000..38803d8 --- /dev/null +++ b/src/openrouter/models/openresponseswebsearchpreview20250311tool.py @@ -0,0 +1,77 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .responsessearchcontextsize import ResponsesSearchContextSize +from .websearchpreviewtooluserlocation import ( + WebSearchPreviewToolUserLocation, + WebSearchPreviewToolUserLocationTypedDict, +) +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from openrouter.utils import validate_open_enum +from pydantic import model_serializer +from pydantic.functional_validators import PlainValidator +from typing import Literal, Optional +from typing_extensions import Annotated, NotRequired, TypedDict + + +OpenResponsesWebSearchPreview20250311ToolType = Literal[ + "web_search_preview_2025_03_11", +] + + +class OpenResponsesWebSearchPreview20250311ToolTypedDict(TypedDict): + r"""Web search preview tool configuration (2025-03-11 version)""" + + type: OpenResponsesWebSearchPreview20250311ToolType + search_context_size: NotRequired[ResponsesSearchContextSize] + r"""Size of the search context for web search tools""" + user_location: NotRequired[Nullable[WebSearchPreviewToolUserLocationTypedDict]] + + +class OpenResponsesWebSearchPreview20250311Tool(BaseModel): + r"""Web search preview tool configuration (2025-03-11 version)""" + + type: OpenResponsesWebSearchPreview20250311ToolType + + search_context_size: Annotated[ + Optional[ResponsesSearchContextSize], PlainValidator(validate_open_enum(False)) + ] = None + r"""Size of the search context for web search tools""" + + user_location: OptionalNullable[WebSearchPreviewToolUserLocation] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["search_context_size", "user_location"] + nullable_fields = ["user_location"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/openresponseswebsearchpreviewtool.py b/src/openrouter/models/openresponseswebsearchpreviewtool.py new file mode 100644 index 0000000..2c074cd --- /dev/null +++ b/src/openrouter/models/openresponseswebsearchpreviewtool.py @@ -0,0 +1,75 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .responsessearchcontextsize import ResponsesSearchContextSize +from .websearchpreviewtooluserlocation import ( + WebSearchPreviewToolUserLocation, + WebSearchPreviewToolUserLocationTypedDict, +) +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from openrouter.utils import validate_open_enum +from pydantic import model_serializer +from pydantic.functional_validators import PlainValidator +from typing import Literal, Optional +from typing_extensions import Annotated, NotRequired, TypedDict + + +OpenResponsesWebSearchPreviewToolType = Literal["web_search_preview",] + + +class OpenResponsesWebSearchPreviewToolTypedDict(TypedDict): + r"""Web search preview tool configuration""" + + type: OpenResponsesWebSearchPreviewToolType + search_context_size: NotRequired[ResponsesSearchContextSize] + r"""Size of the search context for web search tools""" + user_location: NotRequired[Nullable[WebSearchPreviewToolUserLocationTypedDict]] + + +class OpenResponsesWebSearchPreviewTool(BaseModel): + r"""Web search preview tool configuration""" + + type: OpenResponsesWebSearchPreviewToolType + + search_context_size: Annotated[ + Optional[ResponsesSearchContextSize], PlainValidator(validate_open_enum(False)) + ] = None + r"""Size of the search context for web search tools""" + + user_location: OptionalNullable[WebSearchPreviewToolUserLocation] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["search_context_size", "user_location"] + nullable_fields = ["user_location"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/openresponseswebsearchtool.py b/src/openrouter/models/openresponseswebsearchtool.py new file mode 100644 index 0000000..0c93a22 --- /dev/null +++ b/src/openrouter/models/openresponseswebsearchtool.py @@ -0,0 +1,118 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .responsessearchcontextsize import ResponsesSearchContextSize +from .responseswebsearchuserlocation import ( + ResponsesWebSearchUserLocation, + ResponsesWebSearchUserLocationTypedDict, +) +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from openrouter.utils import validate_open_enum +from pydantic import model_serializer +from pydantic.functional_validators import PlainValidator +from typing import List, Literal, Optional +from typing_extensions import Annotated, NotRequired, TypedDict + + +OpenResponsesWebSearchToolType = Literal["web_search",] + + +class OpenResponsesWebSearchToolFiltersTypedDict(TypedDict): + allowed_domains: NotRequired[Nullable[List[str]]] + + +class OpenResponsesWebSearchToolFilters(BaseModel): + allowed_domains: OptionalNullable[List[str]] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["allowed_domains"] + nullable_fields = ["allowed_domains"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m + + +class OpenResponsesWebSearchToolTypedDict(TypedDict): + r"""Web search tool configuration""" + + type: OpenResponsesWebSearchToolType + filters: NotRequired[Nullable[OpenResponsesWebSearchToolFiltersTypedDict]] + search_context_size: NotRequired[ResponsesSearchContextSize] + r"""Size of the search context for web search tools""" + user_location: NotRequired[Nullable[ResponsesWebSearchUserLocationTypedDict]] + r"""User location information for web search""" + + +class OpenResponsesWebSearchTool(BaseModel): + r"""Web search tool configuration""" + + type: OpenResponsesWebSearchToolType + + filters: OptionalNullable[OpenResponsesWebSearchToolFilters] = UNSET + + search_context_size: Annotated[ + Optional[ResponsesSearchContextSize], PlainValidator(validate_open_enum(False)) + ] = None + r"""Size of the search context for web search tools""" + + user_location: OptionalNullable[ResponsesWebSearchUserLocation] = UNSET + r"""User location information for web search""" + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["filters", "search_context_size", "user_location"] + nullable_fields = ["filters", "user_location"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/outputitemimagegenerationcall.py b/src/openrouter/models/outputitemimagegenerationcall.py new file mode 100644 index 0000000..857deab --- /dev/null +++ b/src/openrouter/models/outputitemimagegenerationcall.py @@ -0,0 +1,60 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .imagegenerationstatus import ImageGenerationStatus +from openrouter.types import BaseModel, Nullable, OptionalNullable, UNSET_SENTINEL +from openrouter.utils import validate_open_enum +from pydantic import model_serializer +from pydantic.functional_validators import PlainValidator +from typing import Literal +from typing_extensions import Annotated, NotRequired, TypedDict + + +OutputItemImageGenerationCallType = Literal["image_generation_call",] + + +class OutputItemImageGenerationCallTypedDict(TypedDict): + type: OutputItemImageGenerationCallType + id: str + status: ImageGenerationStatus + result: NotRequired[Nullable[str]] + + +class OutputItemImageGenerationCall(BaseModel): + type: OutputItemImageGenerationCallType + + id: str + + status: Annotated[ImageGenerationStatus, PlainValidator(validate_open_enum(False))] + + result: OptionalNullable[str] = None + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["result"] + nullable_fields = ["result"] + null_default_fields = ["result"] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/outputmessage.py b/src/openrouter/models/outputmessage.py new file mode 100644 index 0000000..a956778 --- /dev/null +++ b/src/openrouter/models/outputmessage.py @@ -0,0 +1,77 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .openairesponsesrefusalcontent import ( + OpenAIResponsesRefusalContent, + OpenAIResponsesRefusalContentTypedDict, +) +from .responseoutputtext import ResponseOutputText, ResponseOutputTextTypedDict +from openrouter.types import BaseModel +from typing import List, Literal, Optional, Union +from typing_extensions import NotRequired, TypeAliasType, TypedDict + + +OutputMessageRole = Literal["assistant",] + + +OutputMessageType = Literal["message",] + + +OutputMessageStatusInProgress = Literal["in_progress",] + + +OutputMessageStatusIncomplete = Literal["incomplete",] + + +OutputMessageStatusCompleted = Literal["completed",] + + +OutputMessageStatusUnionTypedDict = TypeAliasType( + "OutputMessageStatusUnionTypedDict", + Union[ + OutputMessageStatusCompleted, + OutputMessageStatusIncomplete, + OutputMessageStatusInProgress, + ], +) + + +OutputMessageStatusUnion = TypeAliasType( + "OutputMessageStatusUnion", + Union[ + OutputMessageStatusCompleted, + OutputMessageStatusIncomplete, + OutputMessageStatusInProgress, + ], +) + + +OutputMessageContentTypedDict = TypeAliasType( + "OutputMessageContentTypedDict", + Union[OpenAIResponsesRefusalContentTypedDict, ResponseOutputTextTypedDict], +) + + +OutputMessageContent = TypeAliasType( + "OutputMessageContent", Union[OpenAIResponsesRefusalContent, ResponseOutputText] +) + + +class OutputMessageTypedDict(TypedDict): + id: str + role: OutputMessageRole + type: OutputMessageType + content: List[OutputMessageContentTypedDict] + status: NotRequired[OutputMessageStatusUnionTypedDict] + + +class OutputMessage(BaseModel): + id: str + + role: OutputMessageRole + + type: OutputMessageType + + content: List[OutputMessageContent] + + status: Optional[OutputMessageStatusUnion] = None diff --git a/src/openrouter/models/outputmodality.py b/src/openrouter/models/outputmodality.py new file mode 100644 index 0000000..3dfd169 --- /dev/null +++ b/src/openrouter/models/outputmodality.py @@ -0,0 +1,15 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import UnrecognizedStr +from typing import Literal, Union + + +OutputModality = Union[ + Literal[ + "text", + "image", + "embeddings", + ], + UnrecognizedStr, +] diff --git a/src/openrouter/models/parameter.py b/src/openrouter/models/parameter.py new file mode 100644 index 0000000..ec65bc3 --- /dev/null +++ b/src/openrouter/models/parameter.py @@ -0,0 +1,35 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import UnrecognizedStr +from typing import Literal, Union + + +Parameter = Union[ + Literal[ + "temperature", + "top_p", + "top_k", + "min_p", + "top_a", + "frequency_penalty", + "presence_penalty", + "repetition_penalty", + "max_tokens", + "logit_bias", + "logprobs", + "top_logprobs", + "seed", + "response_format", + "structured_outputs", + "stop", + "tools", + "tool_choice", + "parallel_tool_calls", + "include_reasoning", + "reasoning", + "web_search_options", + "verbosity", + ], + UnrecognizedStr, +] diff --git a/src/openrouter/models/payloadtoolargeresponseerrordata.py b/src/openrouter/models/payloadtoolargeresponseerrordata.py new file mode 100644 index 0000000..ee1a068 --- /dev/null +++ b/src/openrouter/models/payloadtoolargeresponseerrordata.py @@ -0,0 +1,61 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from pydantic import model_serializer +from typing import Any, Dict +from typing_extensions import NotRequired, TypedDict + + +class PayloadTooLargeResponseErrorDataTypedDict(TypedDict): + r"""Error data for PayloadTooLargeResponse""" + + code: int + message: str + metadata: NotRequired[Nullable[Dict[str, Nullable[Any]]]] + + +class PayloadTooLargeResponseErrorData(BaseModel): + r"""Error data for PayloadTooLargeResponse""" + + code: int + + message: str + + metadata: OptionalNullable[Dict[str, Nullable[Any]]] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["metadata"] + nullable_fields = ["metadata"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/paymentrequiredresponseerrordata.py b/src/openrouter/models/paymentrequiredresponseerrordata.py new file mode 100644 index 0000000..83abd1e --- /dev/null +++ b/src/openrouter/models/paymentrequiredresponseerrordata.py @@ -0,0 +1,61 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from pydantic import model_serializer +from typing import Any, Dict +from typing_extensions import NotRequired, TypedDict + + +class PaymentRequiredResponseErrorDataTypedDict(TypedDict): + r"""Error data for PaymentRequiredResponse""" + + code: int + message: str + metadata: NotRequired[Nullable[Dict[str, Nullable[Any]]]] + + +class PaymentRequiredResponseErrorData(BaseModel): + r"""Error data for PaymentRequiredResponse""" + + code: int + + message: str + + metadata: OptionalNullable[Dict[str, Nullable[Any]]] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["metadata"] + nullable_fields = ["metadata"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/perrequestlimits.py b/src/openrouter/models/perrequestlimits.py new file mode 100644 index 0000000..d83c7d1 --- /dev/null +++ b/src/openrouter/models/perrequestlimits.py @@ -0,0 +1,24 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel +from typing_extensions import TypedDict + + +class PerRequestLimitsTypedDict(TypedDict): + r"""Per-request token limits""" + + prompt_tokens: float + r"""Maximum prompt tokens per request""" + completion_tokens: float + r"""Maximum completion tokens per request""" + + +class PerRequestLimits(BaseModel): + r"""Per-request token limits""" + + prompt_tokens: float + r"""Maximum prompt tokens per request""" + + completion_tokens: float + r"""Maximum completion tokens per request""" diff --git a/src/openrouter/models/providername.py b/src/openrouter/models/providername.py new file mode 100644 index 0000000..035e1b1 --- /dev/null +++ b/src/openrouter/models/providername.py @@ -0,0 +1,98 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import UnrecognizedStr +from typing import Literal, Union + + +ProviderName = Union[ + Literal[ + "AnyScale", + "Cent-ML", + "HuggingFace", + "Hyperbolic 2", + "Lepton", + "Lynn 2", + "Lynn", + "Mancer", + "Modal", + "OctoAI", + "Recursal", + "Reflection", + "Replicate", + "SambaNova 2", + "SF Compute", + "Together 2", + "01.AI", + "AI21", + "AionLabs", + "Alibaba", + "Amazon Bedrock", + "Anthropic", + "AtlasCloud", + "Atoma", + "Avian", + "Azure", + "BaseTen", + "Cerebras", + "Chutes", + "Cirrascale", + "Clarifai", + "Cloudflare", + "Cohere", + "CrofAI", + "Crusoe", + "DeepInfra", + "DeepSeek", + "Enfer", + "Featherless", + "Fireworks", + "Friendli", + "GMICloud", + "Google", + "Google AI Studio", + "Groq", + "Hyperbolic", + "Inception", + "InferenceNet", + "Infermatic", + "Inflection", + "InoCloud", + "Kluster", + "Lambda", + "Liquid", + "Mancer 2", + "Meta", + "Minimax", + "ModelRun", + "Mistral", + "Modular", + "Moonshot AI", + "Morph", + "NCompass", + "Nebius", + "NextBit", + "Nineteen", + "Novita", + "Nvidia", + "OpenAI", + "OpenInference", + "Parasail", + "Perplexity", + "Phala", + "Relace", + "SambaNova", + "SiliconFlow", + "Stealth", + "Switchpoint", + "Targon", + "Together", + "Ubicloud", + "Venice", + "WandB", + "xAI", + "Z.AI", + "FakeProvider", + ], + UnrecognizedStr, +] diff --git a/src/openrouter/models/provideroverloadedresponseerrordata.py b/src/openrouter/models/provideroverloadedresponseerrordata.py new file mode 100644 index 0000000..f3d7756 --- /dev/null +++ b/src/openrouter/models/provideroverloadedresponseerrordata.py @@ -0,0 +1,61 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from pydantic import model_serializer +from typing import Any, Dict +from typing_extensions import NotRequired, TypedDict + + +class ProviderOverloadedResponseErrorDataTypedDict(TypedDict): + r"""Error data for ProviderOverloadedResponse""" + + code: int + message: str + metadata: NotRequired[Nullable[Dict[str, Nullable[Any]]]] + + +class ProviderOverloadedResponseErrorData(BaseModel): + r"""Error data for ProviderOverloadedResponse""" + + code: int + + message: str + + metadata: OptionalNullable[Dict[str, Nullable[Any]]] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["metadata"] + nullable_fields = ["metadata"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/publicendpoint.py b/src/openrouter/models/publicendpoint.py new file mode 100644 index 0000000..da47f2f --- /dev/null +++ b/src/openrouter/models/publicendpoint.py @@ -0,0 +1,180 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .endpointstatus import EndpointStatus +from .parameter import Parameter +from .providername import ProviderName +from openrouter.types import BaseModel, Nullable, UNSET_SENTINEL, UnrecognizedStr +from openrouter.utils import validate_open_enum +from pydantic import model_serializer +from pydantic.functional_validators import PlainValidator +from typing import Any, List, Literal, Optional, Union +from typing_extensions import Annotated, NotRequired, TypedDict + + +class PricingTypedDict(TypedDict): + prompt: Any + r"""A value in string or number format that is a large number""" + completion: Any + r"""A value in string or number format that is a large number""" + request: NotRequired[Any] + r"""A value in string or number format that is a large number""" + image: NotRequired[Any] + r"""A value in string or number format that is a large number""" + image_output: NotRequired[Any] + r"""A value in string or number format that is a large number""" + audio: NotRequired[Any] + r"""A value in string or number format that is a large number""" + input_audio_cache: NotRequired[Any] + r"""A value in string or number format that is a large number""" + web_search: NotRequired[Any] + r"""A value in string or number format that is a large number""" + internal_reasoning: NotRequired[Any] + r"""A value in string or number format that is a large number""" + input_cache_read: NotRequired[Any] + r"""A value in string or number format that is a large number""" + input_cache_write: NotRequired[Any] + r"""A value in string or number format that is a large number""" + discount: NotRequired[float] + + +class Pricing(BaseModel): + prompt: Any + r"""A value in string or number format that is a large number""" + + completion: Any + r"""A value in string or number format that is a large number""" + + request: Optional[Any] = None + r"""A value in string or number format that is a large number""" + + image: Optional[Any] = None + r"""A value in string or number format that is a large number""" + + image_output: Optional[Any] = None + r"""A value in string or number format that is a large number""" + + audio: Optional[Any] = None + r"""A value in string or number format that is a large number""" + + input_audio_cache: Optional[Any] = None + r"""A value in string or number format that is a large number""" + + web_search: Optional[Any] = None + r"""A value in string or number format that is a large number""" + + internal_reasoning: Optional[Any] = None + r"""A value in string or number format that is a large number""" + + input_cache_read: Optional[Any] = None + r"""A value in string or number format that is a large number""" + + input_cache_write: Optional[Any] = None + r"""A value in string or number format that is a large number""" + + discount: Optional[float] = None + + +PublicEndpointQuantization = Union[ + Literal[ + "int4", + "int8", + "fp4", + "fp6", + "fp8", + "fp16", + "bf16", + "fp32", + "unknown", + ], + UnrecognizedStr, +] + + +class PublicEndpointTypedDict(TypedDict): + r"""Information about a specific model endpoint""" + + name: str + model_name: str + context_length: float + pricing: PricingTypedDict + provider_name: ProviderName + tag: str + quantization: Nullable[PublicEndpointQuantization] + max_completion_tokens: Nullable[float] + max_prompt_tokens: Nullable[float] + supported_parameters: List[Parameter] + uptime_last_30m: Nullable[float] + supports_implicit_caching: bool + status: NotRequired[EndpointStatus] + + +class PublicEndpoint(BaseModel): + r"""Information about a specific model endpoint""" + + name: str + + model_name: str + + context_length: float + + pricing: Pricing + + provider_name: Annotated[ProviderName, PlainValidator(validate_open_enum(False))] + + tag: str + + quantization: Annotated[ + Nullable[PublicEndpointQuantization], PlainValidator(validate_open_enum(False)) + ] + + max_completion_tokens: Nullable[float] + + max_prompt_tokens: Nullable[float] + + supported_parameters: List[ + Annotated[Parameter, PlainValidator(validate_open_enum(False))] + ] + + uptime_last_30m: Nullable[float] + + supports_implicit_caching: bool + + status: Annotated[ + Optional[EndpointStatus], PlainValidator(validate_open_enum(True)) + ] = None + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["status"] + nullable_fields = [ + "quantization", + "max_completion_tokens", + "max_prompt_tokens", + "uptime_last_30m", + ] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/publicpricing.py b/src/openrouter/models/publicpricing.py new file mode 100644 index 0000000..23a48d8 --- /dev/null +++ b/src/openrouter/models/publicpricing.py @@ -0,0 +1,73 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel +from typing import Any, Optional +from typing_extensions import NotRequired, TypedDict + + +class PublicPricingTypedDict(TypedDict): + r"""Pricing information for the model""" + + prompt: Any + r"""A value in string or number format that is a large number""" + completion: Any + r"""A value in string or number format that is a large number""" + request: NotRequired[Any] + r"""A value in string or number format that is a large number""" + image: NotRequired[Any] + r"""A value in string or number format that is a large number""" + image_output: NotRequired[Any] + r"""A value in string or number format that is a large number""" + audio: NotRequired[Any] + r"""A value in string or number format that is a large number""" + input_audio_cache: NotRequired[Any] + r"""A value in string or number format that is a large number""" + web_search: NotRequired[Any] + r"""A value in string or number format that is a large number""" + internal_reasoning: NotRequired[Any] + r"""A value in string or number format that is a large number""" + input_cache_read: NotRequired[Any] + r"""A value in string or number format that is a large number""" + input_cache_write: NotRequired[Any] + r"""A value in string or number format that is a large number""" + discount: NotRequired[float] + + +class PublicPricing(BaseModel): + r"""Pricing information for the model""" + + prompt: Any + r"""A value in string or number format that is a large number""" + + completion: Any + r"""A value in string or number format that is a large number""" + + request: Optional[Any] = None + r"""A value in string or number format that is a large number""" + + image: Optional[Any] = None + r"""A value in string or number format that is a large number""" + + image_output: Optional[Any] = None + r"""A value in string or number format that is a large number""" + + audio: Optional[Any] = None + r"""A value in string or number format that is a large number""" + + input_audio_cache: Optional[Any] = None + r"""A value in string or number format that is a large number""" + + web_search: Optional[Any] = None + r"""A value in string or number format that is a large number""" + + internal_reasoning: Optional[Any] = None + r"""A value in string or number format that is a large number""" + + input_cache_read: Optional[Any] = None + r"""A value in string or number format that is a large number""" + + input_cache_write: Optional[Any] = None + r"""A value in string or number format that is a large number""" + + discount: Optional[float] = None diff --git a/src/openrouter/models/quantization.py b/src/openrouter/models/quantization.py new file mode 100644 index 0000000..dfcecaf --- /dev/null +++ b/src/openrouter/models/quantization.py @@ -0,0 +1,21 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import UnrecognizedStr +from typing import Literal, Union + + +Quantization = Union[ + Literal[ + "int4", + "int8", + "fp4", + "fp6", + "fp8", + "fp16", + "bf16", + "fp32", + "unknown", + ], + UnrecognizedStr, +] diff --git a/src/openrouter/models/reasoningsummarytext.py b/src/openrouter/models/reasoningsummarytext.py new file mode 100644 index 0000000..55e368f --- /dev/null +++ b/src/openrouter/models/reasoningsummarytext.py @@ -0,0 +1,20 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel +from typing import Literal +from typing_extensions import TypedDict + + +ReasoningSummaryTextType = Literal["summary_text",] + + +class ReasoningSummaryTextTypedDict(TypedDict): + type: ReasoningSummaryTextType + text: str + + +class ReasoningSummaryText(BaseModel): + type: ReasoningSummaryTextType + + text: str diff --git a/src/openrouter/models/reasoningsummaryverbosity.py b/src/openrouter/models/reasoningsummaryverbosity.py new file mode 100644 index 0000000..6ed1f76 --- /dev/null +++ b/src/openrouter/models/reasoningsummaryverbosity.py @@ -0,0 +1,15 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import UnrecognizedStr +from typing import Literal, Union + + +ReasoningSummaryVerbosity = Union[ + Literal[ + "auto", + "concise", + "detailed", + ], + UnrecognizedStr, +] diff --git a/src/openrouter/models/reasoningtextcontent.py b/src/openrouter/models/reasoningtextcontent.py new file mode 100644 index 0000000..ecac43e --- /dev/null +++ b/src/openrouter/models/reasoningtextcontent.py @@ -0,0 +1,20 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel +from typing import Literal +from typing_extensions import TypedDict + + +ReasoningTextContentType = Literal["reasoning_text",] + + +class ReasoningTextContentTypedDict(TypedDict): + type: ReasoningTextContentType + text: str + + +class ReasoningTextContent(BaseModel): + type: ReasoningTextContentType + + text: str diff --git a/src/openrouter/models/requesttimeoutresponseerrordata.py b/src/openrouter/models/requesttimeoutresponseerrordata.py new file mode 100644 index 0000000..50be74a --- /dev/null +++ b/src/openrouter/models/requesttimeoutresponseerrordata.py @@ -0,0 +1,61 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from pydantic import model_serializer +from typing import Any, Dict +from typing_extensions import NotRequired, TypedDict + + +class RequestTimeoutResponseErrorDataTypedDict(TypedDict): + r"""Error data for RequestTimeoutResponse""" + + code: int + message: str + metadata: NotRequired[Nullable[Dict[str, Nullable[Any]]]] + + +class RequestTimeoutResponseErrorData(BaseModel): + r"""Error data for RequestTimeoutResponse""" + + code: int + + message: str + + metadata: OptionalNullable[Dict[str, Nullable[Any]]] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["metadata"] + nullable_fields = ["metadata"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/responseformatjsonschema.py b/src/openrouter/models/responseformatjsonschema.py new file mode 100644 index 0000000..efe2a2f --- /dev/null +++ b/src/openrouter/models/responseformatjsonschema.py @@ -0,0 +1,26 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .jsonschemaconfig import JSONSchemaConfig, JSONSchemaConfigTypedDict +from openrouter.types import BaseModel +from openrouter.utils import validate_const +import pydantic +from pydantic.functional_validators import AfterValidator +from typing import Literal +from typing_extensions import Annotated, TypedDict + + +class ResponseFormatJSONSchemaTypedDict(TypedDict): + json_schema: JSONSchemaConfigTypedDict + type: Literal["json_schema"] + + +class ResponseFormatJSONSchema(BaseModel): + json_schema: JSONSchemaConfig + + TYPE: Annotated[ + Annotated[ + Literal["json_schema"], AfterValidator(validate_const("json_schema")) + ], + pydantic.Field(alias="type"), + ] = "json_schema" diff --git a/src/openrouter/models/responseformattextconfig.py b/src/openrouter/models/responseformattextconfig.py new file mode 100644 index 0000000..7478c80 --- /dev/null +++ b/src/openrouter/models/responseformattextconfig.py @@ -0,0 +1,36 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .responsesformatjsonobject import ( + ResponsesFormatJSONObject, + ResponsesFormatJSONObjectTypedDict, +) +from .responsesformattext import ResponsesFormatText, ResponsesFormatTextTypedDict +from .responsesformattextjsonschemaconfig import ( + ResponsesFormatTextJSONSchemaConfig, + ResponsesFormatTextJSONSchemaConfigTypedDict, +) +from typing import Union +from typing_extensions import TypeAliasType + + +ResponseFormatTextConfigTypedDict = TypeAliasType( + "ResponseFormatTextConfigTypedDict", + Union[ + ResponsesFormatTextTypedDict, + ResponsesFormatJSONObjectTypedDict, + ResponsesFormatTextJSONSchemaConfigTypedDict, + ], +) +r"""Text response format configuration""" + + +ResponseFormatTextConfig = TypeAliasType( + "ResponseFormatTextConfig", + Union[ + ResponsesFormatText, + ResponsesFormatJSONObject, + ResponsesFormatTextJSONSchemaConfig, + ], +) +r"""Text response format configuration""" diff --git a/src/openrouter/models/responseformattextgrammar.py b/src/openrouter/models/responseformattextgrammar.py new file mode 100644 index 0000000..446c6ec --- /dev/null +++ b/src/openrouter/models/responseformattextgrammar.py @@ -0,0 +1,23 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel +from openrouter.utils import validate_const +import pydantic +from pydantic.functional_validators import AfterValidator +from typing import Literal +from typing_extensions import Annotated, TypedDict + + +class ResponseFormatTextGrammarTypedDict(TypedDict): + grammar: str + type: Literal["grammar"] + + +class ResponseFormatTextGrammar(BaseModel): + grammar: str + + TYPE: Annotated[ + Annotated[Literal["grammar"], AfterValidator(validate_const("grammar"))], + pydantic.Field(alias="type"), + ] = "grammar" diff --git a/src/openrouter/models/responseinputaudio.py b/src/openrouter/models/responseinputaudio.py new file mode 100644 index 0000000..3d375e3 --- /dev/null +++ b/src/openrouter/models/responseinputaudio.py @@ -0,0 +1,50 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel, UnrecognizedStr +from openrouter.utils import validate_open_enum +import pydantic +from pydantic.functional_validators import PlainValidator +from typing import Literal, Union +from typing_extensions import Annotated, TypedDict + + +ResponseInputAudioType = Literal["input_audio",] + + +ResponseInputAudioFormat = Union[ + Literal[ + "mp3", + "wav", + ], + UnrecognizedStr, +] + + +class ResponseInputAudioInputAudioTypedDict(TypedDict): + data: str + format_: ResponseInputAudioFormat + + +class ResponseInputAudioInputAudio(BaseModel): + data: str + + format_: Annotated[ + Annotated[ResponseInputAudioFormat, PlainValidator(validate_open_enum(False))], + pydantic.Field(alias="format"), + ] + + +class ResponseInputAudioTypedDict(TypedDict): + r"""Audio input content item""" + + type: ResponseInputAudioType + input_audio: ResponseInputAudioInputAudioTypedDict + + +class ResponseInputAudio(BaseModel): + r"""Audio input content item""" + + type: ResponseInputAudioType + + input_audio: ResponseInputAudioInputAudio diff --git a/src/openrouter/models/responseinputfile.py b/src/openrouter/models/responseinputfile.py new file mode 100644 index 0000000..54d94bd --- /dev/null +++ b/src/openrouter/models/responseinputfile.py @@ -0,0 +1,70 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from pydantic import model_serializer +from typing import Literal, Optional +from typing_extensions import NotRequired, TypedDict + + +ResponseInputFileType = Literal["input_file",] + + +class ResponseInputFileTypedDict(TypedDict): + r"""File input content item""" + + type: ResponseInputFileType + file_id: NotRequired[Nullable[str]] + file_data: NotRequired[str] + filename: NotRequired[str] + file_url: NotRequired[str] + + +class ResponseInputFile(BaseModel): + r"""File input content item""" + + type: ResponseInputFileType + + file_id: OptionalNullable[str] = UNSET + + file_data: Optional[str] = None + + filename: Optional[str] = None + + file_url: Optional[str] = None + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["file_id", "file_data", "filename", "file_url"] + nullable_fields = ["file_id"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/responseinputimage.py b/src/openrouter/models/responseinputimage.py new file mode 100644 index 0000000..d2cbfed --- /dev/null +++ b/src/openrouter/models/responseinputimage.py @@ -0,0 +1,79 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, + UnrecognizedStr, +) +from openrouter.utils import validate_open_enum +from pydantic import model_serializer +from pydantic.functional_validators import PlainValidator +from typing import Literal, Union +from typing_extensions import Annotated, NotRequired, TypedDict + + +ResponseInputImageType = Literal["input_image",] + + +ResponseInputImageDetail = Union[ + Literal[ + "auto", + "high", + "low", + ], + UnrecognizedStr, +] + + +class ResponseInputImageTypedDict(TypedDict): + r"""Image input content item""" + + type: ResponseInputImageType + detail: ResponseInputImageDetail + image_url: NotRequired[Nullable[str]] + + +class ResponseInputImage(BaseModel): + r"""Image input content item""" + + type: ResponseInputImageType + + detail: Annotated[ + ResponseInputImageDetail, PlainValidator(validate_open_enum(False)) + ] + + image_url: OptionalNullable[str] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["image_url"] + nullable_fields = ["image_url"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/responseinputtext.py b/src/openrouter/models/responseinputtext.py new file mode 100644 index 0000000..0e643e5 --- /dev/null +++ b/src/openrouter/models/responseinputtext.py @@ -0,0 +1,24 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel +from typing import Literal +from typing_extensions import TypedDict + + +ResponseInputTextType = Literal["input_text",] + + +class ResponseInputTextTypedDict(TypedDict): + r"""Text input content item""" + + type: ResponseInputTextType + text: str + + +class ResponseInputText(BaseModel): + r"""Text input content item""" + + type: ResponseInputTextType + + text: str diff --git a/src/openrouter/models/responseoutputtext.py b/src/openrouter/models/responseoutputtext.py new file mode 100644 index 0000000..b2b88e0 --- /dev/null +++ b/src/openrouter/models/responseoutputtext.py @@ -0,0 +1,27 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .openairesponsesannotation import ( + OpenAIResponsesAnnotation, + OpenAIResponsesAnnotationTypedDict, +) +from openrouter.types import BaseModel +from typing import List, Literal, Optional +from typing_extensions import NotRequired, TypedDict + + +ResponseOutputTextType = Literal["output_text",] + + +class ResponseOutputTextTypedDict(TypedDict): + type: ResponseOutputTextType + text: str + annotations: NotRequired[List[OpenAIResponsesAnnotationTypedDict]] + + +class ResponseOutputText(BaseModel): + type: ResponseOutputTextType + + text: str + + annotations: Optional[List[OpenAIResponsesAnnotation]] = None diff --git a/src/openrouter/models/responseserrorfield.py b/src/openrouter/models/responseserrorfield.py new file mode 100644 index 0000000..d38e923 --- /dev/null +++ b/src/openrouter/models/responseserrorfield.py @@ -0,0 +1,48 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel, UnrecognizedStr +from openrouter.utils import validate_open_enum +from pydantic.functional_validators import PlainValidator +from typing import Literal, Union +from typing_extensions import Annotated, TypedDict + + +CodeEnum = Union[ + Literal[ + "server_error", + "rate_limit_exceeded", + "invalid_prompt", + "vector_store_timeout", + "invalid_image", + "invalid_image_format", + "invalid_base64_image", + "invalid_image_url", + "image_too_large", + "image_too_small", + "image_parse_error", + "image_content_policy_violation", + "invalid_image_mode", + "image_file_too_large", + "unsupported_image_media_type", + "empty_image_file", + "failed_to_download_image", + "image_file_not_found", + ], + UnrecognizedStr, +] + + +class ResponsesErrorFieldTypedDict(TypedDict): + r"""Error information returned from the API""" + + code: CodeEnum + message: str + + +class ResponsesErrorField(BaseModel): + r"""Error information returned from the API""" + + code: Annotated[CodeEnum, PlainValidator(validate_open_enum(False))] + + message: str diff --git a/src/openrouter/models/responsesformatjsonobject.py b/src/openrouter/models/responsesformatjsonobject.py new file mode 100644 index 0000000..e6080b5 --- /dev/null +++ b/src/openrouter/models/responsesformatjsonobject.py @@ -0,0 +1,21 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel +from typing import Literal +from typing_extensions import TypedDict + + +ResponsesFormatJSONObjectType = Literal["json_object",] + + +class ResponsesFormatJSONObjectTypedDict(TypedDict): + r"""JSON object response format""" + + type: ResponsesFormatJSONObjectType + + +class ResponsesFormatJSONObject(BaseModel): + r"""JSON object response format""" + + type: ResponsesFormatJSONObjectType diff --git a/src/openrouter/models/responsesformattext.py b/src/openrouter/models/responsesformattext.py new file mode 100644 index 0000000..ac1382e --- /dev/null +++ b/src/openrouter/models/responsesformattext.py @@ -0,0 +1,21 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel +from typing import Literal +from typing_extensions import TypedDict + + +ResponsesFormatTextType = Literal["text",] + + +class ResponsesFormatTextTypedDict(TypedDict): + r"""Plain text response format""" + + type: ResponsesFormatTextType + + +class ResponsesFormatText(BaseModel): + r"""Plain text response format""" + + type: ResponsesFormatTextType diff --git a/src/openrouter/models/responsesformattextjsonschemaconfig.py b/src/openrouter/models/responsesformattextjsonschemaconfig.py new file mode 100644 index 0000000..d1e2aa2 --- /dev/null +++ b/src/openrouter/models/responsesformattextjsonschemaconfig.py @@ -0,0 +1,71 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +import pydantic +from pydantic import model_serializer +from typing import Any, Dict, Literal, Optional +from typing_extensions import Annotated, NotRequired, TypedDict + + +ResponsesFormatTextJSONSchemaConfigType = Literal["json_schema",] + + +class ResponsesFormatTextJSONSchemaConfigTypedDict(TypedDict): + r"""JSON schema constrained response format""" + + type: ResponsesFormatTextJSONSchemaConfigType + name: str + schema_: Dict[str, Nullable[Any]] + description: NotRequired[str] + strict: NotRequired[Nullable[bool]] + + +class ResponsesFormatTextJSONSchemaConfig(BaseModel): + r"""JSON schema constrained response format""" + + type: ResponsesFormatTextJSONSchemaConfigType + + name: str + + schema_: Annotated[Dict[str, Nullable[Any]], pydantic.Field(alias="schema")] + + description: Optional[str] = None + + strict: OptionalNullable[bool] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["description", "strict"] + nullable_fields = ["strict"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/responsesimagegenerationcall.py b/src/openrouter/models/responsesimagegenerationcall.py new file mode 100644 index 0000000..f26fefd --- /dev/null +++ b/src/openrouter/models/responsesimagegenerationcall.py @@ -0,0 +1,60 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .imagegenerationstatus import ImageGenerationStatus +from openrouter.types import BaseModel, Nullable, OptionalNullable, UNSET_SENTINEL +from openrouter.utils import validate_open_enum +from pydantic import model_serializer +from pydantic.functional_validators import PlainValidator +from typing import Literal +from typing_extensions import Annotated, NotRequired, TypedDict + + +ResponsesImageGenerationCallType = Literal["image_generation_call",] + + +class ResponsesImageGenerationCallTypedDict(TypedDict): + type: ResponsesImageGenerationCallType + id: str + status: ImageGenerationStatus + result: NotRequired[Nullable[str]] + + +class ResponsesImageGenerationCall(BaseModel): + type: ResponsesImageGenerationCallType + + id: str + + status: Annotated[ImageGenerationStatus, PlainValidator(validate_open_enum(False))] + + result: OptionalNullable[str] = None + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["result"] + nullable_fields = ["result"] + null_default_fields = ["result"] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/responsesoutputitem.py b/src/openrouter/models/responsesoutputitem.py new file mode 100644 index 0000000..63c4023 --- /dev/null +++ b/src/openrouter/models/responsesoutputitem.py @@ -0,0 +1,57 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .responsesimagegenerationcall import ( + ResponsesImageGenerationCall, + ResponsesImageGenerationCallTypedDict, +) +from .responsesoutputitemfilesearchcall import ( + ResponsesOutputItemFileSearchCall, + ResponsesOutputItemFileSearchCallTypedDict, +) +from .responsesoutputitemfunctioncall import ( + ResponsesOutputItemFunctionCall, + ResponsesOutputItemFunctionCallTypedDict, +) +from .responsesoutputitemreasoning import ( + ResponsesOutputItemReasoning, + ResponsesOutputItemReasoningTypedDict, +) +from .responsesoutputmessage import ( + ResponsesOutputMessage, + ResponsesOutputMessageTypedDict, +) +from .responseswebsearchcalloutput import ( + ResponsesWebSearchCallOutput, + ResponsesWebSearchCallOutputTypedDict, +) +from typing import Union +from typing_extensions import TypeAliasType + + +ResponsesOutputItemTypedDict = TypeAliasType( + "ResponsesOutputItemTypedDict", + Union[ + ResponsesWebSearchCallOutputTypedDict, + ResponsesOutputItemFileSearchCallTypedDict, + ResponsesImageGenerationCallTypedDict, + ResponsesOutputMessageTypedDict, + ResponsesOutputItemReasoningTypedDict, + ResponsesOutputItemFunctionCallTypedDict, + ], +) +r"""An output item from the response""" + + +ResponsesOutputItem = TypeAliasType( + "ResponsesOutputItem", + Union[ + ResponsesWebSearchCallOutput, + ResponsesOutputItemFileSearchCall, + ResponsesImageGenerationCall, + ResponsesOutputMessage, + ResponsesOutputItemReasoning, + ResponsesOutputItemFunctionCall, + ], +) +r"""An output item from the response""" diff --git a/src/openrouter/models/responsesoutputitemfilesearchcall.py b/src/openrouter/models/responsesoutputitemfilesearchcall.py new file mode 100644 index 0000000..cdc59cc --- /dev/null +++ b/src/openrouter/models/responsesoutputitemfilesearchcall.py @@ -0,0 +1,29 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .websearchstatus import WebSearchStatus +from openrouter.types import BaseModel +from openrouter.utils import validate_open_enum +from pydantic.functional_validators import PlainValidator +from typing import List, Literal +from typing_extensions import Annotated, TypedDict + + +ResponsesOutputItemFileSearchCallType = Literal["file_search_call",] + + +class ResponsesOutputItemFileSearchCallTypedDict(TypedDict): + type: ResponsesOutputItemFileSearchCallType + id: str + queries: List[str] + status: WebSearchStatus + + +class ResponsesOutputItemFileSearchCall(BaseModel): + type: ResponsesOutputItemFileSearchCallType + + id: str + + queries: List[str] + + status: Annotated[WebSearchStatus, PlainValidator(validate_open_enum(False))] diff --git a/src/openrouter/models/responsesoutputitemfunctioncall.py b/src/openrouter/models/responsesoutputitemfunctioncall.py new file mode 100644 index 0000000..b7d5b06 --- /dev/null +++ b/src/openrouter/models/responsesoutputitemfunctioncall.py @@ -0,0 +1,61 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel +from typing import Literal, Optional, Union +from typing_extensions import NotRequired, TypeAliasType, TypedDict + + +ResponsesOutputItemFunctionCallType = Literal["function_call",] + + +ResponsesOutputItemFunctionCallStatusInProgress = Literal["in_progress",] + + +ResponsesOutputItemFunctionCallStatusIncomplete = Literal["incomplete",] + + +ResponsesOutputItemFunctionCallStatusCompleted = Literal["completed",] + + +ResponsesOutputItemFunctionCallStatusUnionTypedDict = TypeAliasType( + "ResponsesOutputItemFunctionCallStatusUnionTypedDict", + Union[ + ResponsesOutputItemFunctionCallStatusCompleted, + ResponsesOutputItemFunctionCallStatusIncomplete, + ResponsesOutputItemFunctionCallStatusInProgress, + ], +) + + +ResponsesOutputItemFunctionCallStatusUnion = TypeAliasType( + "ResponsesOutputItemFunctionCallStatusUnion", + Union[ + ResponsesOutputItemFunctionCallStatusCompleted, + ResponsesOutputItemFunctionCallStatusIncomplete, + ResponsesOutputItemFunctionCallStatusInProgress, + ], +) + + +class ResponsesOutputItemFunctionCallTypedDict(TypedDict): + type: ResponsesOutputItemFunctionCallType + name: str + arguments: str + call_id: str + id: NotRequired[str] + status: NotRequired[ResponsesOutputItemFunctionCallStatusUnionTypedDict] + + +class ResponsesOutputItemFunctionCall(BaseModel): + type: ResponsesOutputItemFunctionCallType + + name: str + + arguments: str + + call_id: str + + id: Optional[str] = None + + status: Optional[ResponsesOutputItemFunctionCallStatusUnion] = None diff --git a/src/openrouter/models/responsesoutputitemreasoning.py b/src/openrouter/models/responsesoutputitemreasoning.py new file mode 100644 index 0000000..99fe60e --- /dev/null +++ b/src/openrouter/models/responsesoutputitemreasoning.py @@ -0,0 +1,104 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .reasoningsummarytext import ReasoningSummaryText, ReasoningSummaryTextTypedDict +from .reasoningtextcontent import ReasoningTextContent, ReasoningTextContentTypedDict +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from pydantic import model_serializer +from typing import List, Literal, Optional, Union +from typing_extensions import NotRequired, TypeAliasType, TypedDict + + +ResponsesOutputItemReasoningType = Literal["reasoning",] + + +ResponsesOutputItemReasoningStatusInProgress = Literal["in_progress",] + + +ResponsesOutputItemReasoningStatusIncomplete = Literal["incomplete",] + + +ResponsesOutputItemReasoningStatusCompleted = Literal["completed",] + + +ResponsesOutputItemReasoningStatusUnionTypedDict = TypeAliasType( + "ResponsesOutputItemReasoningStatusUnionTypedDict", + Union[ + ResponsesOutputItemReasoningStatusCompleted, + ResponsesOutputItemReasoningStatusIncomplete, + ResponsesOutputItemReasoningStatusInProgress, + ], +) + + +ResponsesOutputItemReasoningStatusUnion = TypeAliasType( + "ResponsesOutputItemReasoningStatusUnion", + Union[ + ResponsesOutputItemReasoningStatusCompleted, + ResponsesOutputItemReasoningStatusIncomplete, + ResponsesOutputItemReasoningStatusInProgress, + ], +) + + +class ResponsesOutputItemReasoningTypedDict(TypedDict): + r"""An output item containing reasoning""" + + type: ResponsesOutputItemReasoningType + id: str + summary: List[ReasoningSummaryTextTypedDict] + content: NotRequired[List[ReasoningTextContentTypedDict]] + encrypted_content: NotRequired[Nullable[str]] + status: NotRequired[ResponsesOutputItemReasoningStatusUnionTypedDict] + + +class ResponsesOutputItemReasoning(BaseModel): + r"""An output item containing reasoning""" + + type: ResponsesOutputItemReasoningType + + id: str + + summary: List[ReasoningSummaryText] + + content: Optional[List[ReasoningTextContent]] = None + + encrypted_content: OptionalNullable[str] = UNSET + + status: Optional[ResponsesOutputItemReasoningStatusUnion] = None + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["content", "encrypted_content", "status"] + nullable_fields = ["encrypted_content"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/responsesoutputmessage.py b/src/openrouter/models/responsesoutputmessage.py new file mode 100644 index 0000000..74126d4 --- /dev/null +++ b/src/openrouter/models/responsesoutputmessage.py @@ -0,0 +1,82 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .openairesponsesrefusalcontent import ( + OpenAIResponsesRefusalContent, + OpenAIResponsesRefusalContentTypedDict, +) +from .responseoutputtext import ResponseOutputText, ResponseOutputTextTypedDict +from openrouter.types import BaseModel +from typing import List, Literal, Optional, Union +from typing_extensions import NotRequired, TypeAliasType, TypedDict + + +ResponsesOutputMessageRole = Literal["assistant",] + + +ResponsesOutputMessageType = Literal["message",] + + +ResponsesOutputMessageStatusInProgress = Literal["in_progress",] + + +ResponsesOutputMessageStatusIncomplete = Literal["incomplete",] + + +ResponsesOutputMessageStatusCompleted = Literal["completed",] + + +ResponsesOutputMessageStatusUnionTypedDict = TypeAliasType( + "ResponsesOutputMessageStatusUnionTypedDict", + Union[ + ResponsesOutputMessageStatusCompleted, + ResponsesOutputMessageStatusIncomplete, + ResponsesOutputMessageStatusInProgress, + ], +) + + +ResponsesOutputMessageStatusUnion = TypeAliasType( + "ResponsesOutputMessageStatusUnion", + Union[ + ResponsesOutputMessageStatusCompleted, + ResponsesOutputMessageStatusIncomplete, + ResponsesOutputMessageStatusInProgress, + ], +) + + +ResponsesOutputMessageContentTypedDict = TypeAliasType( + "ResponsesOutputMessageContentTypedDict", + Union[OpenAIResponsesRefusalContentTypedDict, ResponseOutputTextTypedDict], +) + + +ResponsesOutputMessageContent = TypeAliasType( + "ResponsesOutputMessageContent", + Union[OpenAIResponsesRefusalContent, ResponseOutputText], +) + + +class ResponsesOutputMessageTypedDict(TypedDict): + r"""An output message item""" + + id: str + role: ResponsesOutputMessageRole + type: ResponsesOutputMessageType + content: List[ResponsesOutputMessageContentTypedDict] + status: NotRequired[ResponsesOutputMessageStatusUnionTypedDict] + + +class ResponsesOutputMessage(BaseModel): + r"""An output message item""" + + id: str + + role: ResponsesOutputMessageRole + + type: ResponsesOutputMessageType + + content: List[ResponsesOutputMessageContent] + + status: Optional[ResponsesOutputMessageStatusUnion] = None diff --git a/src/openrouter/models/responsessearchcontextsize.py b/src/openrouter/models/responsessearchcontextsize.py new file mode 100644 index 0000000..3395638 --- /dev/null +++ b/src/openrouter/models/responsessearchcontextsize.py @@ -0,0 +1,16 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import UnrecognizedStr +from typing import Literal, Union + + +ResponsesSearchContextSize = Union[ + Literal[ + "low", + "medium", + "high", + ], + UnrecognizedStr, +] +r"""Size of the search context for web search tools""" diff --git a/src/openrouter/models/responseswebsearchcalloutput.py b/src/openrouter/models/responseswebsearchcalloutput.py new file mode 100644 index 0000000..98621d6 --- /dev/null +++ b/src/openrouter/models/responseswebsearchcalloutput.py @@ -0,0 +1,26 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .websearchstatus import WebSearchStatus +from openrouter.types import BaseModel +from openrouter.utils import validate_open_enum +from pydantic.functional_validators import PlainValidator +from typing import Literal +from typing_extensions import Annotated, TypedDict + + +ResponsesWebSearchCallOutputType = Literal["web_search_call",] + + +class ResponsesWebSearchCallOutputTypedDict(TypedDict): + type: ResponsesWebSearchCallOutputType + id: str + status: WebSearchStatus + + +class ResponsesWebSearchCallOutput(BaseModel): + type: ResponsesWebSearchCallOutputType + + id: str + + status: Annotated[WebSearchStatus, PlainValidator(validate_open_enum(False))] diff --git a/src/openrouter/models/responseswebsearchuserlocation.py b/src/openrouter/models/responseswebsearchuserlocation.py new file mode 100644 index 0000000..707cf15 --- /dev/null +++ b/src/openrouter/models/responseswebsearchuserlocation.py @@ -0,0 +1,70 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from pydantic import model_serializer +from typing import Literal, Optional +from typing_extensions import NotRequired, TypedDict + + +ResponsesWebSearchUserLocationType = Literal["approximate",] + + +class ResponsesWebSearchUserLocationTypedDict(TypedDict): + r"""User location information for web search""" + + type: NotRequired[ResponsesWebSearchUserLocationType] + city: NotRequired[Nullable[str]] + country: NotRequired[Nullable[str]] + region: NotRequired[Nullable[str]] + timezone: NotRequired[Nullable[str]] + + +class ResponsesWebSearchUserLocation(BaseModel): + r"""User location information for web search""" + + type: Optional[ResponsesWebSearchUserLocationType] = None + + city: OptionalNullable[str] = UNSET + + country: OptionalNullable[str] = UNSET + + region: OptionalNullable[str] = UNSET + + timezone: OptionalNullable[str] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["type", "city", "country", "region", "timezone"] + nullable_fields = ["city", "country", "region", "timezone"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/responsetextconfig.py b/src/openrouter/models/responsetextconfig.py new file mode 100644 index 0000000..7b464d3 --- /dev/null +++ b/src/openrouter/models/responsetextconfig.py @@ -0,0 +1,83 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .responseformattextconfig import ( + ResponseFormatTextConfig, + ResponseFormatTextConfigTypedDict, +) +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, + UnrecognizedStr, +) +from openrouter.utils import validate_open_enum +import pydantic +from pydantic import model_serializer +from pydantic.functional_validators import PlainValidator +from typing import Literal, Optional, Union +from typing_extensions import Annotated, NotRequired, TypedDict + + +ResponseTextConfigVerbosity = Union[ + Literal[ + "high", + "low", + "medium", + ], + UnrecognizedStr, +] + + +class ResponseTextConfigTypedDict(TypedDict): + r"""Text output configuration including format and verbosity""" + + format_: NotRequired[ResponseFormatTextConfigTypedDict] + r"""Text response format configuration""" + verbosity: NotRequired[Nullable[ResponseTextConfigVerbosity]] + + +class ResponseTextConfig(BaseModel): + r"""Text output configuration including format and verbosity""" + + format_: Annotated[ + Optional[ResponseFormatTextConfig], pydantic.Field(alias="format") + ] = None + r"""Text response format configuration""" + + verbosity: Annotated[ + OptionalNullable[ResponseTextConfigVerbosity], + PlainValidator(validate_open_enum(False)), + ] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["format", "verbosity"] + nullable_fields = ["verbosity"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/security.py b/src/openrouter/models/security.py new file mode 100644 index 0000000..1870d08 --- /dev/null +++ b/src/openrouter/models/security.py @@ -0,0 +1,25 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel +from openrouter.utils import FieldMetadata, SecurityMetadata +from typing import Optional +from typing_extensions import Annotated, NotRequired, TypedDict + + +class SecurityTypedDict(TypedDict): + api_key: NotRequired[str] + + +class Security(BaseModel): + api_key: Annotated[ + Optional[str], + FieldMetadata( + security=SecurityMetadata( + scheme=True, + scheme_type="http", + sub_type="bearer", + field_name="Authorization", + ) + ), + ] = None diff --git a/src/openrouter/models/sendchatcompletionrequestop.py b/src/openrouter/models/sendchatcompletionrequestop.py new file mode 100644 index 0000000..394376a --- /dev/null +++ b/src/openrouter/models/sendchatcompletionrequestop.py @@ -0,0 +1,35 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .chatresponse import ChatResponse, ChatResponseTypedDict +from .chatstreamingresponsechunk import ( + ChatStreamingResponseChunk, + ChatStreamingResponseChunkTypedDict, +) +from openrouter.utils import eventstreaming +from typing import Union +from typing_extensions import TypeAliasType + + +SendChatCompletionRequestResponseTypedDict = TypeAliasType( + "SendChatCompletionRequestResponseTypedDict", + Union[ + ChatResponseTypedDict, + Union[ + eventstreaming.EventStream[ChatStreamingResponseChunkTypedDict], + eventstreaming.EventStreamAsync[ChatStreamingResponseChunkTypedDict], + ], + ], +) + + +SendChatCompletionRequestResponse = TypeAliasType( + "SendChatCompletionRequestResponse", + Union[ + ChatResponse, + Union[ + eventstreaming.EventStream[ChatStreamingResponseChunk], + eventstreaming.EventStreamAsync[ChatStreamingResponseChunk], + ], + ], +) diff --git a/src/openrouter/models/serviceunavailableresponseerrordata.py b/src/openrouter/models/serviceunavailableresponseerrordata.py new file mode 100644 index 0000000..0b28bb2 --- /dev/null +++ b/src/openrouter/models/serviceunavailableresponseerrordata.py @@ -0,0 +1,61 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from pydantic import model_serializer +from typing import Any, Dict +from typing_extensions import NotRequired, TypedDict + + +class ServiceUnavailableResponseErrorDataTypedDict(TypedDict): + r"""Error data for ServiceUnavailableResponse""" + + code: int + message: str + metadata: NotRequired[Nullable[Dict[str, Nullable[Any]]]] + + +class ServiceUnavailableResponseErrorData(BaseModel): + r"""Error data for ServiceUnavailableResponse""" + + code: int + + message: str + + metadata: OptionalNullable[Dict[str, Nullable[Any]]] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["metadata"] + nullable_fields = ["metadata"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/systemmessage.py b/src/openrouter/models/systemmessage.py new file mode 100644 index 0000000..19b6e67 --- /dev/null +++ b/src/openrouter/models/systemmessage.py @@ -0,0 +1,41 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .chatmessagecontentitemtext import ( + ChatMessageContentItemText, + ChatMessageContentItemTextTypedDict, +) +from openrouter.types import BaseModel +from openrouter.utils import validate_const +import pydantic +from pydantic.functional_validators import AfterValidator +from typing import List, Literal, Optional, Union +from typing_extensions import Annotated, NotRequired, TypeAliasType, TypedDict + + +SystemMessageContentTypedDict = TypeAliasType( + "SystemMessageContentTypedDict", + Union[str, List[ChatMessageContentItemTextTypedDict]], +) + + +SystemMessageContent = TypeAliasType( + "SystemMessageContent", Union[str, List[ChatMessageContentItemText]] +) + + +class SystemMessageTypedDict(TypedDict): + content: SystemMessageContentTypedDict + role: Literal["system"] + name: NotRequired[str] + + +class SystemMessage(BaseModel): + content: SystemMessageContent + + ROLE: Annotated[ + Annotated[Literal["system"], AfterValidator(validate_const("system"))], + pydantic.Field(alias="role"), + ] = "system" + + name: Optional[str] = None diff --git a/src/openrouter/models/toolcallstatus.py b/src/openrouter/models/toolcallstatus.py new file mode 100644 index 0000000..bbd8827 --- /dev/null +++ b/src/openrouter/models/toolcallstatus.py @@ -0,0 +1,15 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import UnrecognizedStr +from typing import Literal, Union + + +ToolCallStatus = Union[ + Literal[ + "in_progress", + "completed", + "incomplete", + ], + UnrecognizedStr, +] diff --git a/src/openrouter/models/tooldefinitionjson.py b/src/openrouter/models/tooldefinitionjson.py new file mode 100644 index 0000000..1dde81b --- /dev/null +++ b/src/openrouter/models/tooldefinitionjson.py @@ -0,0 +1,77 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from openrouter.utils import validate_const +import pydantic +from pydantic import model_serializer +from pydantic.functional_validators import AfterValidator +from typing import Any, Dict, Literal, Optional +from typing_extensions import Annotated, NotRequired, TypedDict + + +class ToolDefinitionJSONFunctionTypedDict(TypedDict): + name: str + description: NotRequired[str] + parameters: NotRequired[Dict[str, Any]] + strict: NotRequired[Nullable[bool]] + + +class ToolDefinitionJSONFunction(BaseModel): + name: str + + description: Optional[str] = None + + parameters: Optional[Dict[str, Any]] = None + + strict: OptionalNullable[bool] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["description", "parameters", "strict"] + nullable_fields = ["strict"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m + + +class ToolDefinitionJSONTypedDict(TypedDict): + function: ToolDefinitionJSONFunctionTypedDict + type: Literal["function"] + + +class ToolDefinitionJSON(BaseModel): + function: ToolDefinitionJSONFunction + + TYPE: Annotated[ + Annotated[Literal["function"], AfterValidator(validate_const("function"))], + pydantic.Field(alias="type"), + ] = "function" diff --git a/src/openrouter/models/toolresponsemessage.py b/src/openrouter/models/toolresponsemessage.py new file mode 100644 index 0000000..666740e --- /dev/null +++ b/src/openrouter/models/toolresponsemessage.py @@ -0,0 +1,41 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .chatmessagecontentitem import ( + ChatMessageContentItem, + ChatMessageContentItemTypedDict, +) +from openrouter.types import BaseModel +from openrouter.utils import validate_const +import pydantic +from pydantic.functional_validators import AfterValidator +from typing import List, Literal, Union +from typing_extensions import Annotated, TypeAliasType, TypedDict + + +ToolResponseMessageContentTypedDict = TypeAliasType( + "ToolResponseMessageContentTypedDict", + Union[str, List[ChatMessageContentItemTypedDict]], +) + + +ToolResponseMessageContent = TypeAliasType( + "ToolResponseMessageContent", Union[str, List[ChatMessageContentItem]] +) + + +class ToolResponseMessageTypedDict(TypedDict): + content: ToolResponseMessageContentTypedDict + tool_call_id: str + role: Literal["tool"] + + +class ToolResponseMessage(BaseModel): + content: ToolResponseMessageContent + + tool_call_id: str + + ROLE: Annotated[ + Annotated[Literal["tool"], AfterValidator(validate_const("tool"))], + pydantic.Field(alias="role"), + ] = "tool" diff --git a/src/openrouter/models/toomanyrequestsresponseerrordata.py b/src/openrouter/models/toomanyrequestsresponseerrordata.py new file mode 100644 index 0000000..19fda10 --- /dev/null +++ b/src/openrouter/models/toomanyrequestsresponseerrordata.py @@ -0,0 +1,61 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from pydantic import model_serializer +from typing import Any, Dict +from typing_extensions import NotRequired, TypedDict + + +class TooManyRequestsResponseErrorDataTypedDict(TypedDict): + r"""Error data for TooManyRequestsResponse""" + + code: int + message: str + metadata: NotRequired[Nullable[Dict[str, Nullable[Any]]]] + + +class TooManyRequestsResponseErrorData(BaseModel): + r"""Error data for TooManyRequestsResponse""" + + code: int + + message: str + + metadata: OptionalNullable[Dict[str, Nullable[Any]]] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["metadata"] + nullable_fields = ["metadata"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/topproviderinfo.py b/src/openrouter/models/topproviderinfo.py new file mode 100644 index 0000000..7912635 --- /dev/null +++ b/src/openrouter/models/topproviderinfo.py @@ -0,0 +1,66 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from pydantic import model_serializer +from typing_extensions import NotRequired, TypedDict + + +class TopProviderInfoTypedDict(TypedDict): + r"""Information about the top provider for this model""" + + is_moderated: bool + r"""Whether the top provider moderates content""" + context_length: NotRequired[Nullable[float]] + r"""Context length from the top provider""" + max_completion_tokens: NotRequired[Nullable[float]] + r"""Maximum completion tokens from the top provider""" + + +class TopProviderInfo(BaseModel): + r"""Information about the top provider for this model""" + + is_moderated: bool + r"""Whether the top provider moderates content""" + + context_length: OptionalNullable[float] = UNSET + r"""Context length from the top provider""" + + max_completion_tokens: OptionalNullable[float] = UNSET + r"""Maximum completion tokens from the top provider""" + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["context_length", "max_completion_tokens"] + nullable_fields = ["context_length", "max_completion_tokens"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/unauthorizedresponseerrordata.py b/src/openrouter/models/unauthorizedresponseerrordata.py new file mode 100644 index 0000000..0fc3c7c --- /dev/null +++ b/src/openrouter/models/unauthorizedresponseerrordata.py @@ -0,0 +1,61 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from pydantic import model_serializer +from typing import Any, Dict +from typing_extensions import NotRequired, TypedDict + + +class UnauthorizedResponseErrorDataTypedDict(TypedDict): + r"""Error data for UnauthorizedResponse""" + + code: int + message: str + metadata: NotRequired[Nullable[Dict[str, Nullable[Any]]]] + + +class UnauthorizedResponseErrorData(BaseModel): + r"""Error data for UnauthorizedResponse""" + + code: int + + message: str + + metadata: OptionalNullable[Dict[str, Nullable[Any]]] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["metadata"] + nullable_fields = ["metadata"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/unprocessableentityresponseerrordata.py b/src/openrouter/models/unprocessableentityresponseerrordata.py new file mode 100644 index 0000000..1c70ab3 --- /dev/null +++ b/src/openrouter/models/unprocessableentityresponseerrordata.py @@ -0,0 +1,61 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from pydantic import model_serializer +from typing import Any, Dict +from typing_extensions import NotRequired, TypedDict + + +class UnprocessableEntityResponseErrorDataTypedDict(TypedDict): + r"""Error data for UnprocessableEntityResponse""" + + code: int + message: str + metadata: NotRequired[Nullable[Dict[str, Nullable[Any]]]] + + +class UnprocessableEntityResponseErrorData(BaseModel): + r"""Error data for UnprocessableEntityResponse""" + + code: int + + message: str + + metadata: OptionalNullable[Dict[str, Nullable[Any]]] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["metadata"] + nullable_fields = ["metadata"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/updatekeysop.py b/src/openrouter/models/updatekeysop.py new file mode 100644 index 0000000..bf3bf90 --- /dev/null +++ b/src/openrouter/models/updatekeysop.py @@ -0,0 +1,274 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from datetime import datetime +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, + UnrecognizedStr, +) +from openrouter.utils import ( + FieldMetadata, + PathParamMetadata, + RequestMetadata, + validate_open_enum, +) +from pydantic import model_serializer +from pydantic.functional_validators import PlainValidator +from typing import Literal, Optional, Union +from typing_extensions import Annotated, NotRequired, TypedDict + + +UpdateKeysLimitReset = Union[ + Literal[ + "daily", + "weekly", + "monthly", + ], + UnrecognizedStr, +] +r"""New limit reset type for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday.""" + + +class UpdateKeysRequestBodyTypedDict(TypedDict): + name: NotRequired[str] + r"""New name for the API key""" + disabled: NotRequired[bool] + r"""Whether to disable the API key""" + limit: NotRequired[Nullable[float]] + r"""New spending limit for the API key in USD""" + limit_reset: NotRequired[Nullable[UpdateKeysLimitReset]] + r"""New limit reset type for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday.""" + include_byok_in_limit: NotRequired[bool] + r"""Whether to include BYOK usage in the limit""" + + +class UpdateKeysRequestBody(BaseModel): + name: Optional[str] = None + r"""New name for the API key""" + + disabled: Optional[bool] = None + r"""Whether to disable the API key""" + + limit: OptionalNullable[float] = UNSET + r"""New spending limit for the API key in USD""" + + limit_reset: Annotated[ + OptionalNullable[UpdateKeysLimitReset], + PlainValidator(validate_open_enum(False)), + ] = UNSET + r"""New limit reset type for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday.""" + + include_byok_in_limit: Optional[bool] = None + r"""Whether to include BYOK usage in the limit""" + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = [ + "name", + "disabled", + "limit", + "limit_reset", + "include_byok_in_limit", + ] + nullable_fields = ["limit", "limit_reset"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m + + +class UpdateKeysRequestTypedDict(TypedDict): + hash: str + r"""The hash identifier of the API key to update""" + body: UpdateKeysRequestBodyTypedDict + + +class UpdateKeysRequest(BaseModel): + hash: Annotated[ + str, FieldMetadata(path=PathParamMetadata(style="simple", explode=False)) + ] + r"""The hash identifier of the API key to update""" + + body: Annotated[ + UpdateKeysRequestBody, + FieldMetadata(request=RequestMetadata(media_type="application/json")), + ] + + +class UpdateKeysDataTypedDict(TypedDict): + r"""The updated API key information""" + + hash: str + r"""Unique hash identifier for the API key""" + name: str + r"""Name of the API key""" + label: str + r"""Human-readable label for the API key""" + disabled: bool + r"""Whether the API key is disabled""" + limit: Nullable[float] + r"""Spending limit for the API key in USD""" + limit_remaining: Nullable[float] + r"""Remaining spending limit in USD""" + limit_reset: Nullable[str] + r"""Type of limit reset for the API key""" + include_byok_in_limit: bool + r"""Whether to include external BYOK usage in the credit limit""" + usage: float + r"""Total OpenRouter credit usage (in USD) for the API key""" + usage_daily: float + r"""OpenRouter credit usage (in USD) for the current UTC day""" + usage_weekly: float + r"""OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday)""" + usage_monthly: float + r"""OpenRouter credit usage (in USD) for the current UTC month""" + byok_usage: float + r"""Total external BYOK usage (in USD) for the API key""" + byok_usage_daily: float + r"""External BYOK usage (in USD) for the current UTC day""" + byok_usage_weekly: float + r"""External BYOK usage (in USD) for the current UTC week (Monday-Sunday)""" + byok_usage_monthly: float + r"""External BYOK usage (in USD) for current UTC month""" + created_at: str + r"""ISO 8601 timestamp of when the API key was created""" + updated_at: Nullable[str] + r"""ISO 8601 timestamp of when the API key was last updated""" + expires_at: NotRequired[Nullable[datetime]] + r"""ISO 8601 UTC timestamp when the API key expires, or null if no expiration""" + + +class UpdateKeysData(BaseModel): + r"""The updated API key information""" + + hash: str + r"""Unique hash identifier for the API key""" + + name: str + r"""Name of the API key""" + + label: str + r"""Human-readable label for the API key""" + + disabled: bool + r"""Whether the API key is disabled""" + + limit: Nullable[float] + r"""Spending limit for the API key in USD""" + + limit_remaining: Nullable[float] + r"""Remaining spending limit in USD""" + + limit_reset: Nullable[str] + r"""Type of limit reset for the API key""" + + include_byok_in_limit: bool + r"""Whether to include external BYOK usage in the credit limit""" + + usage: float + r"""Total OpenRouter credit usage (in USD) for the API key""" + + usage_daily: float + r"""OpenRouter credit usage (in USD) for the current UTC day""" + + usage_weekly: float + r"""OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday)""" + + usage_monthly: float + r"""OpenRouter credit usage (in USD) for the current UTC month""" + + byok_usage: float + r"""Total external BYOK usage (in USD) for the API key""" + + byok_usage_daily: float + r"""External BYOK usage (in USD) for the current UTC day""" + + byok_usage_weekly: float + r"""External BYOK usage (in USD) for the current UTC week (Monday-Sunday)""" + + byok_usage_monthly: float + r"""External BYOK usage (in USD) for current UTC month""" + + created_at: str + r"""ISO 8601 timestamp of when the API key was created""" + + updated_at: Nullable[str] + r"""ISO 8601 timestamp of when the API key was last updated""" + + expires_at: OptionalNullable[datetime] = UNSET + r"""ISO 8601 UTC timestamp when the API key expires, or null if no expiration""" + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["expires_at"] + nullable_fields = [ + "limit", + "limit_remaining", + "limit_reset", + "updated_at", + "expires_at", + ] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m + + +class UpdateKeysResponseTypedDict(TypedDict): + r"""API key updated successfully""" + + data: UpdateKeysDataTypedDict + r"""The updated API key information""" + + +class UpdateKeysResponse(BaseModel): + r"""API key updated successfully""" + + data: UpdateKeysData + r"""The updated API key information""" diff --git a/src/openrouter/models/urlcitation.py b/src/openrouter/models/urlcitation.py new file mode 100644 index 0000000..f5ad030 --- /dev/null +++ b/src/openrouter/models/urlcitation.py @@ -0,0 +1,29 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel +from typing import Literal +from typing_extensions import TypedDict + + +URLCitationType = Literal["url_citation",] + + +class URLCitationTypedDict(TypedDict): + type: URLCitationType + url: str + title: str + start_index: float + end_index: float + + +class URLCitation(BaseModel): + type: URLCitationType + + url: str + + title: str + + start_index: float + + end_index: float diff --git a/src/openrouter/models/usermessage.py b/src/openrouter/models/usermessage.py new file mode 100644 index 0000000..ce9e9d6 --- /dev/null +++ b/src/openrouter/models/usermessage.py @@ -0,0 +1,40 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .chatmessagecontentitem import ( + ChatMessageContentItem, + ChatMessageContentItemTypedDict, +) +from openrouter.types import BaseModel +from openrouter.utils import validate_const +import pydantic +from pydantic.functional_validators import AfterValidator +from typing import List, Literal, Optional, Union +from typing_extensions import Annotated, NotRequired, TypeAliasType, TypedDict + + +UserMessageContentTypedDict = TypeAliasType( + "UserMessageContentTypedDict", Union[str, List[ChatMessageContentItemTypedDict]] +) + + +UserMessageContent = TypeAliasType( + "UserMessageContent", Union[str, List[ChatMessageContentItem]] +) + + +class UserMessageTypedDict(TypedDict): + content: UserMessageContentTypedDict + role: Literal["user"] + name: NotRequired[str] + + +class UserMessage(BaseModel): + content: UserMessageContent + + ROLE: Annotated[ + Annotated[Literal["user"], AfterValidator(validate_const("user"))], + pydantic.Field(alias="role"), + ] = "user" + + name: Optional[str] = None diff --git a/src/openrouter/models/websearchpreviewtooluserlocation.py b/src/openrouter/models/websearchpreviewtooluserlocation.py new file mode 100644 index 0000000..af36ed3 --- /dev/null +++ b/src/openrouter/models/websearchpreviewtooluserlocation.py @@ -0,0 +1,66 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import ( + BaseModel, + Nullable, + OptionalNullable, + UNSET, + UNSET_SENTINEL, +) +from pydantic import model_serializer +from typing import Literal +from typing_extensions import NotRequired, TypedDict + + +WebSearchPreviewToolUserLocationType = Literal["approximate",] + + +class WebSearchPreviewToolUserLocationTypedDict(TypedDict): + type: WebSearchPreviewToolUserLocationType + city: NotRequired[Nullable[str]] + country: NotRequired[Nullable[str]] + region: NotRequired[Nullable[str]] + timezone: NotRequired[Nullable[str]] + + +class WebSearchPreviewToolUserLocation(BaseModel): + type: WebSearchPreviewToolUserLocationType + + city: OptionalNullable[str] = UNSET + + country: OptionalNullable[str] = UNSET + + region: OptionalNullable[str] = UNSET + + timezone: OptionalNullable[str] = UNSET + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["city", "country", "region", "timezone"] + nullable_fields = ["city", "country", "region", "timezone"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k) + serialized.pop(k, None) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = ( + self.__pydantic_fields_set__.intersection({n}) + or k in null_default_fields + ) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m diff --git a/src/openrouter/models/websearchstatus.py b/src/openrouter/models/websearchstatus.py new file mode 100644 index 0000000..a607c88 --- /dev/null +++ b/src/openrouter/models/websearchstatus.py @@ -0,0 +1,16 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import UnrecognizedStr +from typing import Literal, Union + + +WebSearchStatus = Union[ + Literal[ + "completed", + "searching", + "in_progress", + "failed", + ], + UnrecognizedStr, +] diff --git a/src/openrouter/models_.py b/src/openrouter/models_.py new file mode 100644 index 0000000..8d7e432 --- /dev/null +++ b/src/openrouter/models_.py @@ -0,0 +1,561 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from .basesdk import BaseSDK +from openrouter import errors, models, utils +from openrouter._hooks import HookContext +from openrouter.types import OptionalNullable, UNSET +from openrouter.utils import get_security_from_env +from openrouter.utils.unmarshal_json_response import unmarshal_json_response +from typing import Any, Mapping, Optional, Union + + +class Models(BaseSDK): + r"""Model information endpoints""" + + def count( + self, + *, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.ModelsCountResponse: + r"""Get total count of available models + + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + req = self._build_request( + method="GET", + path="/models/count", + base_url=base_url, + url_variables=url_variables, + request=None, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = self.do_request( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="listModelsCount", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=["4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response(models.ModelsCountResponse, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) + + async def count_async( + self, + *, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.ModelsCountResponse: + r"""Get total count of available models + + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + req = self._build_request_async( + method="GET", + path="/models/count", + base_url=base_url, + url_variables=url_variables, + request=None, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = await self.do_request_async( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="listModelsCount", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=["4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response(models.ModelsCountResponse, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) + + def list( + self, + *, + category: Optional[str] = None, + supported_parameters: Optional[str] = None, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.ModelsListResponse: + r"""List all models and their properties + + :param category: + :param supported_parameters: + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + + request = models.GetModelsRequest( + category=category, + supported_parameters=supported_parameters, + ) + + req = self._build_request( + method="GET", + path="/models", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = self.do_request( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="getModels", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=["400", "4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response(models.ModelsListResponse, http_res) + if utils.match_response(http_res, "400", "application/json"): + response_data = unmarshal_json_response( + errors.BadRequestResponseErrorData, http_res + ) + raise errors.BadRequestResponseError(response_data, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) + + async def list_async( + self, + *, + category: Optional[str] = None, + supported_parameters: Optional[str] = None, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.ModelsListResponse: + r"""List all models and their properties + + :param category: + :param supported_parameters: + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + + request = models.GetModelsRequest( + category=category, + supported_parameters=supported_parameters, + ) + + req = self._build_request_async( + method="GET", + path="/models", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = await self.do_request_async( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="getModels", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=["400", "4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response(models.ModelsListResponse, http_res) + if utils.match_response(http_res, "400", "application/json"): + response_data = unmarshal_json_response( + errors.BadRequestResponseErrorData, http_res + ) + raise errors.BadRequestResponseError(response_data, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) + + def list_for_user( + self, + *, + security: Union[ + models.ListModelsUserSecurity, models.ListModelsUserSecurityTypedDict + ], + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.ModelsListResponse: + r"""List models filtered by user provider preferences + + :param security: + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + req = self._build_request( + method="GET", + path="/models/user", + base_url=base_url, + url_variables=url_variables, + request=None, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=utils.get_pydantic_model(security, models.ListModelsUserSecurity), + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = self.do_request( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="listModelsUser", + oauth2_scopes=None, + security_source=get_security_from_env(security, models.Security), + ), + request=req, + error_status_codes=["401", "4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response(models.ModelsListResponse, http_res) + if utils.match_response(http_res, "401", "application/json"): + response_data = unmarshal_json_response( + errors.UnauthorizedResponseErrorData, http_res + ) + raise errors.UnauthorizedResponseError(response_data, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) + + async def list_for_user_async( + self, + *, + security: Union[ + models.ListModelsUserSecurity, models.ListModelsUserSecurityTypedDict + ], + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.ModelsListResponse: + r"""List models filtered by user provider preferences + + :param security: + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + req = self._build_request_async( + method="GET", + path="/models/user", + base_url=base_url, + url_variables=url_variables, + request=None, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=utils.get_pydantic_model(security, models.ListModelsUserSecurity), + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = await self.do_request_async( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="listModelsUser", + oauth2_scopes=None, + security_source=get_security_from_env(security, models.Security), + ), + request=req, + error_status_codes=["401", "4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response(models.ModelsListResponse, http_res) + if utils.match_response(http_res, "401", "application/json"): + response_data = unmarshal_json_response( + errors.UnauthorizedResponseErrorData, http_res + ) + raise errors.UnauthorizedResponseError(response_data, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) diff --git a/src/openrouter/oauth.py b/src/openrouter/oauth.py new file mode 100644 index 0000000..ba15506 --- /dev/null +++ b/src/openrouter/oauth.py @@ -0,0 +1,486 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from .basesdk import BaseSDK +from datetime import datetime +from openrouter import errors, models, utils +from openrouter._hooks import HookContext +from openrouter.types import OptionalNullable, UNSET +from openrouter.utils import get_security_from_env +from openrouter.utils.unmarshal_json_response import unmarshal_json_response +from typing import Any, Mapping, Optional + + +class OAuth(BaseSDK): + r"""OAuth authentication endpoints""" + + def exchange_auth_code_for_api_key( + self, + *, + code: str, + code_verifier: Optional[str] = None, + code_challenge_method: OptionalNullable[ + models.ExchangeAuthCodeForAPIKeyCodeChallengeMethod + ] = UNSET, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.ExchangeAuthCodeForAPIKeyResponse: + r"""Exchange authorization code for API key + + Exchange an authorization code from the PKCE flow for a user-controlled API key + + :param code: The authorization code received from the OAuth redirect + :param code_verifier: The code verifier if code_challenge was used in the authorization request + :param code_challenge_method: The method used to generate the code challenge + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + + request = models.ExchangeAuthCodeForAPIKeyRequest( + code=code, + code_verifier=code_verifier, + code_challenge_method=code_challenge_method, + ) + + req = self._build_request( + method="POST", + path="/auth/keys", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=True, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + get_serialized_body=lambda: utils.serialize_request_body( + request, False, False, "json", models.ExchangeAuthCodeForAPIKeyRequest + ), + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = self.do_request( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="exchangeAuthCodeForAPIKey", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=["400", "403", "4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response( + models.ExchangeAuthCodeForAPIKeyResponse, http_res + ) + if utils.match_response(http_res, "400", "application/json"): + response_data = unmarshal_json_response( + errors.BadRequestResponseErrorData, http_res + ) + raise errors.BadRequestResponseError(response_data, http_res) + if utils.match_response(http_res, "403", "application/json"): + response_data = unmarshal_json_response( + errors.ForbiddenResponseErrorData, http_res + ) + raise errors.ForbiddenResponseError(response_data, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) + + async def exchange_auth_code_for_api_key_async( + self, + *, + code: str, + code_verifier: Optional[str] = None, + code_challenge_method: OptionalNullable[ + models.ExchangeAuthCodeForAPIKeyCodeChallengeMethod + ] = UNSET, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.ExchangeAuthCodeForAPIKeyResponse: + r"""Exchange authorization code for API key + + Exchange an authorization code from the PKCE flow for a user-controlled API key + + :param code: The authorization code received from the OAuth redirect + :param code_verifier: The code verifier if code_challenge was used in the authorization request + :param code_challenge_method: The method used to generate the code challenge + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + + request = models.ExchangeAuthCodeForAPIKeyRequest( + code=code, + code_verifier=code_verifier, + code_challenge_method=code_challenge_method, + ) + + req = self._build_request_async( + method="POST", + path="/auth/keys", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=True, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + get_serialized_body=lambda: utils.serialize_request_body( + request, False, False, "json", models.ExchangeAuthCodeForAPIKeyRequest + ), + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = await self.do_request_async( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="exchangeAuthCodeForAPIKey", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=["400", "403", "4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response( + models.ExchangeAuthCodeForAPIKeyResponse, http_res + ) + if utils.match_response(http_res, "400", "application/json"): + response_data = unmarshal_json_response( + errors.BadRequestResponseErrorData, http_res + ) + raise errors.BadRequestResponseError(response_data, http_res) + if utils.match_response(http_res, "403", "application/json"): + response_data = unmarshal_json_response( + errors.ForbiddenResponseErrorData, http_res + ) + raise errors.ForbiddenResponseError(response_data, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) + + def create_auth_code( + self, + *, + callback_url: str, + code_challenge: Optional[str] = None, + code_challenge_method: Optional[ + models.CreateAuthKeysCodeCodeChallengeMethod + ] = None, + limit: Optional[float] = None, + expires_at: OptionalNullable[datetime] = UNSET, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.CreateAuthKeysCodeResponse: + r"""Create authorization code + + Create an authorization code for the PKCE flow to generate a user-controlled API key + + :param callback_url: The callback URL to redirect to after authorization. Note, only https URLs on ports 443 and 3000 are allowed. + :param code_challenge: PKCE code challenge for enhanced security + :param code_challenge_method: The method used to generate the code challenge + :param limit: Credit limit for the API key to be created + :param expires_at: Optional expiration time for the API key to be created + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + + request = models.CreateAuthKeysCodeRequest( + callback_url=callback_url, + code_challenge=code_challenge, + code_challenge_method=code_challenge_method, + limit=limit, + expires_at=expires_at, + ) + + req = self._build_request( + method="POST", + path="/auth/keys/code", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=True, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + get_serialized_body=lambda: utils.serialize_request_body( + request, False, False, "json", models.CreateAuthKeysCodeRequest + ), + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = self.do_request( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="createAuthKeysCode", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=["400", "401", "4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response(models.CreateAuthKeysCodeResponse, http_res) + if utils.match_response(http_res, "400", "application/json"): + response_data = unmarshal_json_response( + errors.BadRequestResponseErrorData, http_res + ) + raise errors.BadRequestResponseError(response_data, http_res) + if utils.match_response(http_res, "401", "application/json"): + response_data = unmarshal_json_response( + errors.UnauthorizedResponseErrorData, http_res + ) + raise errors.UnauthorizedResponseError(response_data, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) + + async def create_auth_code_async( + self, + *, + callback_url: str, + code_challenge: Optional[str] = None, + code_challenge_method: Optional[ + models.CreateAuthKeysCodeCodeChallengeMethod + ] = None, + limit: Optional[float] = None, + expires_at: OptionalNullable[datetime] = UNSET, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.CreateAuthKeysCodeResponse: + r"""Create authorization code + + Create an authorization code for the PKCE flow to generate a user-controlled API key + + :param callback_url: The callback URL to redirect to after authorization. Note, only https URLs on ports 443 and 3000 are allowed. + :param code_challenge: PKCE code challenge for enhanced security + :param code_challenge_method: The method used to generate the code challenge + :param limit: Credit limit for the API key to be created + :param expires_at: Optional expiration time for the API key to be created + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + + request = models.CreateAuthKeysCodeRequest( + callback_url=callback_url, + code_challenge=code_challenge, + code_challenge_method=code_challenge_method, + limit=limit, + expires_at=expires_at, + ) + + req = self._build_request_async( + method="POST", + path="/auth/keys/code", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=True, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + get_serialized_body=lambda: utils.serialize_request_body( + request, False, False, "json", models.CreateAuthKeysCodeRequest + ), + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = await self.do_request_async( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="createAuthKeysCode", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=["400", "401", "4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response(models.CreateAuthKeysCodeResponse, http_res) + if utils.match_response(http_res, "400", "application/json"): + response_data = unmarshal_json_response( + errors.BadRequestResponseErrorData, http_res + ) + raise errors.BadRequestResponseError(response_data, http_res) + if utils.match_response(http_res, "401", "application/json"): + response_data = unmarshal_json_response( + errors.UnauthorizedResponseErrorData, http_res + ) + raise errors.UnauthorizedResponseError(response_data, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) diff --git a/src/openrouter/parameters.py b/src/openrouter/parameters.py new file mode 100644 index 0000000..0faab21 --- /dev/null +++ b/src/openrouter/parameters.py @@ -0,0 +1,231 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from .basesdk import BaseSDK +from openrouter import errors, models, utils +from openrouter._hooks import HookContext +from openrouter.types import OptionalNullable, UNSET +from openrouter.utils import get_security_from_env +from openrouter.utils.unmarshal_json_response import unmarshal_json_response +from typing import Any, Mapping, Optional, Union + + +class Parameters(BaseSDK): + r"""Parameters endpoints""" + + def get_parameters( + self, + *, + security: Union[ + models.GetParametersSecurity, models.GetParametersSecurityTypedDict + ], + author: str, + slug: str, + provider: Optional[models.GetParametersProvider] = None, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.GetParametersResponse: + r"""Get a model's supported parameters and data about which are most popular + + :param security: + :param author: + :param slug: + :param provider: + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + + request = models.GetParametersRequest( + author=author, + slug=slug, + provider=provider, + ) + + req = self._build_request( + method="GET", + path="/parameters/{author}/{slug}", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=False, + request_has_path_params=True, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=utils.get_pydantic_model(security, models.GetParametersSecurity), + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = self.do_request( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="getParameters", + oauth2_scopes=None, + security_source=get_security_from_env(security, models.Security), + ), + request=req, + error_status_codes=["401", "404", "4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response(models.GetParametersResponse, http_res) + if utils.match_response(http_res, "401", "application/json"): + response_data = unmarshal_json_response( + errors.UnauthorizedResponseErrorData, http_res + ) + raise errors.UnauthorizedResponseError(response_data, http_res) + if utils.match_response(http_res, "404", "application/json"): + response_data = unmarshal_json_response( + errors.NotFoundResponseErrorData, http_res + ) + raise errors.NotFoundResponseError(response_data, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) + + async def get_parameters_async( + self, + *, + security: Union[ + models.GetParametersSecurity, models.GetParametersSecurityTypedDict + ], + author: str, + slug: str, + provider: Optional[models.GetParametersProvider] = None, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.GetParametersResponse: + r"""Get a model's supported parameters and data about which are most popular + + :param security: + :param author: + :param slug: + :param provider: + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + + request = models.GetParametersRequest( + author=author, + slug=slug, + provider=provider, + ) + + req = self._build_request_async( + method="GET", + path="/parameters/{author}/{slug}", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=False, + request_has_path_params=True, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=utils.get_pydantic_model(security, models.GetParametersSecurity), + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = await self.do_request_async( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="getParameters", + oauth2_scopes=None, + security_source=get_security_from_env(security, models.Security), + ), + request=req, + error_status_codes=["401", "404", "4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response(models.GetParametersResponse, http_res) + if utils.match_response(http_res, "401", "application/json"): + response_data = unmarshal_json_response( + errors.UnauthorizedResponseErrorData, http_res + ) + raise errors.UnauthorizedResponseError(response_data, http_res) + if utils.match_response(http_res, "404", "application/json"): + response_data = unmarshal_json_response( + errors.NotFoundResponseErrorData, http_res + ) + raise errors.NotFoundResponseError(response_data, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) diff --git a/src/openrouter/providers.py b/src/openrouter/providers.py new file mode 100644 index 0000000..2b891fd --- /dev/null +++ b/src/openrouter/providers.py @@ -0,0 +1,181 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from .basesdk import BaseSDK +from openrouter import errors, models, utils +from openrouter._hooks import HookContext +from openrouter.types import OptionalNullable, UNSET +from openrouter.utils import get_security_from_env +from openrouter.utils.unmarshal_json_response import unmarshal_json_response +from typing import Any, Mapping, Optional + + +class Providers(BaseSDK): + r"""Provider information endpoints""" + + def list( + self, + *, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.ListProvidersResponse: + r"""List all providers + + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + req = self._build_request( + method="GET", + path="/providers", + base_url=base_url, + url_variables=url_variables, + request=None, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = self.do_request( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="listProviders", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=["4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response(models.ListProvidersResponse, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) + + async def list_async( + self, + *, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.ListProvidersResponse: + r"""List all providers + + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + req = self._build_request_async( + method="GET", + path="/providers", + base_url=base_url, + url_variables=url_variables, + request=None, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = await self.do_request_async( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="listProviders", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=["4XX", "500", "5XX"], + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response(models.ListProvidersResponse, http_res) + if utils.match_response(http_res, "500", "application/json"): + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res + ) + raise errors.InternalServerResponseError(response_data, http_res) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + raise errors.OpenRouterDefaultError("Unexpected response received", http_res) diff --git a/src/openrouter/py.typed b/src/openrouter/py.typed new file mode 100644 index 0000000..3e38f1a --- /dev/null +++ b/src/openrouter/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. The package enables type hints. diff --git a/src/openrouter/responses.py b/src/openrouter/responses.py new file mode 100644 index 0000000..22ac874 --- /dev/null +++ b/src/openrouter/responses.py @@ -0,0 +1,1107 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from .basesdk import BaseSDK +from enum import Enum +from openrouter import errors, models, utils +from openrouter._hooks import HookContext +from openrouter.types import OptionalNullable, UNSET +from openrouter.utils import eventstreaming, get_security_from_env +from openrouter.utils.unmarshal_json_response import unmarshal_json_response +from typing import Any, Dict, List, Literal, Mapping, Optional, Union, overload + + +class SendAcceptEnum(str, Enum): + APPLICATION_JSON = "application/json" + TEXT_EVENT_STREAM = "text/event-stream" + + +class Responses(BaseSDK): + r"""beta.responses endpoints""" + + @overload + def send( + self, + *, + input: Optional[ + Union[models.OpenResponsesInput, models.OpenResponsesInputTypedDict] + ] = None, + instructions: OptionalNullable[str] = UNSET, + metadata: OptionalNullable[Dict[str, str]] = UNSET, + tools: Optional[ + Union[ + List[models.OpenResponsesRequestToolUnion], + List[models.OpenResponsesRequestToolUnionTypedDict], + ] + ] = None, + tool_choice: Optional[ + Union[ + models.OpenAIResponsesToolChoiceUnion, + models.OpenAIResponsesToolChoiceUnionTypedDict, + ] + ] = None, + parallel_tool_calls: OptionalNullable[bool] = UNSET, + model: Optional[str] = None, + models: Optional[List[str]] = None, + text: Optional[ + Union[ + models.OpenResponsesResponseText, + models.OpenResponsesResponseTextTypedDict, + ] + ] = None, + reasoning: OptionalNullable[ + Union[ + models.OpenResponsesReasoningConfig, + models.OpenResponsesReasoningConfigTypedDict, + ] + ] = UNSET, + max_output_tokens: OptionalNullable[float] = UNSET, + temperature: OptionalNullable[float] = UNSET, + top_p: OptionalNullable[float] = UNSET, + top_k: Optional[float] = None, + prompt_cache_key: OptionalNullable[str] = UNSET, + previous_response_id: OptionalNullable[str] = UNSET, + prompt: OptionalNullable[ + Union[models.OpenAIResponsesPrompt, models.OpenAIResponsesPromptTypedDict] + ] = UNSET, + include: OptionalNullable[List[models.OpenAIResponsesIncludable]] = UNSET, + background: OptionalNullable[bool] = UNSET, + safety_identifier: OptionalNullable[str] = UNSET, + store: OptionalNullable[bool] = UNSET, + service_tier: OptionalNullable[models.ServiceTier] = UNSET, + truncation: OptionalNullable[models.Truncation] = UNSET, + stream: Union[Literal[False], None] = None, + provider: OptionalNullable[ + Union[models.Provider, models.ProviderTypedDict] + ] = UNSET, + plugins: Optional[ + Union[List[models.Plugin], List[models.PluginTypedDict]] + ] = None, + user: Optional[str] = None, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.OpenResponsesNonStreamingResponse: + r"""Create a response + + Creates a streaming or non-streaming response using OpenResponses API format + + :param input: Input for a response request - can be a string or array of items + :param instructions: + :param metadata: Metadata key-value pairs for the request. Keys must be ≤64 characters and cannot contain brackets. Values must be ≤512 characters. Maximum 16 pairs allowed. + :param tools: + :param tool_choice: + :param parallel_tool_calls: + :param model: + :param models: + :param text: Text output configuration including format and verbosity + :param reasoning: Configuration for reasoning mode in the response + :param max_output_tokens: + :param temperature: + :param top_p: + :param top_k: + :param prompt_cache_key: + :param previous_response_id: + :param prompt: + :param include: + :param background: + :param safety_identifier: + :param store: + :param service_tier: + :param truncation: + :param stream: + :param provider: When multiple model providers are available, optionally indicate your routing preference. + :param plugins: Plugins you want to enable for this request, including their settings. + :param user: A unique identifier representing your end-user, which helps distinguish between different users of your app. This allows your app to identify specific users in case of abuse reports, preventing your entire app from being affected by the actions of individual users. Maximum of 128 characters. + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param accept_header_override: Override the default accept header for this method + :param http_headers: Additional headers to set or replace on requests. + """ + + @overload + def send( + self, + *, + input: Optional[ + Union[models.OpenResponsesInput, models.OpenResponsesInputTypedDict] + ] = None, + instructions: OptionalNullable[str] = UNSET, + metadata: OptionalNullable[Dict[str, str]] = UNSET, + tools: Optional[ + Union[ + List[models.OpenResponsesRequestToolUnion], + List[models.OpenResponsesRequestToolUnionTypedDict], + ] + ] = None, + tool_choice: Optional[ + Union[ + models.OpenAIResponsesToolChoiceUnion, + models.OpenAIResponsesToolChoiceUnionTypedDict, + ] + ] = None, + parallel_tool_calls: OptionalNullable[bool] = UNSET, + model: Optional[str] = None, + models: Optional[List[str]] = None, + text: Optional[ + Union[ + models.OpenResponsesResponseText, + models.OpenResponsesResponseTextTypedDict, + ] + ] = None, + reasoning: OptionalNullable[ + Union[ + models.OpenResponsesReasoningConfig, + models.OpenResponsesReasoningConfigTypedDict, + ] + ] = UNSET, + max_output_tokens: OptionalNullable[float] = UNSET, + temperature: OptionalNullable[float] = UNSET, + top_p: OptionalNullable[float] = UNSET, + top_k: Optional[float] = None, + prompt_cache_key: OptionalNullable[str] = UNSET, + previous_response_id: OptionalNullable[str] = UNSET, + prompt: OptionalNullable[ + Union[models.OpenAIResponsesPrompt, models.OpenAIResponsesPromptTypedDict] + ] = UNSET, + include: OptionalNullable[List[models.OpenAIResponsesIncludable]] = UNSET, + background: OptionalNullable[bool] = UNSET, + safety_identifier: OptionalNullable[str] = UNSET, + store: OptionalNullable[bool] = UNSET, + service_tier: OptionalNullable[models.ServiceTier] = UNSET, + truncation: OptionalNullable[models.Truncation] = UNSET, + stream: Literal[True], + provider: OptionalNullable[ + Union[models.Provider, models.ProviderTypedDict] + ] = UNSET, + plugins: Optional[ + Union[List[models.Plugin], List[models.PluginTypedDict]] + ] = None, + user: Optional[str] = None, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> eventstreaming.EventStream[models.CreateResponsesResponseBody]: + r"""Create a response + + Creates a streaming or non-streaming response using OpenResponses API format + + :param input: Input for a response request - can be a string or array of items + :param instructions: + :param metadata: Metadata key-value pairs for the request. Keys must be ≤64 characters and cannot contain brackets. Values must be ≤512 characters. Maximum 16 pairs allowed. + :param tools: + :param tool_choice: + :param parallel_tool_calls: + :param model: + :param models: + :param text: Text output configuration including format and verbosity + :param reasoning: Configuration for reasoning mode in the response + :param max_output_tokens: + :param temperature: + :param top_p: + :param top_k: + :param prompt_cache_key: + :param previous_response_id: + :param prompt: + :param include: + :param background: + :param safety_identifier: + :param store: + :param service_tier: + :param truncation: + :param stream: + :param provider: When multiple model providers are available, optionally indicate your routing preference. + :param plugins: Plugins you want to enable for this request, including their settings. + :param user: A unique identifier representing your end-user, which helps distinguish between different users of your app. This allows your app to identify specific users in case of abuse reports, preventing your entire app from being affected by the actions of individual users. Maximum of 128 characters. + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param accept_header_override: Override the default accept header for this method + :param http_headers: Additional headers to set or replace on requests. + """ + + def send( + self, + *, + input: Optional[ + Union[models.OpenResponsesInput, models.OpenResponsesInputTypedDict] + ] = None, + instructions: OptionalNullable[str] = UNSET, + metadata: OptionalNullable[Dict[str, str]] = UNSET, + tools: Optional[ + Union[ + List[models.OpenResponsesRequestToolUnion], + List[models.OpenResponsesRequestToolUnionTypedDict], + ] + ] = None, + tool_choice: Optional[ + Union[ + models.OpenAIResponsesToolChoiceUnion, + models.OpenAIResponsesToolChoiceUnionTypedDict, + ] + ] = None, + parallel_tool_calls: OptionalNullable[bool] = UNSET, + model: Optional[str] = None, + models: Optional[List[str]] = None, + text: Optional[ + Union[ + models.OpenResponsesResponseText, + models.OpenResponsesResponseTextTypedDict, + ] + ] = None, + reasoning: OptionalNullable[ + Union[ + models.OpenResponsesReasoningConfig, + models.OpenResponsesReasoningConfigTypedDict, + ] + ] = UNSET, + max_output_tokens: OptionalNullable[float] = UNSET, + temperature: OptionalNullable[float] = UNSET, + top_p: OptionalNullable[float] = UNSET, + top_k: Optional[float] = None, + prompt_cache_key: OptionalNullable[str] = UNSET, + previous_response_id: OptionalNullable[str] = UNSET, + prompt: OptionalNullable[ + Union[models.OpenAIResponsesPrompt, models.OpenAIResponsesPromptTypedDict] + ] = UNSET, + include: OptionalNullable[List[models.OpenAIResponsesIncludable]] = UNSET, + background: OptionalNullable[bool] = UNSET, + safety_identifier: OptionalNullable[str] = UNSET, + store: OptionalNullable[bool] = UNSET, + service_tier: OptionalNullable[models.ServiceTier] = UNSET, + truncation: OptionalNullable[models.Truncation] = UNSET, + stream: Optional[bool] = False, + provider: OptionalNullable[ + Union[models.Provider, models.ProviderTypedDict] + ] = UNSET, + plugins: Optional[ + Union[List[models.Plugin], List[models.PluginTypedDict]] + ] = None, + user: Optional[str] = None, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.CreateResponsesResponse: + r"""Create a response + + Creates a streaming or non-streaming response using OpenResponses API format + + :param input: Input for a response request - can be a string or array of items + :param instructions: + :param metadata: Metadata key-value pairs for the request. Keys must be ≤64 characters and cannot contain brackets. Values must be ≤512 characters. Maximum 16 pairs allowed. + :param tools: + :param tool_choice: + :param parallel_tool_calls: + :param model: + :param models: + :param text: Text output configuration including format and verbosity + :param reasoning: Configuration for reasoning mode in the response + :param max_output_tokens: + :param temperature: + :param top_p: + :param top_k: + :param prompt_cache_key: + :param previous_response_id: + :param prompt: + :param include: + :param background: + :param safety_identifier: + :param store: + :param service_tier: + :param truncation: + :param stream: + :param provider: When multiple model providers are available, optionally indicate your routing preference. + :param plugins: Plugins you want to enable for this request, including their settings. + :param user: A unique identifier representing your end-user, which helps distinguish between different users of your app. This allows your app to identify specific users in case of abuse reports, preventing your entire app from being affected by the actions of individual users. Maximum of 128 characters. + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param accept_header_override: Override the default accept header for this method + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + + request = models.OpenResponsesRequest( + input=utils.get_pydantic_model(input, Optional[models.OpenResponsesInput]), + instructions=instructions, + metadata=metadata, + tools=utils.get_pydantic_model( + tools, Optional[List[models.OpenResponsesRequestToolUnion]] + ), + tool_choice=utils.get_pydantic_model( + tool_choice, Optional[models.OpenAIResponsesToolChoiceUnion] + ), + parallel_tool_calls=parallel_tool_calls, + model=model, + models=models, + text=utils.get_pydantic_model( + text, Optional[models.OpenResponsesResponseText] + ), + reasoning=utils.get_pydantic_model( + reasoning, OptionalNullable[models.OpenResponsesReasoningConfig] + ), + max_output_tokens=max_output_tokens, + temperature=temperature, + top_p=top_p, + top_k=top_k, + prompt_cache_key=prompt_cache_key, + previous_response_id=previous_response_id, + prompt=utils.get_pydantic_model( + prompt, OptionalNullable[models.OpenAIResponsesPrompt] + ), + include=include, + background=background, + safety_identifier=safety_identifier, + store=store, + service_tier=service_tier, + truncation=truncation, + stream=stream, + provider=utils.get_pydantic_model( + provider, OptionalNullable[models.Provider] + ), + plugins=utils.get_pydantic_model(plugins, Optional[List[models.Plugin]]), + user=user, + ) + + req = self._build_request( + method="POST", + path="/responses", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=True, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="text/event-stream" if stream else "application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + get_serialized_body=lambda: utils.serialize_request_body( + request, False, False, "json", models.OpenResponsesRequest + ), + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = self.do_request( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="createResponses", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=[ + "400", + "401", + "402", + "404", + "408", + "413", + "422", + "429", + "4XX", + "500", + "502", + "503", + "524", + "529", + "5XX", + ], + stream=True, + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + http_res_text = utils.stream_to_text(http_res) + return unmarshal_json_response( + models.OpenResponsesNonStreamingResponse, http_res, http_res_text + ) + if utils.match_response(http_res, "200", "text/event-stream"): + return eventstreaming.EventStream( + http_res, + lambda raw: utils.unmarshal_json( + raw, models.CreateResponsesResponseBody + ), + sentinel="[DONE]", + client_ref=self, + ) + if utils.match_response(http_res, "400", "application/json"): + http_res_text = utils.stream_to_text(http_res) + response_data = unmarshal_json_response( + errors.BadRequestResponseErrorData, http_res, http_res_text + ) + raise errors.BadRequestResponseError(response_data, http_res, http_res_text) + if utils.match_response(http_res, "401", "application/json"): + http_res_text = utils.stream_to_text(http_res) + response_data = unmarshal_json_response( + errors.UnauthorizedResponseErrorData, http_res, http_res_text + ) + raise errors.UnauthorizedResponseError( + response_data, http_res, http_res_text + ) + if utils.match_response(http_res, "402", "application/json"): + http_res_text = utils.stream_to_text(http_res) + response_data = unmarshal_json_response( + errors.PaymentRequiredResponseErrorData, http_res, http_res_text + ) + raise errors.PaymentRequiredResponseError( + response_data, http_res, http_res_text + ) + if utils.match_response(http_res, "404", "application/json"): + http_res_text = utils.stream_to_text(http_res) + response_data = unmarshal_json_response( + errors.NotFoundResponseErrorData, http_res, http_res_text + ) + raise errors.NotFoundResponseError(response_data, http_res, http_res_text) + if utils.match_response(http_res, "408", "application/json"): + http_res_text = utils.stream_to_text(http_res) + response_data = unmarshal_json_response( + errors.RequestTimeoutResponseErrorData, http_res, http_res_text + ) + raise errors.RequestTimeoutResponseError( + response_data, http_res, http_res_text + ) + if utils.match_response(http_res, "413", "application/json"): + http_res_text = utils.stream_to_text(http_res) + response_data = unmarshal_json_response( + errors.PayloadTooLargeResponseErrorData, http_res, http_res_text + ) + raise errors.PayloadTooLargeResponseError( + response_data, http_res, http_res_text + ) + if utils.match_response(http_res, "422", "application/json"): + http_res_text = utils.stream_to_text(http_res) + response_data = unmarshal_json_response( + errors.UnprocessableEntityResponseErrorData, http_res, http_res_text + ) + raise errors.UnprocessableEntityResponseError( + response_data, http_res, http_res_text + ) + if utils.match_response(http_res, "429", "application/json"): + http_res_text = utils.stream_to_text(http_res) + response_data = unmarshal_json_response( + errors.TooManyRequestsResponseErrorData, http_res, http_res_text + ) + raise errors.TooManyRequestsResponseError( + response_data, http_res, http_res_text + ) + if utils.match_response(http_res, "500", "application/json"): + http_res_text = utils.stream_to_text(http_res) + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res, http_res_text + ) + raise errors.InternalServerResponseError( + response_data, http_res, http_res_text + ) + if utils.match_response(http_res, "502", "application/json"): + http_res_text = utils.stream_to_text(http_res) + response_data = unmarshal_json_response( + errors.BadGatewayResponseErrorData, http_res, http_res_text + ) + raise errors.BadGatewayResponseError(response_data, http_res, http_res_text) + if utils.match_response(http_res, "503", "application/json"): + http_res_text = utils.stream_to_text(http_res) + response_data = unmarshal_json_response( + errors.ServiceUnavailableResponseErrorData, http_res, http_res_text + ) + raise errors.ServiceUnavailableResponseError( + response_data, http_res, http_res_text + ) + if utils.match_response(http_res, "524", "application/json"): + http_res_text = utils.stream_to_text(http_res) + response_data = unmarshal_json_response( + errors.EdgeNetworkTimeoutResponseErrorData, http_res, http_res_text + ) + raise errors.EdgeNetworkTimeoutResponseError( + response_data, http_res, http_res_text + ) + if utils.match_response(http_res, "529", "application/json"): + http_res_text = utils.stream_to_text(http_res) + response_data = unmarshal_json_response( + errors.ProviderOverloadedResponseErrorData, http_res, http_res_text + ) + raise errors.ProviderOverloadedResponseError( + response_data, http_res, http_res_text + ) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + http_res_text = utils.stream_to_text(http_res) + raise errors.OpenRouterDefaultError( + "Unexpected response received", http_res, http_res_text + ) + + @overload + async def send_async( + self, + *, + input: Optional[ + Union[models.OpenResponsesInput, models.OpenResponsesInputTypedDict] + ] = None, + instructions: OptionalNullable[str] = UNSET, + metadata: OptionalNullable[Dict[str, str]] = UNSET, + tools: Optional[ + Union[ + List[models.OpenResponsesRequestToolUnion], + List[models.OpenResponsesRequestToolUnionTypedDict], + ] + ] = None, + tool_choice: Optional[ + Union[ + models.OpenAIResponsesToolChoiceUnion, + models.OpenAIResponsesToolChoiceUnionTypedDict, + ] + ] = None, + parallel_tool_calls: OptionalNullable[bool] = UNSET, + model: Optional[str] = None, + models: Optional[List[str]] = None, + text: Optional[ + Union[ + models.OpenResponsesResponseText, + models.OpenResponsesResponseTextTypedDict, + ] + ] = None, + reasoning: OptionalNullable[ + Union[ + models.OpenResponsesReasoningConfig, + models.OpenResponsesReasoningConfigTypedDict, + ] + ] = UNSET, + max_output_tokens: OptionalNullable[float] = UNSET, + temperature: OptionalNullable[float] = UNSET, + top_p: OptionalNullable[float] = UNSET, + top_k: Optional[float] = None, + prompt_cache_key: OptionalNullable[str] = UNSET, + previous_response_id: OptionalNullable[str] = UNSET, + prompt: OptionalNullable[ + Union[models.OpenAIResponsesPrompt, models.OpenAIResponsesPromptTypedDict] + ] = UNSET, + include: OptionalNullable[List[models.OpenAIResponsesIncludable]] = UNSET, + background: OptionalNullable[bool] = UNSET, + safety_identifier: OptionalNullable[str] = UNSET, + store: OptionalNullable[bool] = UNSET, + service_tier: OptionalNullable[models.ServiceTier] = UNSET, + truncation: OptionalNullable[models.Truncation] = UNSET, + stream: Union[Literal[False], None] = None, + provider: OptionalNullable[ + Union[models.Provider, models.ProviderTypedDict] + ] = UNSET, + plugins: Optional[ + Union[List[models.Plugin], List[models.PluginTypedDict]] + ] = None, + user: Optional[str] = None, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.OpenResponsesNonStreamingResponse: + r"""Create a response + + Creates a streaming or non-streaming response using OpenResponses API format + + :param input: Input for a response request - can be a string or array of items + :param instructions: + :param metadata: Metadata key-value pairs for the request. Keys must be ≤64 characters and cannot contain brackets. Values must be ≤512 characters. Maximum 16 pairs allowed. + :param tools: + :param tool_choice: + :param parallel_tool_calls: + :param model: + :param models: + :param text: Text output configuration including format and verbosity + :param reasoning: Configuration for reasoning mode in the response + :param max_output_tokens: + :param temperature: + :param top_p: + :param top_k: + :param prompt_cache_key: + :param previous_response_id: + :param prompt: + :param include: + :param background: + :param safety_identifier: + :param store: + :param service_tier: + :param truncation: + :param stream: + :param provider: When multiple model providers are available, optionally indicate your routing preference. + :param plugins: Plugins you want to enable for this request, including their settings. + :param user: A unique identifier representing your end-user, which helps distinguish between different users of your app. This allows your app to identify specific users in case of abuse reports, preventing your entire app from being affected by the actions of individual users. Maximum of 128 characters. + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param accept_header_override: Override the default accept header for this method + :param http_headers: Additional headers to set or replace on requests. + """ + + @overload + async def send_async( + self, + *, + input: Optional[ + Union[models.OpenResponsesInput, models.OpenResponsesInputTypedDict] + ] = None, + instructions: OptionalNullable[str] = UNSET, + metadata: OptionalNullable[Dict[str, str]] = UNSET, + tools: Optional[ + Union[ + List[models.OpenResponsesRequestToolUnion], + List[models.OpenResponsesRequestToolUnionTypedDict], + ] + ] = None, + tool_choice: Optional[ + Union[ + models.OpenAIResponsesToolChoiceUnion, + models.OpenAIResponsesToolChoiceUnionTypedDict, + ] + ] = None, + parallel_tool_calls: OptionalNullable[bool] = UNSET, + model: Optional[str] = None, + models: Optional[List[str]] = None, + text: Optional[ + Union[ + models.OpenResponsesResponseText, + models.OpenResponsesResponseTextTypedDict, + ] + ] = None, + reasoning: OptionalNullable[ + Union[ + models.OpenResponsesReasoningConfig, + models.OpenResponsesReasoningConfigTypedDict, + ] + ] = UNSET, + max_output_tokens: OptionalNullable[float] = UNSET, + temperature: OptionalNullable[float] = UNSET, + top_p: OptionalNullable[float] = UNSET, + top_k: Optional[float] = None, + prompt_cache_key: OptionalNullable[str] = UNSET, + previous_response_id: OptionalNullable[str] = UNSET, + prompt: OptionalNullable[ + Union[models.OpenAIResponsesPrompt, models.OpenAIResponsesPromptTypedDict] + ] = UNSET, + include: OptionalNullable[List[models.OpenAIResponsesIncludable]] = UNSET, + background: OptionalNullable[bool] = UNSET, + safety_identifier: OptionalNullable[str] = UNSET, + store: OptionalNullable[bool] = UNSET, + service_tier: OptionalNullable[models.ServiceTier] = UNSET, + truncation: OptionalNullable[models.Truncation] = UNSET, + stream: Literal[True], + provider: OptionalNullable[ + Union[models.Provider, models.ProviderTypedDict] + ] = UNSET, + plugins: Optional[ + Union[List[models.Plugin], List[models.PluginTypedDict]] + ] = None, + user: Optional[str] = None, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> eventstreaming.EventStreamAsync[models.CreateResponsesResponseBody]: + r"""Create a response + + Creates a streaming or non-streaming response using OpenResponses API format + + :param input: Input for a response request - can be a string or array of items + :param instructions: + :param metadata: Metadata key-value pairs for the request. Keys must be ≤64 characters and cannot contain brackets. Values must be ≤512 characters. Maximum 16 pairs allowed. + :param tools: + :param tool_choice: + :param parallel_tool_calls: + :param model: + :param models: + :param text: Text output configuration including format and verbosity + :param reasoning: Configuration for reasoning mode in the response + :param max_output_tokens: + :param temperature: + :param top_p: + :param top_k: + :param prompt_cache_key: + :param previous_response_id: + :param prompt: + :param include: + :param background: + :param safety_identifier: + :param store: + :param service_tier: + :param truncation: + :param stream: + :param provider: When multiple model providers are available, optionally indicate your routing preference. + :param plugins: Plugins you want to enable for this request, including their settings. + :param user: A unique identifier representing your end-user, which helps distinguish between different users of your app. This allows your app to identify specific users in case of abuse reports, preventing your entire app from being affected by the actions of individual users. Maximum of 128 characters. + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param accept_header_override: Override the default accept header for this method + :param http_headers: Additional headers to set or replace on requests. + """ + + async def send_async( + self, + *, + input: Optional[ + Union[models.OpenResponsesInput, models.OpenResponsesInputTypedDict] + ] = None, + instructions: OptionalNullable[str] = UNSET, + metadata: OptionalNullable[Dict[str, str]] = UNSET, + tools: Optional[ + Union[ + List[models.OpenResponsesRequestToolUnion], + List[models.OpenResponsesRequestToolUnionTypedDict], + ] + ] = None, + tool_choice: Optional[ + Union[ + models.OpenAIResponsesToolChoiceUnion, + models.OpenAIResponsesToolChoiceUnionTypedDict, + ] + ] = None, + parallel_tool_calls: OptionalNullable[bool] = UNSET, + model: Optional[str] = None, + models: Optional[List[str]] = None, + text: Optional[ + Union[ + models.OpenResponsesResponseText, + models.OpenResponsesResponseTextTypedDict, + ] + ] = None, + reasoning: OptionalNullable[ + Union[ + models.OpenResponsesReasoningConfig, + models.OpenResponsesReasoningConfigTypedDict, + ] + ] = UNSET, + max_output_tokens: OptionalNullable[float] = UNSET, + temperature: OptionalNullable[float] = UNSET, + top_p: OptionalNullable[float] = UNSET, + top_k: Optional[float] = None, + prompt_cache_key: OptionalNullable[str] = UNSET, + previous_response_id: OptionalNullable[str] = UNSET, + prompt: OptionalNullable[ + Union[models.OpenAIResponsesPrompt, models.OpenAIResponsesPromptTypedDict] + ] = UNSET, + include: OptionalNullable[List[models.OpenAIResponsesIncludable]] = UNSET, + background: OptionalNullable[bool] = UNSET, + safety_identifier: OptionalNullable[str] = UNSET, + store: OptionalNullable[bool] = UNSET, + service_tier: OptionalNullable[models.ServiceTier] = UNSET, + truncation: OptionalNullable[models.Truncation] = UNSET, + stream: Optional[bool] = False, + provider: OptionalNullable[ + Union[models.Provider, models.ProviderTypedDict] + ] = UNSET, + plugins: Optional[ + Union[List[models.Plugin], List[models.PluginTypedDict]] + ] = None, + user: Optional[str] = None, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> models.CreateResponsesResponse: + r"""Create a response + + Creates a streaming or non-streaming response using OpenResponses API format + + :param input: Input for a response request - can be a string or array of items + :param instructions: + :param metadata: Metadata key-value pairs for the request. Keys must be ≤64 characters and cannot contain brackets. Values must be ≤512 characters. Maximum 16 pairs allowed. + :param tools: + :param tool_choice: + :param parallel_tool_calls: + :param model: + :param models: + :param text: Text output configuration including format and verbosity + :param reasoning: Configuration for reasoning mode in the response + :param max_output_tokens: + :param temperature: + :param top_p: + :param top_k: + :param prompt_cache_key: + :param previous_response_id: + :param prompt: + :param include: + :param background: + :param safety_identifier: + :param store: + :param service_tier: + :param truncation: + :param stream: + :param provider: When multiple model providers are available, optionally indicate your routing preference. + :param plugins: Plugins you want to enable for this request, including their settings. + :param user: A unique identifier representing your end-user, which helps distinguish between different users of your app. This allows your app to identify specific users in case of abuse reports, preventing your entire app from being affected by the actions of individual users. Maximum of 128 characters. + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + :param accept_header_override: Override the default accept header for this method + :param http_headers: Additional headers to set or replace on requests. + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + else: + base_url = self._get_url(base_url, url_variables) + + request = models.OpenResponsesRequest( + input=utils.get_pydantic_model(input, Optional[models.OpenResponsesInput]), + instructions=instructions, + metadata=metadata, + tools=utils.get_pydantic_model( + tools, Optional[List[models.OpenResponsesRequestToolUnion]] + ), + tool_choice=utils.get_pydantic_model( + tool_choice, Optional[models.OpenAIResponsesToolChoiceUnion] + ), + parallel_tool_calls=parallel_tool_calls, + model=model, + models=models, + text=utils.get_pydantic_model( + text, Optional[models.OpenResponsesResponseText] + ), + reasoning=utils.get_pydantic_model( + reasoning, OptionalNullable[models.OpenResponsesReasoningConfig] + ), + max_output_tokens=max_output_tokens, + temperature=temperature, + top_p=top_p, + top_k=top_k, + prompt_cache_key=prompt_cache_key, + previous_response_id=previous_response_id, + prompt=utils.get_pydantic_model( + prompt, OptionalNullable[models.OpenAIResponsesPrompt] + ), + include=include, + background=background, + safety_identifier=safety_identifier, + store=store, + service_tier=service_tier, + truncation=truncation, + stream=stream, + provider=utils.get_pydantic_model( + provider, OptionalNullable[models.Provider] + ), + plugins=utils.get_pydantic_model(plugins, Optional[List[models.Plugin]]), + user=user, + ) + + req = self._build_request_async( + method="POST", + path="/responses", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=True, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="text/event-stream" if stream else "application/json", + http_headers=http_headers, + security=self.sdk_configuration.security, + get_serialized_body=lambda: utils.serialize_request_body( + request, False, False, "json", models.OpenResponsesRequest + ), + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, ["429", "500", "502", "503", "504"]) + + http_res = await self.do_request_async( + hook_ctx=HookContext( + config=self.sdk_configuration, + base_url=base_url or "", + operation_id="createResponses", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, models.Security + ), + ), + request=req, + error_status_codes=[ + "400", + "401", + "402", + "404", + "408", + "413", + "422", + "429", + "4XX", + "500", + "502", + "503", + "524", + "529", + "5XX", + ], + stream=True, + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + http_res_text = await utils.stream_to_text_async(http_res) + return unmarshal_json_response( + models.OpenResponsesNonStreamingResponse, http_res, http_res_text + ) + if utils.match_response(http_res, "200", "text/event-stream"): + return eventstreaming.EventStreamAsync( + http_res, + lambda raw: utils.unmarshal_json( + raw, models.CreateResponsesResponseBody + ), + sentinel="[DONE]", + client_ref=self, + ) + if utils.match_response(http_res, "400", "application/json"): + http_res_text = await utils.stream_to_text_async(http_res) + response_data = unmarshal_json_response( + errors.BadRequestResponseErrorData, http_res, http_res_text + ) + raise errors.BadRequestResponseError(response_data, http_res, http_res_text) + if utils.match_response(http_res, "401", "application/json"): + http_res_text = await utils.stream_to_text_async(http_res) + response_data = unmarshal_json_response( + errors.UnauthorizedResponseErrorData, http_res, http_res_text + ) + raise errors.UnauthorizedResponseError( + response_data, http_res, http_res_text + ) + if utils.match_response(http_res, "402", "application/json"): + http_res_text = await utils.stream_to_text_async(http_res) + response_data = unmarshal_json_response( + errors.PaymentRequiredResponseErrorData, http_res, http_res_text + ) + raise errors.PaymentRequiredResponseError( + response_data, http_res, http_res_text + ) + if utils.match_response(http_res, "404", "application/json"): + http_res_text = await utils.stream_to_text_async(http_res) + response_data = unmarshal_json_response( + errors.NotFoundResponseErrorData, http_res, http_res_text + ) + raise errors.NotFoundResponseError(response_data, http_res, http_res_text) + if utils.match_response(http_res, "408", "application/json"): + http_res_text = await utils.stream_to_text_async(http_res) + response_data = unmarshal_json_response( + errors.RequestTimeoutResponseErrorData, http_res, http_res_text + ) + raise errors.RequestTimeoutResponseError( + response_data, http_res, http_res_text + ) + if utils.match_response(http_res, "413", "application/json"): + http_res_text = await utils.stream_to_text_async(http_res) + response_data = unmarshal_json_response( + errors.PayloadTooLargeResponseErrorData, http_res, http_res_text + ) + raise errors.PayloadTooLargeResponseError( + response_data, http_res, http_res_text + ) + if utils.match_response(http_res, "422", "application/json"): + http_res_text = await utils.stream_to_text_async(http_res) + response_data = unmarshal_json_response( + errors.UnprocessableEntityResponseErrorData, http_res, http_res_text + ) + raise errors.UnprocessableEntityResponseError( + response_data, http_res, http_res_text + ) + if utils.match_response(http_res, "429", "application/json"): + http_res_text = await utils.stream_to_text_async(http_res) + response_data = unmarshal_json_response( + errors.TooManyRequestsResponseErrorData, http_res, http_res_text + ) + raise errors.TooManyRequestsResponseError( + response_data, http_res, http_res_text + ) + if utils.match_response(http_res, "500", "application/json"): + http_res_text = await utils.stream_to_text_async(http_res) + response_data = unmarshal_json_response( + errors.InternalServerResponseErrorData, http_res, http_res_text + ) + raise errors.InternalServerResponseError( + response_data, http_res, http_res_text + ) + if utils.match_response(http_res, "502", "application/json"): + http_res_text = await utils.stream_to_text_async(http_res) + response_data = unmarshal_json_response( + errors.BadGatewayResponseErrorData, http_res, http_res_text + ) + raise errors.BadGatewayResponseError(response_data, http_res, http_res_text) + if utils.match_response(http_res, "503", "application/json"): + http_res_text = await utils.stream_to_text_async(http_res) + response_data = unmarshal_json_response( + errors.ServiceUnavailableResponseErrorData, http_res, http_res_text + ) + raise errors.ServiceUnavailableResponseError( + response_data, http_res, http_res_text + ) + if utils.match_response(http_res, "524", "application/json"): + http_res_text = await utils.stream_to_text_async(http_res) + response_data = unmarshal_json_response( + errors.EdgeNetworkTimeoutResponseErrorData, http_res, http_res_text + ) + raise errors.EdgeNetworkTimeoutResponseError( + response_data, http_res, http_res_text + ) + if utils.match_response(http_res, "529", "application/json"): + http_res_text = await utils.stream_to_text_async(http_res) + response_data = unmarshal_json_response( + errors.ProviderOverloadedResponseErrorData, http_res, http_res_text + ) + raise errors.ProviderOverloadedResponseError( + response_data, http_res, http_res_text + ) + if utils.match_response(http_res, "4XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + if utils.match_response(http_res, "5XX", "*"): + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "API error occurred", http_res, http_res_text + ) + + http_res_text = await utils.stream_to_text_async(http_res) + raise errors.OpenRouterDefaultError( + "Unexpected response received", http_res, http_res_text + ) diff --git a/src/openrouter/sdk.py b/src/openrouter/sdk.py new file mode 100644 index 0000000..8b3fee6 --- /dev/null +++ b/src/openrouter/sdk.py @@ -0,0 +1,224 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from .basesdk import BaseSDK +from .httpclient import AsyncHttpClient, ClientOwner, HttpClient, close_clients +from .sdkconfiguration import SDKConfiguration +from .utils.logger import Logger, get_default_logger +from .utils.retries import RetryConfig +import httpx +import importlib +from openrouter import models, utils +from openrouter._hooks import SDKHooks +from openrouter.types import OptionalNullable, UNSET +import sys +from typing import Any, Callable, Dict, Optional, TYPE_CHECKING, Union, cast +import weakref + +if TYPE_CHECKING: + from openrouter.analytics import Analytics + from openrouter.api_keys import APIKeys + from openrouter.beta import Beta + from openrouter.chat import Chat + from openrouter.completions import Completions + from openrouter.credits import Credits + from openrouter.embeddings import Embeddings + from openrouter.endpoints import Endpoints + from openrouter.generations import Generations + from openrouter.models_ import Models + from openrouter.oauth import OAuth + from openrouter.parameters import Parameters + from openrouter.providers import Providers + + +class OpenRouter(BaseSDK): + r"""OpenRouter API: OpenAI-compatible Chat Completions and Completions API with additional OpenRouter features + https://openrouter.ai/docs - OpenRouter Documentation + """ + + beta: "Beta" + analytics: "Analytics" + r"""Analytics and usage endpoints""" + credits: "Credits" + r"""Credit management endpoints""" + embeddings: "Embeddings" + r"""Text embedding endpoints""" + generations: "Generations" + r"""Generation history endpoints""" + models: "Models" + r"""Model information endpoints""" + endpoints: "Endpoints" + r"""Endpoint information""" + parameters: "Parameters" + r"""Parameters endpoints""" + providers: "Providers" + r"""Provider information endpoints""" + api_keys: "APIKeys" + r"""API key management endpoints""" + o_auth: "OAuth" + r"""OAuth authentication endpoints""" + chat: "Chat" + completions: "Completions" + _sub_sdk_map = { + "beta": ("openrouter.beta", "Beta"), + "analytics": ("openrouter.analytics", "Analytics"), + "credits": ("openrouter.credits", "Credits"), + "embeddings": ("openrouter.embeddings", "Embeddings"), + "generations": ("openrouter.generations", "Generations"), + "models": ("openrouter.models_", "Models"), + "endpoints": ("openrouter.endpoints", "Endpoints"), + "parameters": ("openrouter.parameters", "Parameters"), + "providers": ("openrouter.providers", "Providers"), + "api_keys": ("openrouter.api_keys", "APIKeys"), + "o_auth": ("openrouter.oauth", "OAuth"), + "chat": ("openrouter.chat", "Chat"), + "completions": ("openrouter.completions", "Completions"), + } + + def __init__( + self, + api_key: Optional[Union[Optional[str], Callable[[], Optional[str]]]] = None, + server: Optional[str] = None, + server_url: Optional[str] = None, + url_params: Optional[Dict[str, str]] = None, + client: Optional[HttpClient] = None, + async_client: Optional[AsyncHttpClient] = None, + retry_config: OptionalNullable[RetryConfig] = UNSET, + timeout_ms: Optional[int] = None, + debug_logger: Optional[Logger] = None, + ) -> None: + r"""Instantiates the SDK configuring it with the provided parameters. + + :param api_key: The api_key required for authentication + :param server: The server by name to use for all methods + :param server_url: The server URL to use for all methods + :param url_params: Parameters to optionally template the server URL with + :param client: The HTTP client to use for all synchronous methods + :param async_client: The Async HTTP client to use for all asynchronous methods + :param retry_config: The retry configuration to use for all supported methods + :param timeout_ms: Optional request timeout applied to each operation in milliseconds + """ + client_supplied = True + if client is None: + client = httpx.Client(follow_redirects=True) + client_supplied = False + + assert issubclass( + type(client), HttpClient + ), "The provided client must implement the HttpClient protocol." + + async_client_supplied = True + if async_client is None: + async_client = httpx.AsyncClient(follow_redirects=True) + async_client_supplied = False + + if debug_logger is None: + debug_logger = get_default_logger() + + assert issubclass( + type(async_client), AsyncHttpClient + ), "The provided async_client must implement the AsyncHttpClient protocol." + + security: Any = None + if callable(api_key): + # pylint: disable=unnecessary-lambda-assignment + security = lambda: models.Security(api_key=api_key()) + else: + security = models.Security(api_key=api_key) + + if server_url is not None: + if url_params is not None: + server_url = utils.template_url(server_url, url_params) + + BaseSDK.__init__( + self, + SDKConfiguration( + client=client, + client_supplied=client_supplied, + async_client=async_client, + async_client_supplied=async_client_supplied, + security=security, + server_url=server_url, + server=server, + retry_config=retry_config, + timeout_ms=timeout_ms, + debug_logger=debug_logger, + ), + parent_ref=self, + ) + + hooks = SDKHooks() + + # pylint: disable=protected-access + self.sdk_configuration.__dict__["_hooks"] = hooks + + self.sdk_configuration = hooks.sdk_init(self.sdk_configuration) + + weakref.finalize( + self, + close_clients, + cast(ClientOwner, self.sdk_configuration), + self.sdk_configuration.client, + self.sdk_configuration.client_supplied, + self.sdk_configuration.async_client, + self.sdk_configuration.async_client_supplied, + ) + + def dynamic_import(self, modname, retries=3): + for attempt in range(retries): + try: + return importlib.import_module(modname) + except KeyError: + # Clear any half-initialized module and retry + sys.modules.pop(modname, None) + if attempt == retries - 1: + break + raise KeyError(f"Failed to import module '{modname}' after {retries} attempts") + + def __getattr__(self, name: str): + if name in self._sub_sdk_map: + module_path, class_name = self._sub_sdk_map[name] + try: + module = self.dynamic_import(module_path) + klass = getattr(module, class_name) + instance = klass(self.sdk_configuration, parent_ref=self) + setattr(self, name, instance) + return instance + except ImportError as e: + raise AttributeError( + f"Failed to import module {module_path} for attribute {name}: {e}" + ) from e + except AttributeError as e: + raise AttributeError( + f"Failed to find class {class_name} in module {module_path} for attribute {name}: {e}" + ) from e + + raise AttributeError( + f"'{type(self).__name__}' object has no attribute '{name}'" + ) + + def __dir__(self): + default_attrs = list(super().__dir__()) + lazy_attrs = list(self._sub_sdk_map.keys()) + return sorted(list(set(default_attrs + lazy_attrs))) + + def __enter__(self): + return self + + async def __aenter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if ( + self.sdk_configuration.client is not None + and not self.sdk_configuration.client_supplied + ): + self.sdk_configuration.client.close() + self.sdk_configuration.client = None + + async def __aexit__(self, exc_type, exc_val, exc_tb): + if ( + self.sdk_configuration.async_client is not None + and not self.sdk_configuration.async_client_supplied + ): + await self.sdk_configuration.async_client.aclose() + self.sdk_configuration.async_client = None diff --git a/src/openrouter/sdkconfiguration.py b/src/openrouter/sdkconfiguration.py new file mode 100644 index 0000000..e9d471c --- /dev/null +++ b/src/openrouter/sdkconfiguration.py @@ -0,0 +1,53 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from ._version import ( + __gen_version__, + __openapi_doc_version__, + __user_agent__, + __version__, +) +from .httpclient import AsyncHttpClient, HttpClient +from .utils import Logger, RetryConfig, remove_suffix +from dataclasses import dataclass +from openrouter import models +from openrouter.types import OptionalNullable, UNSET +from pydantic import Field +from typing import Callable, Dict, Optional, Tuple, Union + + +SERVER_PRODUCTION = "production" +r"""Production server""" +SERVERS = { + SERVER_PRODUCTION: "https://openrouter.ai/api/v1", +} +"""Contains the list of servers available to the SDK""" + + +@dataclass +class SDKConfiguration: + client: Union[HttpClient, None] + client_supplied: bool + async_client: Union[AsyncHttpClient, None] + async_client_supplied: bool + debug_logger: Logger + security: Optional[Union[models.Security, Callable[[], models.Security]]] = None + server_url: Optional[str] = "" + server: Optional[str] = "" + language: str = "python" + openapi_doc_version: str = __openapi_doc_version__ + sdk_version: str = __version__ + gen_version: str = __gen_version__ + user_agent: str = __user_agent__ + retry_config: OptionalNullable[RetryConfig] = Field(default_factory=lambda: UNSET) + timeout_ms: Optional[int] = None + + def get_server_details(self) -> Tuple[str, Dict[str, str]]: + if self.server_url is not None and self.server_url: + return remove_suffix(self.server_url, "/"), {} + if not self.server: + self.server = SERVER_PRODUCTION + + if self.server not in SERVERS: + raise ValueError(f'Invalid server "{self.server}"') + + return SERVERS[self.server], {} diff --git a/src/openrouter/types/__init__.py b/src/openrouter/types/__init__.py new file mode 100644 index 0000000..fc76fe0 --- /dev/null +++ b/src/openrouter/types/__init__.py @@ -0,0 +1,21 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from .basemodel import ( + BaseModel, + Nullable, + OptionalNullable, + UnrecognizedInt, + UnrecognizedStr, + UNSET, + UNSET_SENTINEL, +) + +__all__ = [ + "BaseModel", + "Nullable", + "OptionalNullable", + "UnrecognizedInt", + "UnrecognizedStr", + "UNSET", + "UNSET_SENTINEL", +] diff --git a/src/openrouter/types/basemodel.py b/src/openrouter/types/basemodel.py new file mode 100644 index 0000000..231c2e3 --- /dev/null +++ b/src/openrouter/types/basemodel.py @@ -0,0 +1,39 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from pydantic import ConfigDict, model_serializer +from pydantic import BaseModel as PydanticBaseModel +from typing import TYPE_CHECKING, Literal, Optional, TypeVar, Union +from typing_extensions import TypeAliasType, TypeAlias + + +class BaseModel(PydanticBaseModel): + model_config = ConfigDict( + populate_by_name=True, arbitrary_types_allowed=True, protected_namespaces=() + ) + + +class Unset(BaseModel): + @model_serializer(mode="plain") + def serialize_model(self): + return UNSET_SENTINEL + + def __bool__(self) -> Literal[False]: + return False + + +UNSET = Unset() +UNSET_SENTINEL = "~?~unset~?~sentinel~?~" + + +T = TypeVar("T") +if TYPE_CHECKING: + Nullable: TypeAlias = Union[T, None] + OptionalNullable: TypeAlias = Union[Optional[Nullable[T]], Unset] +else: + Nullable = TypeAliasType("Nullable", Union[T, None], type_params=(T,)) + OptionalNullable = TypeAliasType( + "OptionalNullable", Union[Optional[Nullable[T]], Unset], type_params=(T,) + ) + +UnrecognizedInt: TypeAlias = int +UnrecognizedStr: TypeAlias = str diff --git a/src/openrouter/utils/__init__.py b/src/openrouter/utils/__init__.py new file mode 100644 index 0000000..87192dd --- /dev/null +++ b/src/openrouter/utils/__init__.py @@ -0,0 +1,200 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from typing import TYPE_CHECKING +from importlib import import_module +import builtins +import sys + +if TYPE_CHECKING: + from .annotations import get_discriminator + from .datetimes import parse_datetime + from .enums import OpenEnumMeta + from .headers import get_headers, get_response_headers + from .metadata import ( + FieldMetadata, + find_metadata, + FormMetadata, + HeaderMetadata, + MultipartFormMetadata, + PathParamMetadata, + QueryParamMetadata, + RequestMetadata, + SecurityMetadata, + ) + from .queryparams import get_query_params + from .retries import BackoffStrategy, Retries, retry, retry_async, RetryConfig + from .requestbodies import serialize_request_body, SerializedRequestBody + from .security import get_security, get_security_from_env + + from .serializers import ( + get_pydantic_model, + marshal_json, + unmarshal, + unmarshal_json, + serialize_decimal, + serialize_float, + serialize_int, + stream_to_text, + stream_to_text_async, + stream_to_bytes, + stream_to_bytes_async, + validate_const, + validate_decimal, + validate_float, + validate_int, + validate_open_enum, + ) + from .url import generate_url, template_url, remove_suffix + from .values import ( + get_global_from_env, + match_content_type, + match_status_codes, + match_response, + cast_partial, + ) + from .logger import Logger, get_body_content, get_default_logger + +__all__ = [ + "BackoffStrategy", + "FieldMetadata", + "find_metadata", + "FormMetadata", + "generate_url", + "get_body_content", + "get_default_logger", + "get_discriminator", + "parse_datetime", + "get_global_from_env", + "get_headers", + "get_pydantic_model", + "get_query_params", + "get_response_headers", + "get_security", + "get_security_from_env", + "HeaderMetadata", + "Logger", + "marshal_json", + "match_content_type", + "match_status_codes", + "match_response", + "MultipartFormMetadata", + "OpenEnumMeta", + "PathParamMetadata", + "QueryParamMetadata", + "remove_suffix", + "Retries", + "retry", + "retry_async", + "RetryConfig", + "RequestMetadata", + "SecurityMetadata", + "serialize_decimal", + "serialize_float", + "serialize_int", + "serialize_request_body", + "SerializedRequestBody", + "stream_to_text", + "stream_to_text_async", + "stream_to_bytes", + "stream_to_bytes_async", + "template_url", + "unmarshal", + "unmarshal_json", + "validate_decimal", + "validate_const", + "validate_float", + "validate_int", + "validate_open_enum", + "cast_partial", +] + +_dynamic_imports: dict[str, str] = { + "BackoffStrategy": ".retries", + "FieldMetadata": ".metadata", + "find_metadata": ".metadata", + "FormMetadata": ".metadata", + "generate_url": ".url", + "get_body_content": ".logger", + "get_default_logger": ".logger", + "get_discriminator": ".annotations", + "parse_datetime": ".datetimes", + "get_global_from_env": ".values", + "get_headers": ".headers", + "get_pydantic_model": ".serializers", + "get_query_params": ".queryparams", + "get_response_headers": ".headers", + "get_security": ".security", + "get_security_from_env": ".security", + "HeaderMetadata": ".metadata", + "Logger": ".logger", + "marshal_json": ".serializers", + "match_content_type": ".values", + "match_status_codes": ".values", + "match_response": ".values", + "MultipartFormMetadata": ".metadata", + "OpenEnumMeta": ".enums", + "PathParamMetadata": ".metadata", + "QueryParamMetadata": ".metadata", + "remove_suffix": ".url", + "Retries": ".retries", + "retry": ".retries", + "retry_async": ".retries", + "RetryConfig": ".retries", + "RequestMetadata": ".metadata", + "SecurityMetadata": ".metadata", + "serialize_decimal": ".serializers", + "serialize_float": ".serializers", + "serialize_int": ".serializers", + "serialize_request_body": ".requestbodies", + "SerializedRequestBody": ".requestbodies", + "stream_to_text": ".serializers", + "stream_to_text_async": ".serializers", + "stream_to_bytes": ".serializers", + "stream_to_bytes_async": ".serializers", + "template_url": ".url", + "unmarshal": ".serializers", + "unmarshal_json": ".serializers", + "validate_decimal": ".serializers", + "validate_const": ".serializers", + "validate_float": ".serializers", + "validate_int": ".serializers", + "validate_open_enum": ".serializers", + "cast_partial": ".values", +} + + +def dynamic_import(modname, retries=3): + for attempt in range(retries): + try: + return import_module(modname, __package__) + except KeyError: + # Clear any half-initialized module and retry + sys.modules.pop(modname, None) + if attempt == retries - 1: + break + raise KeyError(f"Failed to import module '{modname}' after {retries} attempts") + + +def __getattr__(attr_name: str) -> object: + module_name = _dynamic_imports.get(attr_name) + if module_name is None: + raise AttributeError( + f"no {attr_name} found in _dynamic_imports, module name -> {__name__} " + ) + + try: + module = dynamic_import(module_name) + return getattr(module, attr_name) + except ImportError as e: + raise ImportError( + f"Failed to import {attr_name} from {module_name}: {e}" + ) from e + except AttributeError as e: + raise AttributeError( + f"Failed to get {attr_name} from {module_name}: {e}" + ) from e + + +def __dir__(): + lazy_attrs = builtins.list(_dynamic_imports.keys()) + return builtins.sorted(lazy_attrs) diff --git a/src/openrouter/utils/annotations.py b/src/openrouter/utils/annotations.py new file mode 100644 index 0000000..12e0aa4 --- /dev/null +++ b/src/openrouter/utils/annotations.py @@ -0,0 +1,79 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from enum import Enum +from typing import Any, Optional + + +def get_discriminator(model: Any, fieldname: str, key: str) -> str: + """ + Recursively search for the discriminator attribute in a model. + + Args: + model (Any): The model to search within. + fieldname (str): The name of the field to search for. + key (str): The key to search for in dictionaries. + + Returns: + str: The name of the discriminator attribute. + + Raises: + ValueError: If the discriminator attribute is not found. + """ + upper_fieldname = fieldname.upper() + + def get_field_discriminator(field: Any) -> Optional[str]: + """Search for the discriminator attribute in a given field.""" + + if isinstance(field, dict): + if key in field: + return f"{field[key]}" + + if hasattr(field, fieldname): + attr = getattr(field, fieldname) + if isinstance(attr, Enum): + return f"{attr.value}" + return f"{attr}" + + if hasattr(field, upper_fieldname): + attr = getattr(field, upper_fieldname) + if isinstance(attr, Enum): + return f"{attr.value}" + return f"{attr}" + + return None + + def search_nested_discriminator(obj: Any) -> Optional[str]: + """Recursively search for discriminator in nested structures.""" + # First try direct field lookup + discriminator = get_field_discriminator(obj) + if discriminator is not None: + return discriminator + + # If it's a dict, search in nested values + if isinstance(obj, dict): + for value in obj.values(): + if isinstance(value, list): + # Search in list items + for item in value: + nested_discriminator = search_nested_discriminator(item) + if nested_discriminator is not None: + return nested_discriminator + elif isinstance(value, dict): + # Search in nested dict + nested_discriminator = search_nested_discriminator(value) + if nested_discriminator is not None: + return nested_discriminator + + return None + + if isinstance(model, list): + for field in model: + discriminator = search_nested_discriminator(field) + if discriminator is not None: + return discriminator + + discriminator = search_nested_discriminator(model) + if discriminator is not None: + return discriminator + + raise ValueError(f"Could not find discriminator field {fieldname} in {model}") diff --git a/src/openrouter/utils/datetimes.py b/src/openrouter/utils/datetimes.py new file mode 100644 index 0000000..a6c52cd --- /dev/null +++ b/src/openrouter/utils/datetimes.py @@ -0,0 +1,23 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from datetime import datetime +import sys + + +def parse_datetime(datetime_string: str) -> datetime: + """ + Convert a RFC 3339 / ISO 8601 formatted string into a datetime object. + Python versions 3.11 and later support parsing RFC 3339 directly with + datetime.fromisoformat(), but for earlier versions, this function + encapsulates the necessary extra logic. + """ + # Python 3.11 and later can parse RFC 3339 directly + if sys.version_info >= (3, 11): + return datetime.fromisoformat(datetime_string) + + # For Python 3.10 and earlier, a common ValueError is trailing 'Z' suffix, + # so fix that upfront. + if datetime_string.endswith("Z"): + datetime_string = datetime_string[:-1] + "+00:00" + + return datetime.fromisoformat(datetime_string) diff --git a/src/openrouter/utils/enums.py b/src/openrouter/utils/enums.py new file mode 100644 index 0000000..c3bc13c --- /dev/null +++ b/src/openrouter/utils/enums.py @@ -0,0 +1,74 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +import enum +import sys + +class OpenEnumMeta(enum.EnumMeta): + # The __call__ method `boundary` kwarg was added in 3.11 and must be present + # for pyright. Refer also: https://github.com/pylint-dev/pylint/issues/9622 + # pylint: disable=unexpected-keyword-arg + # The __call__ method `values` varg must be named for pyright. + # pylint: disable=keyword-arg-before-vararg + + if sys.version_info >= (3, 11): + def __call__( + cls, value, names=None, *values, module=None, qualname=None, type=None, start=1, boundary=None + ): + # The `type` kwarg also happens to be a built-in that pylint flags as + # redeclared. Safe to ignore this lint rule with this scope. + # pylint: disable=redefined-builtin + + if names is not None: + return super().__call__( + value, + names=names, + *values, + module=module, + qualname=qualname, + type=type, + start=start, + boundary=boundary, + ) + + try: + return super().__call__( + value, + names=names, # pyright: ignore[reportArgumentType] + *values, + module=module, + qualname=qualname, + type=type, + start=start, + boundary=boundary, + ) + except ValueError: + return value + else: + def __call__( + cls, value, names=None, *, module=None, qualname=None, type=None, start=1 + ): + # The `type` kwarg also happens to be a built-in that pylint flags as + # redeclared. Safe to ignore this lint rule with this scope. + # pylint: disable=redefined-builtin + + if names is not None: + return super().__call__( + value, + names=names, + module=module, + qualname=qualname, + type=type, + start=start, + ) + + try: + return super().__call__( + value, + names=names, # pyright: ignore[reportArgumentType] + module=module, + qualname=qualname, + type=type, + start=start, + ) + except ValueError: + return value diff --git a/src/openrouter/utils/eventstreaming.py b/src/openrouter/utils/eventstreaming.py new file mode 100644 index 0000000..0969899 --- /dev/null +++ b/src/openrouter/utils/eventstreaming.py @@ -0,0 +1,248 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +import re +import json +from typing import ( + Callable, + Generic, + TypeVar, + Optional, + Generator, + AsyncGenerator, + Tuple, +) +import httpx + +T = TypeVar("T") + + +class EventStream(Generic[T]): + # Holds a reference to the SDK client to avoid it being garbage collected + # and cause termination of the underlying httpx client. + client_ref: Optional[object] + response: httpx.Response + generator: Generator[T, None, None] + + def __init__( + self, + response: httpx.Response, + decoder: Callable[[str], T], + sentinel: Optional[str] = None, + client_ref: Optional[object] = None, + ): + self.response = response + self.generator = stream_events(response, decoder, sentinel) + self.client_ref = client_ref + + def __iter__(self): + return self + + def __next__(self): + return next(self.generator) + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.response.close() + + +class EventStreamAsync(Generic[T]): + # Holds a reference to the SDK client to avoid it being garbage collected + # and cause termination of the underlying httpx client. + client_ref: Optional[object] + response: httpx.Response + generator: AsyncGenerator[T, None] + + def __init__( + self, + response: httpx.Response, + decoder: Callable[[str], T], + sentinel: Optional[str] = None, + client_ref: Optional[object] = None, + ): + self.response = response + self.generator = stream_events_async(response, decoder, sentinel) + self.client_ref = client_ref + + def __aiter__(self): + return self + + async def __anext__(self): + return await self.generator.__anext__() + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc_val, exc_tb): + await self.response.aclose() + + +class ServerEvent: + id: Optional[str] = None + event: Optional[str] = None + data: Optional[str] = None + retry: Optional[int] = None + + +MESSAGE_BOUNDARIES = [ + b"\r\n\r\n", + b"\n\n", + b"\r\r", +] + + +async def stream_events_async( + response: httpx.Response, + decoder: Callable[[str], T], + sentinel: Optional[str] = None, +) -> AsyncGenerator[T, None]: + buffer = bytearray() + position = 0 + discard = False + async for chunk in response.aiter_bytes(): + # We've encountered the sentinel value and should no longer process + # incoming data. Instead we throw new data away until the server closes + # the connection. + if discard: + continue + + buffer += chunk + for i in range(position, len(buffer)): + char = buffer[i : i + 1] + seq: Optional[bytes] = None + if char in [b"\r", b"\n"]: + for boundary in MESSAGE_BOUNDARIES: + seq = _peek_sequence(i, buffer, boundary) + if seq is not None: + break + if seq is None: + continue + + block = buffer[position:i] + position = i + len(seq) + event, discard = _parse_event(block, decoder, sentinel) + if event is not None: + yield event + + if position > 0: + buffer = buffer[position:] + position = 0 + + event, discard = _parse_event(buffer, decoder, sentinel) + if event is not None: + yield event + + +def stream_events( + response: httpx.Response, + decoder: Callable[[str], T], + sentinel: Optional[str] = None, +) -> Generator[T, None, None]: + buffer = bytearray() + position = 0 + discard = False + for chunk in response.iter_bytes(): + # We've encountered the sentinel value and should no longer process + # incoming data. Instead we throw new data away until the server closes + # the connection. + if discard: + continue + + buffer += chunk + for i in range(position, len(buffer)): + char = buffer[i : i + 1] + seq: Optional[bytes] = None + if char in [b"\r", b"\n"]: + for boundary in MESSAGE_BOUNDARIES: + seq = _peek_sequence(i, buffer, boundary) + if seq is not None: + break + if seq is None: + continue + + block = buffer[position:i] + position = i + len(seq) + event, discard = _parse_event(block, decoder, sentinel) + if event is not None: + yield event + + if position > 0: + buffer = buffer[position:] + position = 0 + + event, discard = _parse_event(buffer, decoder, sentinel) + if event is not None: + yield event + + +def _parse_event( + raw: bytearray, decoder: Callable[[str], T], sentinel: Optional[str] = None +) -> Tuple[Optional[T], bool]: + block = raw.decode() + lines = re.split(r"\r?\n|\r", block) + publish = False + event = ServerEvent() + data = "" + for line in lines: + if not line: + continue + + delim = line.find(":") + if delim <= 0: + continue + + field = line[0:delim] + value = line[delim + 1 :] if delim < len(line) - 1 else "" + if len(value) and value[0] == " ": + value = value[1:] + + if field == "event": + event.event = value + publish = True + elif field == "data": + data += value + "\n" + publish = True + elif field == "id": + event.id = value + publish = True + elif field == "retry": + event.retry = int(value) if value.isdigit() else None + publish = True + + if sentinel and data == f"{sentinel}\n": + return None, True + + if data: + data = data[:-1] + event.data = data + + data_is_primitive = ( + data.isnumeric() or data == "true" or data == "false" or data == "null" + ) + data_is_json = ( + data.startswith("{") or data.startswith("[") or data.startswith('"') + ) + + if data_is_primitive or data_is_json: + try: + event.data = json.loads(data) + except Exception: + pass + + out = None + if publish: + out = decoder(json.dumps(event.__dict__)) + + return out, False + + +def _peek_sequence(position: int, buffer: bytearray, sequence: bytes): + if len(sequence) > (len(buffer) - position): + return None + + for i, seq in enumerate(sequence): + if buffer[position + i] != seq: + return None + + return sequence diff --git a/src/openrouter/utils/forms.py b/src/openrouter/utils/forms.py new file mode 100644 index 0000000..e873495 --- /dev/null +++ b/src/openrouter/utils/forms.py @@ -0,0 +1,223 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from typing import ( + Any, + Dict, + get_type_hints, + List, + Tuple, +) +from pydantic import BaseModel +from pydantic.fields import FieldInfo + +from .serializers import marshal_json + +from .metadata import ( + FormMetadata, + MultipartFormMetadata, + find_field_metadata, +) +from .values import _is_set, _val_to_string + + +def _populate_form( + field_name: str, + explode: bool, + obj: Any, + delimiter: str, + form: Dict[str, List[str]], +): + if not _is_set(obj): + return form + + if isinstance(obj, BaseModel): + items = [] + + obj_fields: Dict[str, FieldInfo] = obj.__class__.model_fields + for name in obj_fields: + obj_field = obj_fields[name] + obj_field_name = obj_field.alias if obj_field.alias is not None else name + if obj_field_name == "": + continue + + val = getattr(obj, name) + if not _is_set(val): + continue + + if explode: + form[obj_field_name] = [_val_to_string(val)] + else: + items.append(f"{obj_field_name}{delimiter}{_val_to_string(val)}") + + if len(items) > 0: + form[field_name] = [delimiter.join(items)] + elif isinstance(obj, Dict): + items = [] + for key, value in obj.items(): + if not _is_set(value): + continue + + if explode: + form[key] = [_val_to_string(value)] + else: + items.append(f"{key}{delimiter}{_val_to_string(value)}") + + if len(items) > 0: + form[field_name] = [delimiter.join(items)] + elif isinstance(obj, List): + items = [] + + for value in obj: + if not _is_set(value): + continue + + if explode: + if not field_name in form: + form[field_name] = [] + form[field_name].append(_val_to_string(value)) + else: + items.append(_val_to_string(value)) + + if len(items) > 0: + form[field_name] = [delimiter.join([str(item) for item in items])] + else: + form[field_name] = [_val_to_string(obj)] + + return form + + +def _extract_file_properties(file_obj: Any) -> Tuple[str, Any, Any]: + """Extract file name, content, and content type from a file object.""" + file_fields: Dict[str, FieldInfo] = file_obj.__class__.model_fields + + file_name = "" + content = None + content_type = None + + for file_field_name in file_fields: + file_field = file_fields[file_field_name] + + file_metadata = find_field_metadata(file_field, MultipartFormMetadata) + if file_metadata is None: + continue + + if file_metadata.content: + content = getattr(file_obj, file_field_name, None) + elif file_field_name == "content_type": + content_type = getattr(file_obj, file_field_name, None) + else: + file_name = getattr(file_obj, file_field_name) + + if file_name == "" or content is None: + raise ValueError("invalid multipart/form-data file") + + return file_name, content, content_type + + +def serialize_multipart_form( + media_type: str, request: Any +) -> Tuple[str, Dict[str, Any], List[Tuple[str, Any]]]: + form: Dict[str, Any] = {} + files: List[Tuple[str, Any]] = [] + + if not isinstance(request, BaseModel): + raise TypeError("invalid request body type") + + request_fields: Dict[str, FieldInfo] = request.__class__.model_fields + request_field_types = get_type_hints(request.__class__) + + for name in request_fields: + field = request_fields[name] + + val = getattr(request, name) + if not _is_set(val): + continue + + field_metadata = find_field_metadata(field, MultipartFormMetadata) + if not field_metadata: + continue + + f_name = field.alias if field.alias else name + + if field_metadata.file: + if isinstance(val, List): + # Handle array of files + for file_obj in val: + if not _is_set(file_obj): + continue + + file_name, content, content_type = _extract_file_properties(file_obj) + + if content_type is not None: + files.append((f_name + "[]", (file_name, content, content_type))) + else: + files.append((f_name + "[]", (file_name, content))) + else: + # Handle single file + file_name, content, content_type = _extract_file_properties(val) + + if content_type is not None: + files.append((f_name, (file_name, content, content_type))) + else: + files.append((f_name, (file_name, content))) + elif field_metadata.json: + files.append((f_name, ( + None, + marshal_json(val, request_field_types[name]), + "application/json", + ))) + else: + if isinstance(val, List): + values = [] + + for value in val: + if not _is_set(value): + continue + values.append(_val_to_string(value)) + + form[f_name + "[]"] = values + else: + form[f_name] = _val_to_string(val) + return media_type, form, files + + +def serialize_form_data(data: Any) -> Dict[str, Any]: + form: Dict[str, List[str]] = {} + + if isinstance(data, BaseModel): + data_fields: Dict[str, FieldInfo] = data.__class__.model_fields + data_field_types = get_type_hints(data.__class__) + for name in data_fields: + field = data_fields[name] + + val = getattr(data, name) + if not _is_set(val): + continue + + metadata = find_field_metadata(field, FormMetadata) + if metadata is None: + continue + + f_name = field.alias if field.alias is not None else name + + if metadata.json: + form[f_name] = [marshal_json(val, data_field_types[name])] + else: + if metadata.style == "form": + _populate_form( + f_name, + metadata.explode, + val, + ",", + form, + ) + else: + raise ValueError(f"Invalid form style for field {name}") + elif isinstance(data, Dict): + for key, value in data.items(): + if _is_set(value): + form[key] = [_val_to_string(value)] + else: + raise TypeError(f"Invalid request body type {type(data)} for form data") + + return form diff --git a/src/openrouter/utils/headers.py b/src/openrouter/utils/headers.py new file mode 100644 index 0000000..37864cb --- /dev/null +++ b/src/openrouter/utils/headers.py @@ -0,0 +1,136 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from typing import ( + Any, + Dict, + List, + Optional, +) +from httpx import Headers +from pydantic import BaseModel +from pydantic.fields import FieldInfo + +from .metadata import ( + HeaderMetadata, + find_field_metadata, +) + +from .values import _is_set, _populate_from_globals, _val_to_string + + +def get_headers(headers_params: Any, gbls: Optional[Any] = None) -> Dict[str, str]: + headers: Dict[str, str] = {} + + globals_already_populated = [] + if _is_set(headers_params): + globals_already_populated = _populate_headers(headers_params, gbls, headers, []) + if _is_set(gbls): + _populate_headers(gbls, None, headers, globals_already_populated) + + return headers + + +def _populate_headers( + headers_params: Any, + gbls: Any, + header_values: Dict[str, str], + skip_fields: List[str], +) -> List[str]: + globals_already_populated: List[str] = [] + + if not isinstance(headers_params, BaseModel): + return globals_already_populated + + param_fields: Dict[str, FieldInfo] = headers_params.__class__.model_fields + for name in param_fields: + if name in skip_fields: + continue + + field = param_fields[name] + f_name = field.alias if field.alias is not None else name + + metadata = find_field_metadata(field, HeaderMetadata) + if metadata is None: + continue + + value, global_found = _populate_from_globals( + name, getattr(headers_params, name), HeaderMetadata, gbls + ) + if global_found: + globals_already_populated.append(name) + value = _serialize_header(metadata.explode, value) + + if value != "": + header_values[f_name] = value + + return globals_already_populated + + +def _serialize_header(explode: bool, obj: Any) -> str: + if not _is_set(obj): + return "" + + if isinstance(obj, BaseModel): + items = [] + obj_fields: Dict[str, FieldInfo] = obj.__class__.model_fields + for name in obj_fields: + obj_field = obj_fields[name] + obj_param_metadata = find_field_metadata(obj_field, HeaderMetadata) + + if not obj_param_metadata: + continue + + f_name = obj_field.alias if obj_field.alias is not None else name + + val = getattr(obj, name) + if not _is_set(val): + continue + + if explode: + items.append(f"{f_name}={_val_to_string(val)}") + else: + items.append(f_name) + items.append(_val_to_string(val)) + + if len(items) > 0: + return ",".join(items) + elif isinstance(obj, Dict): + items = [] + + for key, value in obj.items(): + if not _is_set(value): + continue + + if explode: + items.append(f"{key}={_val_to_string(value)}") + else: + items.append(key) + items.append(_val_to_string(value)) + + if len(items) > 0: + return ",".join([str(item) for item in items]) + elif isinstance(obj, List): + items = [] + + for value in obj: + if not _is_set(value): + continue + + items.append(_val_to_string(value)) + + if len(items) > 0: + return ",".join(items) + elif _is_set(obj): + return f"{_val_to_string(obj)}" + + return "" + + +def get_response_headers(headers: Headers) -> Dict[str, List[str]]: + res: Dict[str, List[str]] = {} + for k, v in headers.items(): + if not k in res: + res[k] = [] + + res[k].append(v) + return res diff --git a/src/openrouter/utils/logger.py b/src/openrouter/utils/logger.py new file mode 100644 index 0000000..db55cd3 --- /dev/null +++ b/src/openrouter/utils/logger.py @@ -0,0 +1,27 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +import httpx +import logging +import os +from typing import Any, Protocol + + +class Logger(Protocol): + def debug(self, msg: str, *args: Any, **kwargs: Any) -> None: + pass + + +class NoOpLogger: + def debug(self, msg: str, *args: Any, **kwargs: Any) -> None: + pass + + +def get_body_content(req: httpx.Request) -> str: + return "" if not hasattr(req, "_content") else str(req.content) + + +def get_default_logger() -> Logger: + if os.getenv("OPENROUTER_DEBUG"): + logging.basicConfig(level=logging.DEBUG) + return logging.getLogger("openrouter") + return NoOpLogger() diff --git a/src/openrouter/utils/metadata.py b/src/openrouter/utils/metadata.py new file mode 100644 index 0000000..173b3e5 --- /dev/null +++ b/src/openrouter/utils/metadata.py @@ -0,0 +1,118 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from typing import Optional, Type, TypeVar, Union +from dataclasses import dataclass +from pydantic.fields import FieldInfo + + +T = TypeVar("T") + + +@dataclass +class SecurityMetadata: + option: bool = False + scheme: bool = False + scheme_type: Optional[str] = None + sub_type: Optional[str] = None + field_name: Optional[str] = None + + def get_field_name(self, default: str) -> str: + return self.field_name or default + + +@dataclass +class ParamMetadata: + serialization: Optional[str] = None + style: str = "simple" + explode: bool = False + + +@dataclass +class PathParamMetadata(ParamMetadata): + pass + + +@dataclass +class QueryParamMetadata(ParamMetadata): + style: str = "form" + explode: bool = True + + +@dataclass +class HeaderMetadata(ParamMetadata): + pass + + +@dataclass +class RequestMetadata: + media_type: str = "application/octet-stream" + + +@dataclass +class MultipartFormMetadata: + file: bool = False + content: bool = False + json: bool = False + + +@dataclass +class FormMetadata: + json: bool = False + style: str = "form" + explode: bool = True + + +class FieldMetadata: + security: Optional[SecurityMetadata] = None + path: Optional[PathParamMetadata] = None + query: Optional[QueryParamMetadata] = None + header: Optional[HeaderMetadata] = None + request: Optional[RequestMetadata] = None + form: Optional[FormMetadata] = None + multipart: Optional[MultipartFormMetadata] = None + + def __init__( + self, + security: Optional[SecurityMetadata] = None, + path: Optional[Union[PathParamMetadata, bool]] = None, + query: Optional[Union[QueryParamMetadata, bool]] = None, + header: Optional[Union[HeaderMetadata, bool]] = None, + request: Optional[Union[RequestMetadata, bool]] = None, + form: Optional[Union[FormMetadata, bool]] = None, + multipart: Optional[Union[MultipartFormMetadata, bool]] = None, + ): + self.security = security + self.path = PathParamMetadata() if isinstance(path, bool) else path + self.query = QueryParamMetadata() if isinstance(query, bool) else query + self.header = HeaderMetadata() if isinstance(header, bool) else header + self.request = RequestMetadata() if isinstance(request, bool) else request + self.form = FormMetadata() if isinstance(form, bool) else form + self.multipart = ( + MultipartFormMetadata() if isinstance(multipart, bool) else multipart + ) + + +def find_field_metadata(field_info: FieldInfo, metadata_type: Type[T]) -> Optional[T]: + metadata = find_metadata(field_info, FieldMetadata) + if not metadata: + return None + + fields = metadata.__dict__ + + for field in fields: + if isinstance(fields[field], metadata_type): + return fields[field] + + return None + + +def find_metadata(field_info: FieldInfo, metadata_type: Type[T]) -> Optional[T]: + metadata = field_info.metadata + if not metadata: + return None + + for md in metadata: + if isinstance(md, metadata_type): + return md + + return None diff --git a/src/openrouter/utils/queryparams.py b/src/openrouter/utils/queryparams.py new file mode 100644 index 0000000..37a6e7f --- /dev/null +++ b/src/openrouter/utils/queryparams.py @@ -0,0 +1,205 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from typing import ( + Any, + Dict, + get_type_hints, + List, + Optional, +) + +from pydantic import BaseModel +from pydantic.fields import FieldInfo + +from .metadata import ( + QueryParamMetadata, + find_field_metadata, +) +from .values import ( + _get_serialized_params, + _is_set, + _populate_from_globals, + _val_to_string, +) +from .forms import _populate_form + + +def get_query_params( + query_params: Any, + gbls: Optional[Any] = None, +) -> Dict[str, List[str]]: + params: Dict[str, List[str]] = {} + + globals_already_populated = _populate_query_params(query_params, gbls, params, []) + if _is_set(gbls): + _populate_query_params(gbls, None, params, globals_already_populated) + + return params + + +def _populate_query_params( + query_params: Any, + gbls: Any, + query_param_values: Dict[str, List[str]], + skip_fields: List[str], +) -> List[str]: + globals_already_populated: List[str] = [] + + if not isinstance(query_params, BaseModel): + return globals_already_populated + + param_fields: Dict[str, FieldInfo] = query_params.__class__.model_fields + param_field_types = get_type_hints(query_params.__class__) + for name in param_fields: + if name in skip_fields: + continue + + field = param_fields[name] + + metadata = find_field_metadata(field, QueryParamMetadata) + if not metadata: + continue + + value = getattr(query_params, name) if _is_set(query_params) else None + + value, global_found = _populate_from_globals( + name, value, QueryParamMetadata, gbls + ) + if global_found: + globals_already_populated.append(name) + + f_name = field.alias if field.alias is not None else name + serialization = metadata.serialization + if serialization is not None: + serialized_parms = _get_serialized_params( + metadata, f_name, value, param_field_types[name] + ) + for key, value in serialized_parms.items(): + if key in query_param_values: + query_param_values[key].extend(value) + else: + query_param_values[key] = [value] + else: + style = metadata.style + if style == "deepObject": + _populate_deep_object_query_params(f_name, value, query_param_values) + elif style == "form": + _populate_delimited_query_params( + metadata, f_name, value, ",", query_param_values + ) + elif style == "pipeDelimited": + _populate_delimited_query_params( + metadata, f_name, value, "|", query_param_values + ) + else: + raise NotImplementedError( + f"query param style {style} not yet supported" + ) + + return globals_already_populated + + +def _populate_deep_object_query_params( + field_name: str, + obj: Any, + params: Dict[str, List[str]], +): + if not _is_set(obj): + return + + if isinstance(obj, BaseModel): + _populate_deep_object_query_params_basemodel(field_name, obj, params) + elif isinstance(obj, Dict): + _populate_deep_object_query_params_dict(field_name, obj, params) + + +def _populate_deep_object_query_params_basemodel( + prior_params_key: str, + obj: Any, + params: Dict[str, List[str]], +): + if not _is_set(obj) or not isinstance(obj, BaseModel): + return + + obj_fields: Dict[str, FieldInfo] = obj.__class__.model_fields + for name in obj_fields: + obj_field = obj_fields[name] + + f_name = obj_field.alias if obj_field.alias is not None else name + + params_key = f"{prior_params_key}[{f_name}]" + + obj_param_metadata = find_field_metadata(obj_field, QueryParamMetadata) + if not _is_set(obj_param_metadata): + continue + + obj_val = getattr(obj, name) + if not _is_set(obj_val): + continue + + if isinstance(obj_val, BaseModel): + _populate_deep_object_query_params_basemodel(params_key, obj_val, params) + elif isinstance(obj_val, Dict): + _populate_deep_object_query_params_dict(params_key, obj_val, params) + elif isinstance(obj_val, List): + _populate_deep_object_query_params_list(params_key, obj_val, params) + else: + params[params_key] = [_val_to_string(obj_val)] + + +def _populate_deep_object_query_params_dict( + prior_params_key: str, + value: Dict, + params: Dict[str, List[str]], +): + if not _is_set(value): + return + + for key, val in value.items(): + if not _is_set(val): + continue + + params_key = f"{prior_params_key}[{key}]" + + if isinstance(val, BaseModel): + _populate_deep_object_query_params_basemodel(params_key, val, params) + elif isinstance(val, Dict): + _populate_deep_object_query_params_dict(params_key, val, params) + elif isinstance(val, List): + _populate_deep_object_query_params_list(params_key, val, params) + else: + params[params_key] = [_val_to_string(val)] + + +def _populate_deep_object_query_params_list( + params_key: str, + value: List, + params: Dict[str, List[str]], +): + if not _is_set(value): + return + + for val in value: + if not _is_set(val): + continue + + if params.get(params_key) is None: + params[params_key] = [] + + params[params_key].append(_val_to_string(val)) + + +def _populate_delimited_query_params( + metadata: QueryParamMetadata, + field_name: str, + obj: Any, + delimiter: str, + query_param_values: Dict[str, List[str]], +): + _populate_form( + field_name, + metadata.explode, + obj, + delimiter, + query_param_values, + ) diff --git a/src/openrouter/utils/requestbodies.py b/src/openrouter/utils/requestbodies.py new file mode 100644 index 0000000..d5240dd --- /dev/null +++ b/src/openrouter/utils/requestbodies.py @@ -0,0 +1,66 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +import io +from dataclasses import dataclass +import re +from typing import ( + Any, + Optional, +) + +from .forms import serialize_form_data, serialize_multipart_form + +from .serializers import marshal_json + +SERIALIZATION_METHOD_TO_CONTENT_TYPE = { + "json": "application/json", + "form": "application/x-www-form-urlencoded", + "multipart": "multipart/form-data", + "raw": "application/octet-stream", + "string": "text/plain", +} + + +@dataclass +class SerializedRequestBody: + media_type: Optional[str] = None + content: Optional[Any] = None + data: Optional[Any] = None + files: Optional[Any] = None + + +def serialize_request_body( + request_body: Any, + nullable: bool, + optional: bool, + serialization_method: str, + request_body_type, +) -> Optional[SerializedRequestBody]: + if request_body is None: + if not nullable and optional: + return None + + media_type = SERIALIZATION_METHOD_TO_CONTENT_TYPE[serialization_method] + + serialized_request_body = SerializedRequestBody(media_type) + + if re.match(r"(application|text)\/.*?\+*json.*", media_type) is not None: + serialized_request_body.content = marshal_json(request_body, request_body_type) + elif re.match(r"multipart\/.*", media_type) is not None: + ( + serialized_request_body.media_type, + serialized_request_body.data, + serialized_request_body.files, + ) = serialize_multipart_form(media_type, request_body) + elif re.match(r"application\/x-www-form-urlencoded.*", media_type) is not None: + serialized_request_body.data = serialize_form_data(request_body) + elif isinstance(request_body, (bytes, bytearray, io.BytesIO, io.BufferedReader)): + serialized_request_body.content = request_body + elif isinstance(request_body, str): + serialized_request_body.content = request_body + else: + raise TypeError( + f"invalid request body type {type(request_body)} for mediaType {media_type}" + ) + + return serialized_request_body diff --git a/src/openrouter/utils/retries.py b/src/openrouter/utils/retries.py new file mode 100644 index 0000000..4d60867 --- /dev/null +++ b/src/openrouter/utils/retries.py @@ -0,0 +1,217 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +import asyncio +import random +import time +from typing import List + +import httpx + + +class BackoffStrategy: + initial_interval: int + max_interval: int + exponent: float + max_elapsed_time: int + + def __init__( + self, + initial_interval: int, + max_interval: int, + exponent: float, + max_elapsed_time: int, + ): + self.initial_interval = initial_interval + self.max_interval = max_interval + self.exponent = exponent + self.max_elapsed_time = max_elapsed_time + + +class RetryConfig: + strategy: str + backoff: BackoffStrategy + retry_connection_errors: bool + + def __init__( + self, strategy: str, backoff: BackoffStrategy, retry_connection_errors: bool + ): + self.strategy = strategy + self.backoff = backoff + self.retry_connection_errors = retry_connection_errors + + +class Retries: + config: RetryConfig + status_codes: List[str] + + def __init__(self, config: RetryConfig, status_codes: List[str]): + self.config = config + self.status_codes = status_codes + + +class TemporaryError(Exception): + response: httpx.Response + + def __init__(self, response: httpx.Response): + self.response = response + + +class PermanentError(Exception): + inner: Exception + + def __init__(self, inner: Exception): + self.inner = inner + + +def retry(func, retries: Retries): + if retries.config.strategy == "backoff": + + def do_request() -> httpx.Response: + res: httpx.Response + try: + res = func() + + for code in retries.status_codes: + if "X" in code.upper(): + code_range = int(code[0]) + + status_major = res.status_code / 100 + + if code_range <= status_major < code_range + 1: + raise TemporaryError(res) + else: + parsed_code = int(code) + + if res.status_code == parsed_code: + raise TemporaryError(res) + except httpx.ConnectError as exception: + if retries.config.retry_connection_errors: + raise + + raise PermanentError(exception) from exception + except httpx.TimeoutException as exception: + if retries.config.retry_connection_errors: + raise + + raise PermanentError(exception) from exception + except TemporaryError: + raise + except Exception as exception: + raise PermanentError(exception) from exception + + return res + + return retry_with_backoff( + do_request, + retries.config.backoff.initial_interval, + retries.config.backoff.max_interval, + retries.config.backoff.exponent, + retries.config.backoff.max_elapsed_time, + ) + + return func() + + +async def retry_async(func, retries: Retries): + if retries.config.strategy == "backoff": + + async def do_request() -> httpx.Response: + res: httpx.Response + try: + res = await func() + + for code in retries.status_codes: + if "X" in code.upper(): + code_range = int(code[0]) + + status_major = res.status_code / 100 + + if code_range <= status_major < code_range + 1: + raise TemporaryError(res) + else: + parsed_code = int(code) + + if res.status_code == parsed_code: + raise TemporaryError(res) + except httpx.ConnectError as exception: + if retries.config.retry_connection_errors: + raise + + raise PermanentError(exception) from exception + except httpx.TimeoutException as exception: + if retries.config.retry_connection_errors: + raise + + raise PermanentError(exception) from exception + except TemporaryError: + raise + except Exception as exception: + raise PermanentError(exception) from exception + + return res + + return await retry_with_backoff_async( + do_request, + retries.config.backoff.initial_interval, + retries.config.backoff.max_interval, + retries.config.backoff.exponent, + retries.config.backoff.max_elapsed_time, + ) + + return await func() + + +def retry_with_backoff( + func, + initial_interval=500, + max_interval=60000, + exponent=1.5, + max_elapsed_time=3600000, +): + start = round(time.time() * 1000) + retries = 0 + + while True: + try: + return func() + except PermanentError as exception: + raise exception.inner + except Exception as exception: # pylint: disable=broad-exception-caught + now = round(time.time() * 1000) + if now - start > max_elapsed_time: + if isinstance(exception, TemporaryError): + return exception.response + + raise + sleep = (initial_interval / 1000) * exponent**retries + random.uniform(0, 1) + sleep = min(sleep, max_interval / 1000) + time.sleep(sleep) + retries += 1 + + +async def retry_with_backoff_async( + func, + initial_interval=500, + max_interval=60000, + exponent=1.5, + max_elapsed_time=3600000, +): + start = round(time.time() * 1000) + retries = 0 + + while True: + try: + return await func() + except PermanentError as exception: + raise exception.inner + except Exception as exception: # pylint: disable=broad-exception-caught + now = round(time.time() * 1000) + if now - start > max_elapsed_time: + if isinstance(exception, TemporaryError): + return exception.response + + raise + sleep = (initial_interval / 1000) * exponent**retries + random.uniform(0, 1) + sleep = min(sleep, max_interval / 1000) + await asyncio.sleep(sleep) + retries += 1 diff --git a/src/openrouter/utils/security.py b/src/openrouter/utils/security.py new file mode 100644 index 0000000..6996c79 --- /dev/null +++ b/src/openrouter/utils/security.py @@ -0,0 +1,192 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +import base64 + +from typing import ( + Any, + Dict, + List, + Optional, + Tuple, +) +from pydantic import BaseModel +from pydantic.fields import FieldInfo + +from .metadata import ( + SecurityMetadata, + find_field_metadata, +) +import os + + +def get_security(security: Any) -> Tuple[Dict[str, str], Dict[str, List[str]]]: + headers: Dict[str, str] = {} + query_params: Dict[str, List[str]] = {} + + if security is None: + return headers, query_params + + if not isinstance(security, BaseModel): + raise TypeError("security must be a pydantic model") + + sec_fields: Dict[str, FieldInfo] = security.__class__.model_fields + for name in sec_fields: + sec_field = sec_fields[name] + + value = getattr(security, name) + if value is None: + continue + + metadata = find_field_metadata(sec_field, SecurityMetadata) + if metadata is None: + continue + if metadata.option: + _parse_security_option(headers, query_params, value) + return headers, query_params + if metadata.scheme: + # Special case for basic auth or custom auth which could be a flattened model + if metadata.sub_type in ["basic", "custom"] and not isinstance( + value, BaseModel + ): + _parse_security_scheme(headers, query_params, metadata, name, security) + else: + _parse_security_scheme(headers, query_params, metadata, name, value) + + return headers, query_params + + +def get_security_from_env(security: Any, security_class: Any) -> Optional[BaseModel]: + if security is not None: + return security + + if not issubclass(security_class, BaseModel): + raise TypeError("security_class must be a pydantic model class") + + security_dict: Any = {} + + if os.getenv("OPENROUTER_API_KEY"): + security_dict["api_key"] = os.getenv("OPENROUTER_API_KEY") + + return security_class(**security_dict) if security_dict else None + + +def _parse_security_option( + headers: Dict[str, str], query_params: Dict[str, List[str]], option: Any +): + if not isinstance(option, BaseModel): + raise TypeError("security option must be a pydantic model") + + opt_fields: Dict[str, FieldInfo] = option.__class__.model_fields + for name in opt_fields: + opt_field = opt_fields[name] + + metadata = find_field_metadata(opt_field, SecurityMetadata) + if metadata is None or not metadata.scheme: + continue + _parse_security_scheme( + headers, query_params, metadata, name, getattr(option, name) + ) + + +def _parse_security_scheme( + headers: Dict[str, str], + query_params: Dict[str, List[str]], + scheme_metadata: SecurityMetadata, + field_name: str, + scheme: Any, +): + scheme_type = scheme_metadata.scheme_type + sub_type = scheme_metadata.sub_type + + if isinstance(scheme, BaseModel): + if scheme_type == "http": + if sub_type == "basic": + _parse_basic_auth_scheme(headers, scheme) + return + if sub_type == "custom": + return + + scheme_fields: Dict[str, FieldInfo] = scheme.__class__.model_fields + for name in scheme_fields: + scheme_field = scheme_fields[name] + + metadata = find_field_metadata(scheme_field, SecurityMetadata) + if metadata is None or metadata.field_name is None: + continue + + value = getattr(scheme, name) + + _parse_security_scheme_value( + headers, query_params, scheme_metadata, metadata, name, value + ) + else: + _parse_security_scheme_value( + headers, query_params, scheme_metadata, scheme_metadata, field_name, scheme + ) + + +def _parse_security_scheme_value( + headers: Dict[str, str], + query_params: Dict[str, List[str]], + scheme_metadata: SecurityMetadata, + security_metadata: SecurityMetadata, + field_name: str, + value: Any, +): + scheme_type = scheme_metadata.scheme_type + sub_type = scheme_metadata.sub_type + + header_name = security_metadata.get_field_name(field_name) + + if scheme_type == "apiKey": + if sub_type == "header": + headers[header_name] = value + elif sub_type == "query": + query_params[header_name] = [value] + else: + raise ValueError("sub type {sub_type} not supported") + elif scheme_type == "openIdConnect": + headers[header_name] = _apply_bearer(value) + elif scheme_type == "oauth2": + if sub_type != "client_credentials": + headers[header_name] = _apply_bearer(value) + elif scheme_type == "http": + if sub_type == "bearer": + headers[header_name] = _apply_bearer(value) + elif sub_type == "custom": + return + else: + raise ValueError("sub type {sub_type} not supported") + else: + raise ValueError("scheme type {scheme_type} not supported") + + +def _apply_bearer(token: str) -> str: + return token.lower().startswith("bearer ") and token or f"Bearer {token}" + + +def _parse_basic_auth_scheme(headers: Dict[str, str], scheme: Any): + username = "" + password = "" + + if not isinstance(scheme, BaseModel): + raise TypeError("basic auth scheme must be a pydantic model") + + scheme_fields: Dict[str, FieldInfo] = scheme.__class__.model_fields + for name in scheme_fields: + scheme_field = scheme_fields[name] + + metadata = find_field_metadata(scheme_field, SecurityMetadata) + if metadata is None or metadata.field_name is None: + continue + + field_name = metadata.field_name + value = getattr(scheme, name) + + if field_name == "username": + username = value + if field_name == "password": + password = value + + data = f"{username}:{password}".encode() + headers["Authorization"] = f"Basic {base64.b64encode(data).decode()}" diff --git a/src/openrouter/utils/serializers.py b/src/openrouter/utils/serializers.py new file mode 100644 index 0000000..378a14c --- /dev/null +++ b/src/openrouter/utils/serializers.py @@ -0,0 +1,249 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from decimal import Decimal +import functools +import json +import typing +from typing import Any, Dict, List, Tuple, Union, get_args +import typing_extensions +from typing_extensions import get_origin + +import httpx +from pydantic import ConfigDict, create_model +from pydantic_core import from_json + +from ..types.basemodel import BaseModel, Nullable, OptionalNullable, Unset + + +def serialize_decimal(as_str: bool): + def serialize(d): + # Optional[T] is a Union[T, None] + if is_union(type(d)) and type(None) in get_args(type(d)) and d is None: + return None + if isinstance(d, Unset): + return d + + if not isinstance(d, Decimal): + raise ValueError("Expected Decimal object") + + return str(d) if as_str else float(d) + + return serialize + + +def validate_decimal(d): + if d is None: + return None + + if isinstance(d, (Decimal, Unset)): + return d + + if not isinstance(d, (str, int, float)): + raise ValueError("Expected string, int or float") + + return Decimal(str(d)) + + +def serialize_float(as_str: bool): + def serialize(f): + # Optional[T] is a Union[T, None] + if is_union(type(f)) and type(None) in get_args(type(f)) and f is None: + return None + if isinstance(f, Unset): + return f + + if not isinstance(f, float): + raise ValueError("Expected float") + + return str(f) if as_str else f + + return serialize + + +def validate_float(f): + if f is None: + return None + + if isinstance(f, (float, Unset)): + return f + + if not isinstance(f, str): + raise ValueError("Expected string") + + return float(f) + + +def serialize_int(as_str: bool): + def serialize(i): + # Optional[T] is a Union[T, None] + if is_union(type(i)) and type(None) in get_args(type(i)) and i is None: + return None + if isinstance(i, Unset): + return i + + if not isinstance(i, int): + raise ValueError("Expected int") + + return str(i) if as_str else i + + return serialize + + +def validate_int(b): + if b is None: + return None + + if isinstance(b, (int, Unset)): + return b + + if not isinstance(b, str): + raise ValueError("Expected string") + + return int(b) + + +def validate_open_enum(is_int: bool): + def validate(e): + if e is None: + return None + + if isinstance(e, Unset): + return e + + if is_int: + if not isinstance(e, int): + raise ValueError("Expected int") + else: + if not isinstance(e, str): + raise ValueError("Expected string") + + return e + + return validate + + +def validate_const(v): + def validate(c): + # Optional[T] is a Union[T, None] + if is_union(type(c)) and type(None) in get_args(type(c)) and c is None: + return None + + if v != c: + raise ValueError(f"Expected {v}") + + return c + + return validate + + +def unmarshal_json(raw, typ: Any) -> Any: + return unmarshal(from_json(raw), typ) + + +def unmarshal(val, typ: Any) -> Any: + unmarshaller = create_model( + "Unmarshaller", + body=(typ, ...), + __config__=ConfigDict(populate_by_name=True, arbitrary_types_allowed=True), + ) + + m = unmarshaller(body=val) + + # pyright: ignore[reportAttributeAccessIssue] + return m.body # type: ignore + + +def marshal_json(val, typ): + if is_nullable(typ) and val is None: + return "null" + + marshaller = create_model( + "Marshaller", + body=(typ, ...), + __config__=ConfigDict(populate_by_name=True, arbitrary_types_allowed=True), + ) + + m = marshaller(body=val) + + d = m.model_dump(by_alias=True, mode="json", exclude_none=True) + + if len(d) == 0: + return "" + + return json.dumps(d[next(iter(d))], separators=(",", ":")) + + +def is_nullable(field): + origin = get_origin(field) + if origin is Nullable or origin is OptionalNullable: + return True + + if not origin is Union or type(None) not in get_args(field): + return False + + for arg in get_args(field): + if get_origin(arg) is Nullable or get_origin(arg) is OptionalNullable: + return True + + return False + + +def is_union(obj: object) -> bool: + """ + Returns True if the given object is a typing.Union or typing_extensions.Union. + """ + return any( + obj is typing_obj for typing_obj in _get_typing_objects_by_name_of("Union") + ) + + +def stream_to_text(stream: httpx.Response) -> str: + return "".join(stream.iter_text()) + + +async def stream_to_text_async(stream: httpx.Response) -> str: + return "".join([chunk async for chunk in stream.aiter_text()]) + + +def stream_to_bytes(stream: httpx.Response) -> bytes: + return stream.content + + +async def stream_to_bytes_async(stream: httpx.Response) -> bytes: + return await stream.aread() + + +def get_pydantic_model(data: Any, typ: Any) -> Any: + if not _contains_pydantic_model(data): + return unmarshal(data, typ) + + return data + + +def _contains_pydantic_model(data: Any) -> bool: + if isinstance(data, BaseModel): + return True + if isinstance(data, List): + return any(_contains_pydantic_model(item) for item in data) + if isinstance(data, Dict): + return any(_contains_pydantic_model(value) for value in data.values()) + + return False + + +@functools.cache +def _get_typing_objects_by_name_of(name: str) -> Tuple[Any, ...]: + """ + Get typing objects by name from typing and typing_extensions. + Reference: https://typing-extensions.readthedocs.io/en/latest/#runtime-use-of-types + """ + result = tuple( + getattr(module, name) + for module in (typing, typing_extensions) + if hasattr(module, name) + ) + if not result: + raise ValueError( + f"Neither typing nor typing_extensions has an object called {name!r}" + ) + return result diff --git a/src/openrouter/utils/unmarshal_json_response.py b/src/openrouter/utils/unmarshal_json_response.py new file mode 100644 index 0000000..079836c --- /dev/null +++ b/src/openrouter/utils/unmarshal_json_response.py @@ -0,0 +1,24 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from typing import Any, Optional + +import httpx + +from .serializers import unmarshal_json +from openrouter import errors + + +def unmarshal_json_response( + typ: Any, http_res: httpx.Response, body: Optional[str] = None +) -> Any: + if body is None: + body = http_res.text + try: + return unmarshal_json(body, typ) + except Exception as e: + raise errors.ResponseValidationError( + "Response validation failed", + http_res, + e, + body, + ) from e diff --git a/src/openrouter/utils/url.py b/src/openrouter/utils/url.py new file mode 100644 index 0000000..c78ccba --- /dev/null +++ b/src/openrouter/utils/url.py @@ -0,0 +1,155 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from decimal import Decimal +from typing import ( + Any, + Dict, + get_type_hints, + List, + Optional, + Union, + get_args, + get_origin, +) +from pydantic import BaseModel +from pydantic.fields import FieldInfo + +from .metadata import ( + PathParamMetadata, + find_field_metadata, +) +from .values import ( + _get_serialized_params, + _is_set, + _populate_from_globals, + _val_to_string, +) + + +def generate_url( + server_url: str, + path: str, + path_params: Any, + gbls: Optional[Any] = None, +) -> str: + path_param_values: Dict[str, str] = {} + + globals_already_populated = _populate_path_params( + path_params, gbls, path_param_values, [] + ) + if _is_set(gbls): + _populate_path_params(gbls, None, path_param_values, globals_already_populated) + + for key, value in path_param_values.items(): + path = path.replace("{" + key + "}", value, 1) + + return remove_suffix(server_url, "/") + path + + +def _populate_path_params( + path_params: Any, + gbls: Any, + path_param_values: Dict[str, str], + skip_fields: List[str], +) -> List[str]: + globals_already_populated: List[str] = [] + + if not isinstance(path_params, BaseModel): + return globals_already_populated + + path_param_fields: Dict[str, FieldInfo] = path_params.__class__.model_fields + path_param_field_types = get_type_hints(path_params.__class__) + for name in path_param_fields: + if name in skip_fields: + continue + + field = path_param_fields[name] + + param_metadata = find_field_metadata(field, PathParamMetadata) + if param_metadata is None: + continue + + param = getattr(path_params, name) if _is_set(path_params) else None + param, global_found = _populate_from_globals( + name, param, PathParamMetadata, gbls + ) + if global_found: + globals_already_populated.append(name) + + if not _is_set(param): + continue + + f_name = field.alias if field.alias is not None else name + serialization = param_metadata.serialization + if serialization is not None: + serialized_params = _get_serialized_params( + param_metadata, f_name, param, path_param_field_types[name] + ) + for key, value in serialized_params.items(): + path_param_values[key] = value + else: + pp_vals: List[str] = [] + if param_metadata.style == "simple": + if isinstance(param, List): + for pp_val in param: + if not _is_set(pp_val): + continue + pp_vals.append(_val_to_string(pp_val)) + path_param_values[f_name] = ",".join(pp_vals) + elif isinstance(param, Dict): + for pp_key in param: + if not _is_set(param[pp_key]): + continue + if param_metadata.explode: + pp_vals.append(f"{pp_key}={_val_to_string(param[pp_key])}") + else: + pp_vals.append(f"{pp_key},{_val_to_string(param[pp_key])}") + path_param_values[f_name] = ",".join(pp_vals) + elif not isinstance(param, (str, int, float, complex, bool, Decimal)): + param_fields: Dict[str, FieldInfo] = param.__class__.model_fields + for name in param_fields: + param_field = param_fields[name] + + param_value_metadata = find_field_metadata( + param_field, PathParamMetadata + ) + if param_value_metadata is None: + continue + + param_name = ( + param_field.alias if param_field.alias is not None else name + ) + + param_field_val = getattr(param, name) + if not _is_set(param_field_val): + continue + if param_metadata.explode: + pp_vals.append( + f"{param_name}={_val_to_string(param_field_val)}" + ) + else: + pp_vals.append( + f"{param_name},{_val_to_string(param_field_val)}" + ) + path_param_values[f_name] = ",".join(pp_vals) + elif _is_set(param): + path_param_values[f_name] = _val_to_string(param) + + return globals_already_populated + + +def is_optional(field): + return get_origin(field) is Union and type(None) in get_args(field) + + +def template_url(url_with_params: str, params: Dict[str, str]) -> str: + for key, value in params.items(): + url_with_params = url_with_params.replace("{" + key + "}", value) + + return url_with_params + + +def remove_suffix(input_string, suffix): + if suffix and input_string.endswith(suffix): + return input_string[: -len(suffix)] + return input_string diff --git a/src/openrouter/utils/values.py b/src/openrouter/utils/values.py new file mode 100644 index 0000000..dae01a4 --- /dev/null +++ b/src/openrouter/utils/values.py @@ -0,0 +1,137 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from datetime import datetime +from enum import Enum +from email.message import Message +from functools import partial +import os +from typing import Any, Callable, Dict, List, Optional, Tuple, TypeVar, Union, cast + +from httpx import Response +from pydantic import BaseModel +from pydantic.fields import FieldInfo + +from ..types.basemodel import Unset + +from .serializers import marshal_json + +from .metadata import ParamMetadata, find_field_metadata + + +def match_content_type(content_type: str, pattern: str) -> bool: + if pattern in (content_type, "*", "*/*"): + return True + + msg = Message() + msg["content-type"] = content_type + media_type = msg.get_content_type() + + if media_type == pattern: + return True + + parts = media_type.split("/") + if len(parts) == 2: + if pattern in (f"{parts[0]}/*", f"*/{parts[1]}"): + return True + + return False + + +def match_status_codes(status_codes: List[str], status_code: int) -> bool: + if "default" in status_codes: + return True + + for code in status_codes: + if code == str(status_code): + return True + + if code.endswith("XX") and code.startswith(str(status_code)[:1]): + return True + return False + + +T = TypeVar("T") + +def cast_partial(typ): + return partial(cast, typ) + +def get_global_from_env( + value: Optional[T], env_key: str, type_cast: Callable[[str], T] +) -> Optional[T]: + if value is not None: + return value + env_value = os.getenv(env_key) + if env_value is not None: + try: + return type_cast(env_value) + except ValueError: + pass + return None + + +def match_response( + response: Response, code: Union[str, List[str]], content_type: str +) -> bool: + codes = code if isinstance(code, list) else [code] + return match_status_codes(codes, response.status_code) and match_content_type( + response.headers.get("content-type", "application/octet-stream"), content_type + ) + + +def _populate_from_globals( + param_name: str, value: Any, param_metadata_type: type, gbls: Any +) -> Tuple[Any, bool]: + if gbls is None: + return value, False + + if not isinstance(gbls, BaseModel): + raise TypeError("globals must be a pydantic model") + + global_fields: Dict[str, FieldInfo] = gbls.__class__.model_fields + found = False + for name in global_fields: + field = global_fields[name] + if name is not param_name: + continue + + found = True + + if value is not None: + return value, True + + global_value = getattr(gbls, name) + + param_metadata = find_field_metadata(field, param_metadata_type) + if param_metadata is None: + return value, True + + return global_value, True + + return value, found + + +def _val_to_string(val) -> str: + if isinstance(val, bool): + return str(val).lower() + if isinstance(val, datetime): + return str(val.isoformat().replace("+00:00", "Z")) + if isinstance(val, Enum): + return str(val.value) + + return str(val) + + +def _get_serialized_params( + metadata: ParamMetadata, field_name: str, obj: Any, typ: type +) -> Dict[str, str]: + params: Dict[str, str] = {} + + serialization = metadata.serialization + if serialization == "json": + params[field_name] = marshal_json(obj, typ) + + return params + + +def _is_set(value: Any) -> bool: + return value is not None and not isinstance(value, Unset)